Always-visible placement ghosts + true-nearest 2D opening snap (#407)

* feat(editor): always-visible translucent placement ghost for openings + roof accessories

When a host-surface placement tool is armed, the node's real geometry now
follows the cursor everywhere as a translucent ghost: tinted invalid (red)
and unconfirmable off-host, snapping onto its host surface (wall/roof) with
the existing valid/invalid affordances when near. This replaces the old red
wireframe box (door/window) and red DragBoundingBox (roof accessories), so
the armed tool is visible before the cursor reaches a placeable surface.

- New shared `applyGhost` helper (nodes/src/shared/ghost-materials.ts):
  clones materials, disables raycast (avoids cursor-ray starvation),
  tints invalid; cleanup disposes only the clones.
- New door/window preview components built from the real geometry via new
  `buildDoorPreviewMesh`/`buildWindowPreviewMesh` viewer exports; tools float
  the ghost via a `fallbackPose` that is mutually exclusive with the on-host
  draft + wireframe outline.
- `RoofAttachmentFallbackPreview` gains a `ghost` prop; all 11 roof-accessory
  tools pass their real preview (invalid-tinted) instead of a box `size`.

Snapping behavior is unchanged (no proximity snap yet).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(editor): magnetic proximity wall-snap for door/window placement

The door/window ghost now follows the cursor over the floor like a moving
item and magnetically snaps onto the nearest wall within range (1.5 m), then
releases back to free-follow when the cursor moves away — instead of only
attaching on a direct wall-mesh ray hit. A grid-snap sound plays each time it
snaps onto a new spot, so it reads as moving a physical object that can only
land on walls.

- Plan-space proximity via the existing `findClosestWallInPlan` (the same
  helper the 2D floor-plan move uses): level-scoped, skips curved walls,
  returns wall + along-wall localX + side + wall-local rotation.
- `grid:move` drives the snap and `grid:click` commits when proximity-snapped;
  a direct wall-mesh hover (wall:enter/move) still owns the precise face side.
  Both paths share `applyWallTarget` (create the draft once, reparent only on
  an actual wall change) and a shared commit that refreshes alignment anchors.
- Disambiguation without a stuck flag: a per-pointermove `timeStamp` gate
  (R3F + the grid raycast share the source DOM event) plus a `cameraDragging`
  guard and stale-`hostKind` reset, so a missed wall:leave during a camera
  orbit can't strand the draft.
- Window keeps its sill height on the floor path (the floor cursor carries no
  wall-face Y) — defaults to a ~0.9 m sill, mirroring the 2D move.
- Shift bypasses the along-wall grid/alignment snap but still attaches to the
  nearest wall, matching the 3D-hover and 2D-move conventions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): door/window preset placement follows the cursor over open floor

The community preset/catalog flow places doors and windows through the
isNew move path (MoveDoorTool / MoveWindowTool), which had no free-follow:
the fresh clone was parented to the level at the origin and only became
visible once the cursor reached a wall, so over empty floor nothing tracked
the cursor. Now the move tools mirror the def.tool placement behaviour:

- Off-wall, the real node rides the cursor like an item (reparented to the
  level, positioned at the building-local cursor) so it's obvious what's
  being placed before it attaches.
- Within range of a wall it magnetically snaps on via findClosestWallInPlan
  (the same plan-space helper the 2D move uses), releasing back to free-follow
  when the cursor moves away, and plays the grid-snap sound on each new snap.
- grid:click commits only when snapped (open floor is a no-op — a door/window
  needs a wall); the wall/roof mesh-hover paths are unchanged and still own
  their own click. A per-pointermove timeStamp gate + cameraDragging guard
  keep the floor handler from fighting a wall/roof hover.
- Windows default to a ~0.9m sill while off-wall (fresh preset clones carry
  position [0,0,0], which buried half the window below the floor).

