Wassim SAMAD 1419709131
editor: structure build-start/end cues + menu hover/click SFX (#378)
* wip sfx

* wip audios

* feat(editor): structure build-start/end cues + menu hover/click SFX

Sound design pass for the build/items experience:

- Split structure-build into a start cue (draft begins) and end cue
  (commit). Wall/fence fire start on the first click; slab/ceiling/zone
  tick start on every non-closing vertex; roof on the first corner.
- Doors and windows now use the structure-end cue on place + move;
  shelves use item-place instead.
- New menu_hover (round-robin retired in favour of a single sample) and
  menu_click cues wired to the Build/Items main categories, item-catalog
  tiles, the icon rail / tab bar, and the bottom action menu (via the
  shared ActionButton).
- Refresh item_pick / item_place / item_rotate samples; drop the
  now-unused numbered menu_hover variations.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(editor): silence forEach return lint in updateSFXVolumes

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(editor): convert SFX wavs to mp3 to shrink assets

Re-encode all SFX samples as 128kbps mp3 (~94% smaller, transparent for
short UI cues) and point the player at the .mp3 sources. Drops the .wav
originals; the freshly converted item_pick/place/rotate.mp3 override the
older committed mp3s.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-06 20:15:24 -04:00

393 lines
12 KiB
TypeScript

import {
type AnyNode,
type AnyNodeId,
collectAlignmentAnchors,
emitter,
type GridEvent,
type LevelNode,
RoofNode,
RoofSegmentNode,
resolveAlignment,
sceneRegistry,
useAlignmentGuides,
useScene,
} from '@pascal-app/core'
import { useViewer } from '@pascal-app/viewer'
import { useEffect, useMemo, useRef, useState } from 'react'
import * as THREE from 'three'
import { BufferGeometry, DoubleSide, type Group, type Line, Vector3 } from 'three'
import { markToolCancelConsumed } from '../../../hooks/use-keyboard'
import { EDITOR_LAYER } from '../../../lib/constants'
import { sfxEmitter } from '../../../lib/sfx-bus'
import useEditor from '../../../store/use-editor'
import { CursorSphere } from '../shared/cursor-sphere'
const DEFAULT_WALL_HEIGHT = 0.5
const DEFAULT_PITCH_DEG = 40
const GRID_OFFSET = 0.02
/** Figma-style alignment-snap threshold (meters), matching the move tools. */
const ALIGNMENT_THRESHOLD_M = 0.08
/**
* Creates a roof group with one default gable segment
*/
const commitRoofPlacement = (
levelId: LevelNode['id'],
corner1: [number, number, number],
corner2: [number, number, number],
selectedIds: string[],
): AnyNode['id'] => {
const { createNode, createNodes, nodes } = useScene.getState()
// A placed roof preset seeds `toolDefaults.roof` with the flattened
// subtree params (roofType, pitch, wallHeight, overhang, materials, …)
// before the tool activates. The footprint (width/depth) and placement
// come from the drawn rectangle and always win; the segment carries the
// shape/material params, the roof container picks up the materials.
const defaults = useEditor.getState().toolDefaults.roof ?? {}
const centerX = (corner1[0] + corner2[0]) / 2
const centerZ = (corner1[2] + corner2[2]) / 2
const width = Math.max(Math.abs(corner2[0] - corner1[0]), 1)
const depth = Math.max(Math.abs(corner2[2] - corner1[2]), 1)
// Determine if there is an active roof node we should add to
let targetRoofId: RoofNode['id'] | null = null
const selectedId = selectedIds[0]
if (selectedIds.length === 1 && selectedId) {
const selectedNode = nodes[selectedId as AnyNodeId]
if (selectedNode?.type === 'roof') {
targetRoofId = selectedNode.id
} else if (selectedNode?.type === 'roof-segment' && selectedNode.parentId) {
targetRoofId = selectedNode.parentId as RoofNode['id']
}
}
if (targetRoofId) {
const targetRoof = nodes[targetRoofId] as RoofNode
let localX = centerX
let localZ = centerZ
// Convert world coordinates to the local space of the parent roof
const targetObj = sceneRegistry.nodes.get(targetRoofId)
if (targetObj) {
const worldVec = new THREE.Vector3(centerX, 0, centerZ)
targetObj.worldToLocal(worldVec)
localX = worldVec.x
localZ = worldVec.z
} else {
// Math fallback if mesh isn't ready
const dx = centerX - targetRoof.position[0]
const dz = centerZ - targetRoof.position[2]
const angle = -targetRoof.rotation
localX = dx * Math.cos(angle) - dz * Math.sin(angle)
localZ = dx * Math.sin(angle) + dz * Math.cos(angle)
}
const segment = RoofSegmentNode.parse({
wallHeight: DEFAULT_WALL_HEIGHT,
pitch: DEFAULT_PITCH_DEG,
roofType: 'gable',
...defaults,
width,
depth,
position: [localX, 0, localZ],
})
createNode(segment, targetRoofId as AnyNode['id'])
sfxEmitter.emit('sfx:structure-build')
return segment.id // Returns segment ID so it can be selected immediately
}
// Count existing roofs for naming
const roofCount = Object.values(nodes).filter((n) => n.type === 'roof').length
const name = `Roof ${roofCount + 1}`
// Create the segment first (centered in its new parent)
const segment = RoofSegmentNode.parse({
wallHeight: DEFAULT_WALL_HEIGHT,
pitch: DEFAULT_PITCH_DEG,
roofType: 'gable',
...defaults,
width,
depth,
position: [0, 0, 0],
})
// Create the roof container. Segment-shaped params (roofType, pitch, …) are
// dropped by the RoofNode schema; surface materials in `defaults` carry over.
const roof = RoofNode.parse({
...defaults,
name,
position: [centerX, 0, centerZ],
children: [segment.id],
})
// Create roof first (so segment can be parented to it), then segment
createNodes([
{ node: roof, parentId: levelId },
{ node: segment, parentId: roof.id },
])
sfxEmitter.emit('sfx:structure-build')
return roof.id
}
type PreviewState = {
corner1: [number, number, number] | null
cursorPosition: [number, number, number]
levelY: number
}
export const RoofTool: React.FC = () => {
const cursorRef = useRef<Group>(null)
const outlineRef = useRef<Line>(null!)
const currentLevelId = useViewer((state) => state.selection.levelId)
const selectedIds = useViewer((state) => state.selection.selectedIds)
const setSelection = useViewer((state) => state.setSelection)
const setTool = useEditor((state) => state.setTool)
const setMode = useEditor((state) => state.setMode)
const selectedIdsRef = useRef(selectedIds)
useEffect(() => {
selectedIdsRef.current = selectedIds
}, [selectedIds])
// Clear preset-seeded defaults on deactivation so a later manual roof draw
// isn't built with a stale preset's parameters. Unmount-only.
useEffect(() => () => useEditor.getState().setToolDefaults('roof', null), [])
const corner1Ref = useRef<[number, number, number] | null>(null)
const previousGridPosRef = useRef<[number, number] | null>(null)
const [preview, setPreview] = useState<PreviewState>({
corner1: null,
cursorPosition: [0, 0, 0],
levelY: 0,
})
useEffect(() => {
if (!currentLevelId) return
outlineRef.current.geometry = new BufferGeometry()
// Alignment candidates — anchors of every alignable object; refreshed
// after each roof commits. Both corners of the rectangle align.
let alignmentCandidates = collectAlignmentAnchors(useScene.getState().nodes, '', currentLevelId)
// Snap the drafted corner onto another object's nearest real anchor and
// publish the guide. The probe is the RAW cursor, NOT the 0.5m-grid-snapped
// point: resolving against the grid point would only ever catch anchors
// that happen to sit on a grid line, so off-grid items (furniture, angled
// walls) would never surface a guide. The matched axis locks exactly to the
// candidate's coordinate; the other axis keeps its grid snap. Alt bypasses.
const alignPoint = (
gridX: number,
gridZ: number,
rawX: number,
rawZ: number,
bypass: boolean,
): [number, number] => {
if (bypass || alignmentCandidates.length === 0) {
useAlignmentGuides.getState().clear()
return [gridX, gridZ]
}
const ar = resolveAlignment({
moving: [{ nodeId: '__roof-draft__', kind: 'corner', x: rawX, z: rawZ }],
candidates: alignmentCandidates,
threshold: ALIGNMENT_THRESHOLD_M,
})
if (ar.guides.length === 0) {
useAlignmentGuides.getState().clear()
return [gridX, gridZ]
}
useAlignmentGuides.getState().set(ar.guides)
let x = gridX
let z = gridZ
for (const guide of ar.guides) {
if (guide.axis === 'x') x = guide.coord
else z = guide.coord
}
return [x, z]
}
const updateOutline = (
corner1: [number, number, number],
corner2: [number, number, number],
) => {
const gridY = corner1[1] + GRID_OFFSET
const groundPoints = [
new Vector3(corner1[0], gridY, corner1[2]),
new Vector3(corner2[0], gridY, corner1[2]),
new Vector3(corner2[0], gridY, corner2[2]),
new Vector3(corner1[0], gridY, corner2[2]),
new Vector3(corner1[0], gridY, corner1[2]),
]
outlineRef.current.geometry.dispose()
outlineRef.current.geometry = new BufferGeometry().setFromPoints(groundPoints)
outlineRef.current.visible = true
}
const onGridMove = (event: GridEvent) => {
if (!cursorRef.current) return
const [gridX, gridZ] = alignPoint(
Math.round(event.localPosition[0] * 2) / 2,
Math.round(event.localPosition[2] * 2) / 2,
event.localPosition[0],
event.localPosition[2],
event.nativeEvent?.altKey === true,
)
const y = event.localPosition[1]
const cursorPosition: [number, number, number] = [gridX, y, gridZ]
const gridY = y + GRID_OFFSET
cursorRef.current.position.set(gridX, gridY, gridZ)
if (
corner1Ref.current &&
previousGridPosRef.current &&
(gridX !== previousGridPosRef.current[0] || gridZ !== previousGridPosRef.current[1])
) {
sfxEmitter.emit('sfx:grid-snap')
}
previousGridPosRef.current = [gridX, gridZ]
setPreview({
corner1: corner1Ref.current,
cursorPosition,
levelY: y,
})
if (corner1Ref.current) {
updateOutline(corner1Ref.current, cursorPosition)
}
}
const onGridClick = (event: GridEvent) => {
if (!currentLevelId) return
const [gridX, gridZ] = alignPoint(
Math.round(event.localPosition[0] * 2) / 2,
Math.round(event.localPosition[2] * 2) / 2,
event.localPosition[0],
event.localPosition[2],
event.nativeEvent?.altKey === true,
)
const y = event.localPosition[1]
if (corner1Ref.current) {
const roofId = commitRoofPlacement(
currentLevelId,
corner1Ref.current,
[gridX, y, gridZ],
selectedIdsRef.current,
)
setSelection({ selectedIds: [roofId as AnyNode['id']] })
corner1Ref.current = null
outlineRef.current.visible = false
alignmentCandidates = collectAlignmentAnchors(useScene.getState().nodes, '', currentLevelId)
useAlignmentGuides.getState().clear()
} else {
corner1Ref.current = [gridX, y, gridZ]
sfxEmitter.emit('sfx:structure-build-start')
setPreview((prev) => ({
...prev,
corner1: corner1Ref.current,
}))
}
}
const onCancel = () => {
if (corner1Ref.current) {
markToolCancelConsumed()
corner1Ref.current = null
outlineRef.current.visible = false
setPreview((prev) => ({ ...prev, corner1: null }))
}
useAlignmentGuides.getState().clear()
}
emitter.on('grid:move', onGridMove)
emitter.on('grid:click', onGridClick)
emitter.on('tool:cancel', onCancel)
return () => {
emitter.off('grid:move', onGridMove)
emitter.off('grid:click', onGridClick)
emitter.off('tool:cancel', onCancel)
useAlignmentGuides.getState().clear()
corner1Ref.current = null
}
}, [currentLevelId, setSelection])
const { corner1, cursorPosition, levelY } = preview
const previewDimensions = useMemo(() => {
if (!corner1) return null
const length = Math.abs(cursorPosition[0] - corner1[0])
const width = Math.abs(cursorPosition[2] - corner1[2])
const centerX = (corner1[0] + cursorPosition[0]) / 2
const centerZ = (corner1[2] + cursorPosition[2]) / 2
return { length, width, centerX, centerZ }
}, [corner1, cursorPosition])
return (
<group>
<CursorSphere ref={cursorRef} />
{/* @ts-ignore */}
<line
frustumCulled={false}
layers={EDITOR_LAYER}
// @ts-expect-error
ref={outlineRef}
renderOrder={1}
visible={false}
>
<bufferGeometry />
<lineBasicNodeMaterial
color="#818cf8"
depthTest={false}
depthWrite={false}
linewidth={2}
opacity={0.3}
transparent
/>
</line>
{corner1 && (
<CursorSphere
color="#818cf8"
position={[corner1[0], levelY + GRID_OFFSET, corner1[2]]}
showTooltip={false}
/>
)}
{previewDimensions && previewDimensions.length > 0.1 && previewDimensions.width > 0.1 && (
<mesh
layers={EDITOR_LAYER}
position={[previewDimensions.centerX, levelY + GRID_OFFSET, previewDimensions.centerZ]}
rotation={[-Math.PI / 2, 0, 0]}
>
<planeGeometry args={[previewDimensions.length, previewDimensions.width]} />
<meshBasicMaterial
color="#818cf8"
depthTest={false}
depthWrite={false}
opacity={0.1}
side={DoubleSide}
transparent
/>
</mesh>
)}
</group>
)
}