The wall/roof commit body is extracted into a shared commitToWall so the
mesh-click and proximity-click paths stay identical. Existing-node moves are
fully restored on cancel/unmount (the node stays isTransient through
free-follow). Standalone-editor def.tool placement already had this in a
prior commit; this brings the community move path to parity.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(editor): 2D floorplan ghost follows the cursor for door/window placement

Mirrors the 3D free-follow in the top-down floor plan: while placing a door
or window, a loose footprint rectangle now follows the cursor over open floor
so it's obvious what's being placed before it snaps to a wall. The instant the
cursor nears a wall, the existing synthesized wall:enter/move path takes over
and the real on-wall door/window symbol (swing arc, etc.) replaces the ghost.

- The opening-placement pointer-move handler in floorplan-panel sets a new
  `openingGhostPoint` on the off-wall (findClosestWallPoint miss) branch and
  clears it on a wall hit; a loose width × 0.1m rectangle renders at that point
  inside the floor-plan scene group (same world→SVG transform as every glyph).
- Width comes from the moving node or the kind default (door 0.9 / window 1.5).
- The ghost clears when opening placement ends (tool/mode change, cancel,
  commit) and on level change, so no stale rectangle lingers.

Deliberately a plain rectangle, not the full swing-arc symbol: off-wall there's
no host to orient the swing to. The shared door/window def.floorplan builders
are untouched — overloading them with a wall-less fallback would make
roof-hosted doors (parent is a roof segment, builder returns null today) draw
stray rectangles in plan. Keeping the preview in the editor layer avoids that.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(editor): faithful 2D door/window ghost, 2D wall-slide, R-flip during placement; 3D snap only on hover

Three placement fixes plus a snapping revision, for both the standalone
def.tool path and the community isNew move path (door + window):

- 2D faithful ghost: the off-wall placement ghost now renders the real
  blueprint symbol (door swing arc / window panes) following the cursor, not a
  bare rectangle. Done by publishing a transient opening on a synthetic wall to
  usePlacementPreview (extended with a `parentNode` fed as the builder's
  ctx.parent) so the real def.floorplan builder draws it. Cleared on wall-hit,
  on commit, on placement-inactive, and on level change.
- 2D slide-along-wall: the floor-plan registry layer ignored useLiveTransforms
  for door/window (only floor-placed + slab/ceiling/zone), so a same-wall slide
  updated the 3D mesh but left the 2D symbol frozen. It now merges the
  wall-local live position/rotation onto the node (keeping parentId) so the 2D
  symbol slides with the cursor.
- R-flip during placement: pressing R now flips a door/window's facing
  (front ↔ back, rotation += π) before commit — the placement tools own R while
  placing (the global selection-based R/T handler stands down via
  isPlacingOpening so it can't double-fire). No-op on roof faces (front-only).
- 3D snapping zero-padding: removed the 1.5 m proximity magnet; in 3D the
  opening free-follows the cursor over open floor and snaps only when the cursor
  ray actually hovers a wall/roof mesh (big raycast targets). 2D keeps its
  0.5 m findClosestWallPoint padding since plan walls are thin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): make FloorplanRegistryMoveOverlay the sole 2D owner of door/window placement

Community door/window placement (movingNode + metadata.isNew) had TWO 2D paths
running at once: the floorplan-panel synthesized wall:*/grid:* events (driving
the 3D MoveDoorTool) AND FloorplanRegistryMoveOverlay via def.floorplanMoveTarget.
They fought — R didn't flip the 2D symbol and clicks didn't commit in 2D, while
3D worked. The overlay + floorplanMoveTarget is the purpose-built 2D owner
(faithful def.floorplan symbol, plan-space CTM coords, Figma snap, single-undo
commit), so it now owns 2D opening placement when movingNode is set:

- floorplan-panel: the opening pointer-move branch + the registry grid catch-all
  + the background-click catch-all all now exclude the door/window MOVE case
  (`!isOpeningMoveActive`), so the synthesized events no longer fire for it (they
  still drive pure raw-build placement, which has no movingNode). Without the
  catch-all exclusions the move case fell through to grid:move/grid:click, which
  re-drove the 3D tool's free-follow and consumed the commit click.
- R-flip in 2D: `FloorplanMoveTargetSession` gains optional `flipSide()`;
  door/window floorplan-move implement it (XOR the wall-derived side + π rotation,
  re-running the last apply). The overlay's keydown calls `session.flipSide()` on
  R — gated on `hasMovedSinceStart` so it only fires when the 2D pane is the
  active mover (the 3D MoveDoorTool owns R in 3D/split; this prevents a double
  flip / double cue on one R press).
- Commit in 2D now flows solely through the overlay's pointerup (no competing
  synthesized wall:click), so click-to-place commits.

The global use-keyboard R/T already stands down during opening placement
(isPlacingOpening), so a selected node can't also flip.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): 2D door/window move free-follows the cursor off-wall and commits only on a wall

Moving an existing door/window in the 2D floor plan: the move target's `apply`
early-returned off-wall (`if (!hit) return`), so the opening stayed frozen on
its old wall instead of following the cursor between walls (3D free-follows),
and an off-wall confirm click committed the stale last-wall position — looking
like the placement failed.

Now `doorFloorplanMoveTarget`/`windowFloorplanMoveTarget` mirror the 3D move:
- Off-wall, `apply` free-follows the cursor — hides the real node and floats the
  faithful door/window symbol at the cursor via a synthetic wall published to
  `usePlacementPreview` (the same preview layer fresh placement uses). The real
  node is `visible:false` so the registry layer skips it (no double symbol).
- Back on a wall, it clears the ghost, reveals the real node, and snaps as before.
- `canCommit` returns false while off-wall, so an open-floor click reverts to the
  pre-move snapshot (door returns to its wall) instead of committing in mid-air —
  matching the 3D move, where clicking open floor commits nothing. On a wall the
  commit lands normally.

The overlay's snapshot revert (cancel / invalid commit) and the on-wall `apply`'s
`visible:true` restore both guarantee the node is never left hidden after a move.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): 2D opening snap picks the true nearest wall, with a tighter radius

The 2D door/window snap felt too aggressive and could grab a wall further away
than the one the cursor was actually nearest. Root cause in
`findClosestWallInPlan`: it compared a candidate's true segment distance against
the previous best's `perpDistance` (signed offset to the wall's infinite line,
not the clamped segment distance). Near a wall end those diverge, so a closer
wall could be rejected / a farther one kept.

- Track the best segment distance and keep the strict minimum — the wall chosen
  is now always the single closest segment to the cursor (true nearest), which
  resolves correctly when many walls sit close together.
- Tighten the snap radius from 1.5 m to 0.4 m: plan walls are thin, so the old
  radius snapped from far away. The opening now free-follows the cursor until
  it's genuinely near a wall.

Only the 2D move/placement targets use this helper (3D snaps on raycast hover);
wall-attached items share the same improved nearest-wall behaviour.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(editor): true-nearest 2D opening snap with dev hit-area overlay

Round 7 of the placement-ghosts work. Make the 2D door/window wall snap
always pick the wall nearest the cursor, fix fresh-placement snapping/slide
in 2D, and add a dev-only overlay that visualises each wall's snap region.

- Extract the plan-space nearest-wall-segment math to core
  (`lib/wall-distance.ts`: collectLevelWallSegments / closestOnSegment /
  nearestWallSegment / WALL_SNAP_DISTANCE_M). `findClosestWallInPlan`
  delegates to it, so the snap and the debug overlay share one source of
  truth. WallHit contract unchanged.
- door/window 2D move now resolves the host level via the shared
  `getOpeningHostLevelId` (wall-hosted, roof-hosted, AND fresh-placement
  parented straight to the level — the last case previously resolved to the
  building, so a new opening never snapped in 2D).
- Cursor resolver switched to absolute mode: query the snap with the true
  cursor, not the original-wall position + grab delta, so it picks the
  cursor-nearest wall (matching the 3D move) instead of a far wall across a
  thin gap.
- 2D move clears any stale `useLiveTransforms` entry for the node each apply:
  the registry layer renders door/window from the live transform in
  preference to the scene node, so a leftover entry from the 3D tool froze
  the 2D slide for fresh / re-armed openings.
- Fresh window defaults to a 0.9 m sill in 2D (was sitting half-below floor
  at y=0), matching the 3D MoveWindowTool.
- New dev-only FloorplanVoronoiLayer + `show2dVoronoi` editor flag: draws
  each wall's snap hit area as an analytic capsule (no grid sampling), gated
  on a developer-menu toggle.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Aymeric Rabot
2026-06-15 12:24:27 -04:00
committed by GitHub
co-authored by Claude Opus 4.8
parent aafb238545
commit 1628b728fa
49 changed files with 1907 additions and 748 deletions
@@ -0,0 +1,75 @@
'use client'
import type { Material, Mesh, Object3D, Raycaster } from 'three'
export const INVALID_GHOST_COLOR = 0xef_44_44
const NO_RAYCAST = (_raycaster: Raycaster, _intersects: unknown[]) => {}
/**
* Apply ghost material treatment to a preview mesh tree.
*
* Traverses the object tree, disables raycasting on all descendants (prevents
* cursor-ray starvation), and clones visible mesh materials to set translucency.
*
* When `invalid` is true, sets color/emissive to INVALID_GHOST_COLOR and opacity ~0.4.
* Otherwise sets opacity ~0.5 while preserving the original color.
*
* Skips: meshes whose material.visible === false (door/window root hitbox) and
* children named 'cutout'.
*
* Returns cleanup that disposes only the cloned materials (never originals or geometry).
*
* @param root - The preview mesh tree (typically from buildDoorPreviewMesh / buildWindowPreviewMesh)
* @param opts - { invalid?: boolean } whether to tint red for invalid placement
* @returns Cleanup function that disposes the cloned materials
*/
export function applyGhost(root: Object3D, opts?: { invalid?: boolean }): () => void {
const invalid = opts?.invalid ?? false
const cloned: Material[] = []
root.traverse((obj) => {
// Disable raycast on every descendant to prevent cursor-ray starvation.
obj.raycast = NO_RAYCAST
const mesh = obj as Mesh
if (!mesh.isMesh) return
if (mesh.name === 'cutout') return
const original = mesh.material
const wasArray = Array.isArray(original)
const cloneOne = (mat: Material): Material | null => {
// Skip invisible materials (door/window root hitbox).
if ((mat as { visible?: boolean }).visible === false) return null
const clone = mat.clone()
clone.transparent = true
clone.depthWrite = false
if (invalid) {
;(clone as { color?: { setHex: (c: number) => void } }).color?.setHex(INVALID_GHOST_COLOR)
;(clone as { emissive?: { setHex: (c: number) => void } }).emissive?.setHex(
INVALID_GHOST_COLOR,
)
clone.opacity = 0.4
} else {
clone.opacity = 0.5
}
cloned.push(clone)
return clone
}
if (wasArray) {
const clonedMats = original.map(cloneOne).filter((m): m is Material => m !== null)
if (clonedMats.length > 0) mesh.material = clonedMats
} else {
const clone = cloneOne(original)
if (clone) mesh.material = clone
}
})
return () => {
for (const mat of cloned) {
mat.dispose()
}
}
}
@@ -9,7 +9,7 @@ import {
sceneRegistry,
} from '@pascal-app/core'
import { DragBoundingBox } from '@pascal-app/editor'
import { useEffect, useRef, useState } from 'react'
import { type ReactNode, useEffect, useRef, useState } from 'react'
import { Vector3 } from 'three'
const INVALID_PREVIEW_COLOR = 0xef_44_44
@@ -17,6 +17,7 @@ type ValidTarget = 'roof' | 'gutter'
export function RoofAttachmentFallbackPreview({
activeBuildingId,
ghost,
isValidRoofTarget,
lift = 0,
onInvalidTarget,
@@ -24,10 +25,11 @@ export function RoofAttachmentFallbackPreview({
validTarget = 'roof',
}: {
activeBuildingId: string | null | undefined
ghost?: ReactNode
isValidRoofTarget?: (event: RoofEvent) => boolean
lift?: number
onInvalidTarget?: () => void
size: [number, number, number]
size?: [number, number, number]
validTarget?: ValidTarget
}) {
const [position, setPosition] = useState<[number, number, number] | null>(null)
@@ -100,6 +102,13 @@ export function RoofAttachmentFallbackPreview({
if (!(activeBuildingId && position)) return null
// When ghost is provided, render the ghost instead of DragBoundingBox
if (ghost) {
return <group position={position}>{ghost}</group>
}
// Fallback to DragBoundingBox for callers not yet migrated
if (!size) return null
return (
<DragBoundingBox
color={INVALID_PREVIEW_COLOR}
@@ -84,6 +84,32 @@ export function getRoofHostedOpeningLevelId(
return (roof.parentId as AnyNodeId | null) ?? null
}
/**
* The level that owns the wall-snap candidates for an opening (door /
* window), across all three parentings the 2D move can start from:
* - roof-hosted: opening → segment → roof → level (`getRoofHostedOpeningLevelId`).
* - wall-hosted (existing opening): parent is a wall → its parent is the level.
* - fresh placement (preset/catalog): the clone is parented straight to the
* LEVEL (`place-preset` sets `parentId: levelId`), so the parent IS the level.
*
* The fresh-placement case is the subtle one: treating the parent as always a
* wall (`parent.parentId`) resolves a fresh opening's level to the BUILDING,
* and `collectLevelWallSegments(building)` finds no walls — so a new door /
* window never snapped in 2D. Returns null when the parent chain is none of
* the above.
*/
export function getOpeningHostLevelId(
node: { parentId: string | null },
nodes: Record<string, AnyNode | undefined>,
): AnyNodeId | null {
const roofLevelId = getRoofHostedOpeningLevelId(node, nodes)
if (roofLevelId) return roofLevelId
const parent = node.parentId ? nodes[node.parentId] : undefined
if (!parent) return null
if (parent.type === 'level') return parent.id as AnyNodeId
return (parent.parentId as AnyNodeId | null) ?? null
}
/**
* Level-plan [x, z] of a roof-hosted node — its face-local center mapped
* through the face frame, then composed through the segment's and roof's
+38 -76
View File
@@ -1,9 +1,11 @@
import {
type AnyNode,
type AnyNodeId,
collectLevelWallSegments,
getScaledDimensions,
type ItemNode,
isCurvedWall,
nearestWallSegment,
WALL_SNAP_DISTANCE_M,
type WallNode,
} from '@pascal-app/core'
@@ -22,8 +24,6 @@ import {
* rejects curved walls (mitering + arc + opening would tear in 3D).
*/
const WALL_SNAP_DISTANCE_M = 1.5
export type WallHit = {
wall: WallNode
/** Distance along the wall from `start` (clamped to [0, length]). */
@@ -61,10 +61,14 @@ export function projectWallLocalPointToPlan(
}
/**
* Walk every wall under `parentLevelId` and return the closest one to
* `planPoint`, or `null` if no wall is within `WALL_SNAP_DISTANCE_M`.
* `excludeWallId` skips a specific wall (e.g. the current parent during
* a re-parent flow if you want a "must change" guard).
* Return the single closest wall under `parentLevelId` to `planPoint` — the
* wall whose segment-Voronoi cell the point lies in — or `null` if nothing is
* within `WALL_SNAP_DISTANCE_M`. `excludeWallId` skips a specific wall.
*
* The nearest-segment scan + curved-wall filter live in core
* (`collectLevelWallSegments` / `nearestWallSegment`) so the editor's 2D
* Voronoi debug overlay classifies points with the exact same math — the
* overlay is then a faithful picture of where this snaps.
*/
export function findClosestWallInPlan(
planPoint: readonly [number, number],
@@ -72,78 +76,36 @@ export function findClosestWallInPlan(
parentLevelId: AnyNodeId | null,
excludeWallId?: AnyNodeId,
): WallHit | null {
if (!parentLevelId) return null
const level = nodes[parentLevelId]
const childIds = (level as unknown as { children?: AnyNodeId[] })?.children
if (!Array.isArray(childIds)) return null
const segments = collectLevelWallSegments(nodes, parentLevelId)
const closest = nearestWallSegment(
segments,
planPoint[0],
planPoint[1],
WALL_SNAP_DISTANCE_M,
excludeWallId,
)
if (!closest) return null
let best: WallHit | null = null
const { segment, along, perp } = closest
// Side determination, calibrated to the 3D wall convention. In wall-local
// space the wall extends along +X and its +Z axis is the front-face normal;
// `perp >= 0` is consistently the front side (see `closestOnSegment`).
const side: 'front' | 'back' = perp >= 0 ? 'front' : 'back'
// Wall-local rotation matching 3D `calculateItemRotation`: 0 front, π back.
// The node is parented to the wall, so this composes with the wall's own
// rotation at render — never a world-space rotation here.
const itemRotation = side === 'front' ? 0 : Math.PI
for (const childId of childIds) {
const node = nodes[childId]
if (!node || node.type !== 'wall') continue
if (childId === excludeWallId) continue
const wall = node as WallNode
if (isCurvedWall(wall)) continue
const sx = wall.start[0]
const sy = wall.start[1]
const dx = wall.end[0] - sx
const dy = wall.end[1] - sy
const wallLength = Math.hypot(dx, dy)
if (wallLength < 1e-6) continue
const dirX = dx / wallLength
const dirY = dy / wallLength
// Project pointer onto wall axis.
const px = planPoint[0] - sx
const py = planPoint[1] - sy
const along = px * dirX + py * dirY
const perpRaw = px * -dirY + py * dirX // signed perpendicular distance
const clampedAlong = Math.max(0, Math.min(wallLength, along))
// Distance from the pointer to the wall segment (not just the line).
const closestPointX = sx + dirX * clampedAlong
const closestPointY = sy + dirY * clampedAlong
const distance = Math.hypot(planPoint[0] - closestPointX, planPoint[1] - closestPointY)
if (distance > WALL_SNAP_DISTANCE_M) continue
if (best && distance >= Math.abs(best.perpDistance) && best.wall.id !== wall.id) continue
// Side determination, calibrated to the 3D wall convention. In
// wall-local space the wall extends along +X and its +Z axis is the
// front-face normal. After `mesh.rotation.y = -wallAngle`:
// - For a wall going `+X` in plan (wallAngle=0): wall-local +Z
// maps to world +Z = plan +Y, so the front face is on plan +Y.
// `perpRaw = py` is positive → front.
// - For a wall going `+Y` in plan (wallAngle=π/2): wall-local +Z
// maps to world -X = plan -X, so the front face is on plan -X.
// `perpRaw = -px` is positive there → front.
// So `perpRaw >= 0` is consistently the front side. The earlier
// labelling had this flipped, which produced rotations that were
// off by 90° on non-horizontal walls.
const side: 'front' | 'back' = perpRaw >= 0 ? 'front' : 'back'
// Rotation in wall-local space — matches 3D `calculateItemRotation`:
// 0 when the item faces the front normal (+Z), π for the back. The
// node is parented to the wall, so this composes with the wall's
// own rotation when rendered. Don't return a world-space rotation
// here — the consumer writes this straight into `node.rotation[1]`.
const itemRotation = side === 'front' ? 0 : Math.PI
best = {
wall,
localX: clampedAlong,
perpDistance: perpRaw,
side,
dirX,
dirY,
wallLength,
itemRotation,
}
return {
wall: segment.wall,
localX: along,
perpDistance: perp,
side,
dirX: segment.dirX,
dirY: segment.dirY,
wallLength: segment.length,
itemRotation,
}
return best
}
/** Figma-style along-wall alignment threshold (meters) — parity with the