arch: enforce layer boundaries — ceiling dispatch, store relocation, shared helper (#382)
* Add roof surface placement support for items Items (e.g. solar panels) can now be placed on sloped roof surfaces. The placement system computes euler rotation from the roof surface normal so items sit flush on the slope instead of going inside. - Add roofStrategy to placement-strategies with enter/move/click/leave - Wire roof:enter/move/click/leave events in the placement coordinator - Add calculateRoofRotation in placement-math using surface normals - Support full 3D cursor rotation for sloped surfaces - Items on roofs are parented to the level with world-space rotation Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fixed conflict * editor: per-door-type floor-plan symbols Render a distinct, static plan symbol for each door type in the registry floor-plan builder (`packages/nodes/src/door/floorplan.ts`), independent of the door's live open/close animation: - single / hinged: fixed 90° swing with a dashed quarter-circle arc - double / french: two mirrored half-width leaves + dashed arcs - folding / bifold: static zigzag accordion (~80% span) on the wall face - sliding: bypass — two overlapping panels on parallel tracks + arrow - pocket: thin white leaf, ~60% closed, sliding into the solid wall - barn: surface-mounted panel parked over the wall, dashed closed-ghost + slide arrow The swing arc is dashed in screen-pixel units (the renderer uses non-scaling-stroke). Symbols are oriented by hingesSide / swingDirection / slideDirection as appropriate. Also includes pre-existing working-tree changes unrelated to the door symbols: group move/rotate transform and box-select tweaks, and a regenerated ifc-converter next-env.d.ts. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Fix recessed ceiling fixtures and draw safety * feat(editor): magnetic wall-snap with per-kind beacon (2D + 3D) Snap the wall draft / endpoint-move point onto existing wall geometry — corners, midpoints, wall–wall intersections, and along-wall edges — and show a beacon at the snap point whose glyph encodes what it caught (square = corner, triangle = midpoint, ✕ = intersection, circle = edge). - Pure snap geometry extracted to wall-snap-geometry.ts (unit-tested). - Ephemeral useWallSnapIndicator store drives a 3D pillar+glyph beacon and a 2D SVG glyph beacon, both indigo to match the alignment guides. - Gated by a new persisted "Magnetic snap" toggle in the Display menu (useEditor); honored by draw + commit + endpoint-move in both views. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * editor: garage and open-doorway floor-plan symbols Extend the per-door-type plan symbols in the registry floor-plan builder (packages/nodes/src/door/floorplan.ts): - open doorway (openingKind === 'opening'): bare gap, no leaf/arc/panel (mirrors the 3D system, which renders only the cutout for openings) - garage sectional: closed leaf + side tracks into the garage + dashed parked ghost at the inner end - garage roll-up: closed leaf + coil barrel (capsule) with a coil hint - garage tilt-up: closed leaf + dashed parked panel + dashed curved up-and-over swing path - gate the swing arc to actual swing doors (hinged/double/french) so other types fall back to the plain footprint Garage mechanisms sit on the interior (door-local -z) side to match the 3D garage builders, independent of swingDirection. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * arch: enforce layer boundaries — registry dispatch, store relocation, shared helper Three architectural fixes to bring the branch into full compliance: 1. **ceiling-system kind check → CeilingCutCapability** Replace `child.type === 'item'` branch in `ceiling-system` with registry dispatch. Add `CeilingCutCapability` type to `packages/core` registry types, implement `buildCeilingHole` on `itemDefinition`, and rewrite `collectRecessedItemHoles` → `collectCeilingHoles` to dispatch through `nodeRegistry` — viewer never again inspects a node's kind directly. 2. **useAlignmentGuides + useWallSnapIndicator → packages/editor** These stores are editor-only UI (snap beacons, alignment guides). Move them from `packages/core/src/store/` to `packages/editor/src/store/`, re-export from `packages/editor`, and update all 34 consumer files across `packages/editor` and `packages/nodes` to import from `@pascal-app/editor`. 3. **findLevelAncestorId extracted to core** `item-light-system` had a private `resolveNodeLevelId` that duplicated level-ancestor traversal logic. Extract it as `findLevelAncestorId` in `packages/core` (spatial-grid-sync), export it, and replace the local copy. All four packages typecheck cleanly (zero errors). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: fix lint, untrack .claude/launch.json Run bun check --write to clear 8 Biome errors (formatting + import order + one unused import). Untrack .claude/launch.json and add it plus .claude/settings.local.json to .gitignore so local IDE/agent configs stop landing in commits. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
7796837081
commit
ce6f999310
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useAlignmentGuides } from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { memo } from 'react'
|
||||
import { formatMeasurement } from '../editor/measurement-pill'
|
||||
|
||||
@@ -12,11 +12,11 @@ import {
|
||||
pauseSceneHistory,
|
||||
resolveAlignment,
|
||||
resumeSceneHistory,
|
||||
useAlignmentGuides,
|
||||
useLiveNodeOverrides,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { useEffect } from 'react'
|
||||
import { commitFreshPlacementSubtree } from '../../lib/fresh-planar-placement'
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
'use client'
|
||||
|
||||
import { useWallSnapIndicator, type WallSnapKind } from '@pascal-app/editor'
|
||||
import { memo } from 'react'
|
||||
import { useFloorplanRender } from './floorplan-render-context'
|
||||
|
||||
/**
|
||||
* "Magnetic" wall-snap beacon for the 2D floor plan — the top-down twin of the
|
||||
* 3D `WallSnapBeaconLayer`. Subscribes to the shared `useWallSnapIndicator`
|
||||
* store (published by the floor-plan wall draft + endpoint-move handlers) and
|
||||
* draws a marker at the snap point whose shape tells you *what* it caught,
|
||||
* matching the 3D glyphs:
|
||||
*
|
||||
* endpoint (corner) → square midpoint → triangle
|
||||
* intersection → ✕ cross wall body (edge) → circle
|
||||
*
|
||||
* Indigo to match the 3D beacon and stay distinct from the red Figma alignment
|
||||
* guides. Sizes are pixel-budgeted via `unitsPerPixel` so the marker stays a
|
||||
* constant size on screen at any zoom. Mounted inside the `data-floorplan-scene`
|
||||
* group so coordinates are world meters (XZ) 1:1, like the alignment guides.
|
||||
*/
|
||||
const COLOR = '#6366f1' // indigo-500 — matches the 3D beacon
|
||||
|
||||
export const FloorplanSnapBeaconLayer = memo(function FloorplanSnapBeaconLayer() {
|
||||
const point = useWallSnapIndicator((s) => s.point)
|
||||
const ctx = useFloorplanRender()
|
||||
|
||||
if (!point) return null
|
||||
|
||||
const upp = ctx?.unitsPerPixel ?? 0.01
|
||||
const m = 6 * upp // base half-size of the glyph in world meters
|
||||
const stroke = 1.5 * upp
|
||||
|
||||
return (
|
||||
<g pointerEvents="none">
|
||||
<SnapMarker color={COLOR} kind={point.kind} m={m} stroke={stroke} x={point.x} z={point.z} />
|
||||
</g>
|
||||
)
|
||||
})
|
||||
|
||||
function SnapMarker({
|
||||
color,
|
||||
kind,
|
||||
m,
|
||||
stroke,
|
||||
x,
|
||||
z,
|
||||
}: {
|
||||
color: string
|
||||
kind: WallSnapKind
|
||||
m: number
|
||||
stroke: number
|
||||
x: number
|
||||
z: number
|
||||
}) {
|
||||
if (kind === 'endpoint') {
|
||||
return <rect fill={color} height={m * 2} width={m * 2} x={x - m} y={z - m} />
|
||||
}
|
||||
if (kind === 'midpoint') {
|
||||
const t = m * 1.3
|
||||
const points = `${x},${z - t} ${x - t},${z + t} ${x + t},${z + t}`
|
||||
return <polygon fill={color} points={points} />
|
||||
}
|
||||
if (kind === 'intersection') {
|
||||
const c = m * 1.4
|
||||
return (
|
||||
<g stroke={color} strokeLinecap="round" strokeWidth={stroke * 2}>
|
||||
<line x1={x - c} x2={x + c} y1={z - c} y2={z + c} />
|
||||
<line x1={x - c} x2={x + c} y1={z + c} y2={z - c} />
|
||||
</g>
|
||||
)
|
||||
}
|
||||
// 'wall' (edge / along-wall) → circle
|
||||
return <circle cx={x} cy={z} fill={color} r={m} />
|
||||
}
|
||||
@@ -14,12 +14,12 @@ import {
|
||||
pauseSceneHistory,
|
||||
resolveBuildingForLevel,
|
||||
resumeSceneHistory,
|
||||
useAlignmentGuides,
|
||||
useInteractive,
|
||||
useLiveNodeOverrides,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import {
|
||||
memo,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { type AlignmentGuide, sceneRegistry, useAlignmentGuides } from '@pascal-app/core'
|
||||
import { type AlignmentGuide, sceneRegistry } from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { Html } from '@react-three/drei'
|
||||
import { useFrame } from '@react-three/fiber'
|
||||
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
StairSegmentNode as StairSegmentNodeSchema,
|
||||
sampleWallCenterline,
|
||||
sceneRegistry,
|
||||
useAlignmentGuides,
|
||||
useInteractive,
|
||||
useLiveNodeOverrides,
|
||||
useLiveTransforms,
|
||||
@@ -48,6 +47,7 @@ import {
|
||||
ZoneNode as ZoneNodeSchema,
|
||||
type ZoneNode as ZoneNodeType,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides, useWallSnapIndicator } from '@pascal-app/editor'
|
||||
import { getSceneTheme, useViewer } from '@pascal-app/viewer'
|
||||
import { Command, Ruler } from 'lucide-react'
|
||||
import {
|
||||
@@ -87,6 +87,7 @@ import {
|
||||
type FloorplanRenderContextValue,
|
||||
FloorplanRenderProvider,
|
||||
} from '../editor-2d/floorplan-render-context'
|
||||
import { FloorplanSnapBeaconLayer } from '../editor-2d/floorplan-snap-beacon-layer'
|
||||
import { FloorplanWallMoveGhostLayer } from '../editor-2d/floorplan-wall-move-ghost-layer'
|
||||
import { FloorplanDraftLayer } from '../editor-2d/renderers/floorplan-draft-layer'
|
||||
import { FloorplanGeometryRenderer } from '../editor-2d/renderers/floorplan-geometry-renderer'
|
||||
@@ -132,6 +133,7 @@ import {
|
||||
createWallOnCurrentLevel,
|
||||
isSegmentLongEnough,
|
||||
snapWallDraftPoint,
|
||||
snapWallDraftPointDetailed,
|
||||
snapPointToGrid as snapWallPointToGrid,
|
||||
WALL_FINE_GRID_STEP,
|
||||
WALL_GRID_STEP,
|
||||
@@ -6843,6 +6845,7 @@ export function FloorplanPanel() {
|
||||
wallEndpointDragRef.current = null
|
||||
setWallEndpointDraft(null)
|
||||
setHoveredEndpointId(null)
|
||||
useWallSnapIndicator.getState().clear()
|
||||
}, [])
|
||||
const clearWallCurveDrag = useCallback(() => {
|
||||
wallCurveDragRef.current = null
|
||||
@@ -6869,6 +6872,7 @@ export function FloorplanPanel() {
|
||||
// Drop any Figma-style alignment guide a draft branch left behind so it
|
||||
// doesn't linger after the tool deactivates / Esc / draft reset.
|
||||
useAlignmentGuides.getState().clear()
|
||||
useWallSnapIndicator.getState().clear()
|
||||
}, [
|
||||
clearFencePlacementDraft,
|
||||
clearCeilingPlacementDraft,
|
||||
@@ -7265,12 +7269,22 @@ export function FloorplanPanel() {
|
||||
// Wall endpoint move: grid snap only (no 45° angle snap from the
|
||||
// fixed corner — that's draft-only behaviour). Shift switches
|
||||
// to the fine grid step for precision.
|
||||
const snappedPoint = snapWallDraftPoint({
|
||||
const snapResult = snapWallDraftPointDetailed({
|
||||
point: planPoint,
|
||||
walls,
|
||||
ignoreWallIds: [dragState.wallId],
|
||||
step: shiftPressed ? WALL_FINE_GRID_STEP : undefined,
|
||||
magnetic: useEditor.getState().magneticSnap,
|
||||
})
|
||||
const snappedPoint = snapResult.point
|
||||
// Magnetic beacon at the endpoint when it locked onto existing geometry.
|
||||
useWallSnapIndicator
|
||||
.getState()
|
||||
.set(
|
||||
snapResult.snap
|
||||
? { x: snappedPoint[0], z: snappedPoint[1], kind: snapResult.snap }
|
||||
: null,
|
||||
)
|
||||
|
||||
if (pointsEqual(dragState.currentPoint, snappedPoint)) {
|
||||
return
|
||||
@@ -8238,20 +8252,25 @@ export function FloorplanPanel() {
|
||||
// wins outright — never pull the cursor off a corner the user is
|
||||
// closing onto — so alignment runs ONLY when the wall snap left the
|
||||
// point on the plain grid. Alt bypasses alignment.
|
||||
const gridStep = shiftPressed ? WALL_FINE_GRID_STEP : WALL_GRID_STEP
|
||||
const wallSnapped = snapWallDraftPoint({
|
||||
const wallSnap = snapWallDraftPointDetailed({
|
||||
point: planPoint,
|
||||
walls,
|
||||
step: shiftPressed ? WALL_FINE_GRID_STEP : undefined,
|
||||
magnetic: useEditor.getState().magneticSnap,
|
||||
})
|
||||
const gridBase = snapWallPointToGrid(planPoint, gridStep)
|
||||
const lockedToWall = wallSnapped[0] !== gridBase[0] || wallSnapped[1] !== gridBase[1]
|
||||
const wallSnapped = wallSnap.point
|
||||
// Locked onto existing geometry (corner / midpoint / crossing / edge) →
|
||||
// that snap wins, so skip Figma alignment and stand the beacon there.
|
||||
const lockedToWall = wallSnap.snap !== null
|
||||
let snappedPoint = wallSnapped
|
||||
if (lockedToWall) {
|
||||
useAlignmentGuides.getState().clear()
|
||||
} else {
|
||||
snappedPoint = alignFloorplanDraftPoint(wallSnapped, { bypass: event.altKey })
|
||||
}
|
||||
useWallSnapIndicator
|
||||
.getState()
|
||||
.set(wallSnap.snap ? { x: snappedPoint[0], z: snappedPoint[1], kind: wallSnap.snap } : null)
|
||||
|
||||
// Emit `grid:move` so the registry-driven wall tool's 3D preview
|
||||
// tracks the cursor. The local draftEnd update below is what
|
||||
@@ -8506,6 +8525,19 @@ export function FloorplanPanel() {
|
||||
phase,
|
||||
toPoint2D,
|
||||
})
|
||||
// Wall-commit snap for the placement hook. Mirrors the move-preview branch:
|
||||
// it honours the Magnetic snap toggle so a click never snaps to geometry the
|
||||
// preview didn't (keeps 2D commit consistent with the preview and with 3D).
|
||||
const snapWallDraftPointMagnetic = useCallback(
|
||||
(args: {
|
||||
point: WallPlanPoint
|
||||
walls: WallNode[]
|
||||
start?: WallPlanPoint
|
||||
angleSnap?: boolean
|
||||
step?: number
|
||||
}) => snapWallDraftPoint({ ...args, magnetic: useEditor.getState().magneticSnap }),
|
||||
[],
|
||||
)
|
||||
const { handleBackgroundPlacementClick } = useFloorplanBackgroundPlacement({
|
||||
activePolygonDraftPoints,
|
||||
ceilingDraftPoints,
|
||||
@@ -8539,7 +8571,7 @@ export function FloorplanPanel() {
|
||||
setRoofDraftStart,
|
||||
shiftPressed,
|
||||
snapPolygonDraftPoint,
|
||||
snapWallDraftPoint,
|
||||
snapWallDraftPoint: snapWallDraftPointMagnetic,
|
||||
toPoint2D,
|
||||
walls,
|
||||
})
|
||||
@@ -10047,6 +10079,11 @@ export function FloorplanPanel() {
|
||||
paint on top of node geometry. */}
|
||||
<FloorplanAlignmentGuideLayer />
|
||||
|
||||
{/* "Magnetic" wall-snap beacon — per-kind glyph at the active
|
||||
draft / endpoint-move snap point. Same store + coord space as
|
||||
the alignment guides. */}
|
||||
<FloorplanSnapBeaconLayer />
|
||||
|
||||
<FloorplanMarqueeLayer
|
||||
bounds={visibleSvgMarqueeBounds}
|
||||
cursorColor={palette.cursor}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { MathUtils, type Mesh, PlaneGeometry, Vector2, Vector3 } from 'three'
|
||||
import { color, float, fract, fwidth, mix, positionLocal, uniform } from 'three/tsl'
|
||||
import { MeshBasicNodeMaterial } from 'three/webgpu'
|
||||
import { useCeilingEvents } from '../../hooks/use-ceiling-events'
|
||||
import { useGridEvents } from '../../hooks/use-grid-events'
|
||||
|
||||
export const Grid = ({
|
||||
@@ -117,6 +118,10 @@ export const Grid = ({
|
||||
|
||||
// Use custom raycasting for grid events (independent of mesh events)
|
||||
useGridEvents(gridY)
|
||||
// Same technique for ceiling-item placement: a math-plane raycast per ceiling,
|
||||
// so commits don't depend on hitting the thin, single-sided `ceiling-grid`
|
||||
// overlay mesh (which dropped clicks even with the green box showing).
|
||||
useCeilingEvents()
|
||||
|
||||
// Track the last world-space cursor hit. The reveal-fade shader reads
|
||||
// `positionLocal.xy` (vertex position on the un-transformed plane), and
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
collectParticipants,
|
||||
computeGroupBox,
|
||||
expandToComponent,
|
||||
levelFrame,
|
||||
type Vec2,
|
||||
} from './group-transform-shared'
|
||||
import {
|
||||
@@ -118,15 +119,18 @@ function GroupMoveHandleInner({ ids }: { ids: string[] }) {
|
||||
const planeY = rest.baseY
|
||||
|
||||
// Snapshot selected participants + connected wall/fence neighbours.
|
||||
const { starts, links } = collectParticipants(
|
||||
ids,
|
||||
useScene.getState().nodes,
|
||||
useViewer.getState().selection.levelId,
|
||||
)
|
||||
const levelId = useViewer.getState().selection.levelId
|
||||
const { starts, links } = collectParticipants(ids, useScene.getState().nodes, levelId)
|
||||
if (starts.length === 0) return
|
||||
|
||||
// Horizontal drag plane at the group's base; delta measured in world XZ
|
||||
// (= level-local XZ on an axis-aligned level).
|
||||
// Placements are stored in the level frame, so convert each world-space
|
||||
// ground-plane hit into that frame before measuring the delta. Frozen at
|
||||
// drag-start; `frameOrigin` lets us map the local delta back to world for
|
||||
// the gizmo's own travel (it's portalled to the scene root).
|
||||
const { matrix: frame, inverse: frameInv } = levelFrame(levelId)
|
||||
const frameOrigin = new Vector3().applyMatrix4(frame)
|
||||
|
||||
// Horizontal drag plane at the group's base.
|
||||
const plane = new Plane(new Vector3(0, 1, 0), -planeY)
|
||||
const ndc = new Vector2()
|
||||
const setNDC = (clientX: number, clientY: number) => {
|
||||
@@ -141,7 +145,7 @@ function GroupMoveHandleInner({ ids }: { ids: string[] }) {
|
||||
raycaster.setFromCamera(ndc, camera)
|
||||
const hit = new Vector3()
|
||||
if (!raycaster.ray.intersectPlane(plane, hit)) return
|
||||
const startHit = hit.clone()
|
||||
const startLocal = hit.clone().applyMatrix4(frameInv)
|
||||
|
||||
document.body.style.cursor = 'grabbing'
|
||||
sfxEmitter.emit('sfx:item-pick')
|
||||
@@ -160,9 +164,14 @@ function GroupMoveHandleInner({ ids }: { ids: string[] }) {
|
||||
raycaster.setFromCamera(ndc, camera)
|
||||
const moveHit = new Vector3()
|
||||
if (!raycaster.ray.intersectPlane(plane, moveHit)) return
|
||||
const moveLocal = moveHit.applyMatrix4(frameInv)
|
||||
const snap = !e.shiftKey && step > 0
|
||||
const dx = snap ? Math.round((moveHit.x - startHit.x) / step) * step : moveHit.x - startHit.x
|
||||
const dz = snap ? Math.round((moveHit.z - startHit.z) / step) * step : moveHit.z - startHit.z
|
||||
const dx = snap
|
||||
? Math.round((moveLocal.x - startLocal.x) / step) * step
|
||||
: moveLocal.x - startLocal.x
|
||||
const dz = snap
|
||||
? Math.round((moveLocal.z - startLocal.z) / step) * step
|
||||
: moveLocal.z - startLocal.z
|
||||
|
||||
// Ticker on each grid-cell crossing, like single-item placement.
|
||||
if (snap && (!lastSnap || lastSnap[0] !== dx || lastSnap[1] !== dz)) {
|
||||
@@ -210,7 +219,9 @@ function GroupMoveHandleInner({ ids }: { ids: string[] }) {
|
||||
}
|
||||
useLiveNodeOverrides.getState().setMany(overrideEntries)
|
||||
|
||||
setLiveDelta([dx, dz])
|
||||
// Gizmo rides the group in world space; map the level-frame delta back out.
|
||||
const worldDelta = new Vector3(dx, 0, dz).applyMatrix4(frame).sub(frameOrigin)
|
||||
setLiveDelta([worldDelta.x, worldDelta.z])
|
||||
}
|
||||
|
||||
const affectedIds: AnyNodeId[] = [...starts.map((s) => s.id), ...links.map((l) => l.id)]
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
collectParticipants,
|
||||
computeGroupBox,
|
||||
expandToComponent,
|
||||
levelFrame,
|
||||
type Vec2,
|
||||
type Vec3,
|
||||
} from './group-transform-shared'
|
||||
@@ -140,13 +141,17 @@ function GroupRotateHandleInner({ ids }: { ids: string[] }) {
|
||||
|
||||
// Snapshot the selected participants + connected wall/fence neighbours whose
|
||||
// shared endpoints must follow the rotation (so junctions stay welded).
|
||||
const { starts, links } = collectParticipants(
|
||||
ids,
|
||||
useScene.getState().nodes,
|
||||
useViewer.getState().selection.levelId,
|
||||
)
|
||||
const levelId = useViewer.getState().selection.levelId
|
||||
const { starts, links } = collectParticipants(ids, useScene.getState().nodes, levelId)
|
||||
if (starts.length === 0) return
|
||||
|
||||
// Placements live in the level frame; the world pivot must be converted into
|
||||
// it before orbiting positions, or a rotated building displaces the centre.
|
||||
// The swept angle is frame-invariant (both frames differ by a constant yaw,
|
||||
// which cancels in `angleOf(move) - angleOf(start)`), so it's still measured
|
||||
// in world against `center` — keeping the world-space guide overlay correct.
|
||||
const localCenter = center.clone().applyMatrix4(levelFrame(levelId).inverse)
|
||||
|
||||
// Horizontal drag plane at the pivot; bearing measured around the pivot.
|
||||
const plane = new Plane(new Vector3(0, 1, 0), -center.y)
|
||||
const angleOf = (p: Vector3) => Math.atan2(p.z - center.z, p.x - center.x)
|
||||
@@ -155,7 +160,7 @@ function GroupRotateHandleInner({ ids }: { ids: string[] }) {
|
||||
// participant's anchor point(s).
|
||||
let spread = 0
|
||||
const reach = (x: number, z: number) => {
|
||||
spread = Math.max(spread, Math.hypot(x - center.x, z - center.z))
|
||||
spread = Math.max(spread, Math.hypot(x - localCenter.x, z - localCenter.z))
|
||||
}
|
||||
for (const s of starts) {
|
||||
if (s.kind === 'endpoint') {
|
||||
@@ -207,9 +212,9 @@ function GroupRotateHandleInner({ ids }: { ids: string[] }) {
|
||||
const cos = Math.cos(delta)
|
||||
const sin = Math.sin(delta)
|
||||
const rot = (x: number, z: number): Vec2 => {
|
||||
const dx = x - center.x
|
||||
const dz = z - center.z
|
||||
return [center.x + dx * cos - dz * sin, center.z + dx * sin + dz * cos]
|
||||
const dx = x - localCenter.x
|
||||
const dz = z - localCenter.z
|
||||
return [localCenter.x + dx * cos - dz * sin, localCenter.z + dx * sin + dz * cos]
|
||||
}
|
||||
const overrideEntries: Array<readonly [string, Record<string, unknown>]> = []
|
||||
const liveTransforms = useLiveTransforms.getState()
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
resolveBuildingForLevel,
|
||||
sceneRegistry,
|
||||
} from '@pascal-app/core'
|
||||
import { Box3 } from 'three'
|
||||
import { Box3, Matrix4 } from 'three'
|
||||
|
||||
// Shared plumbing for the group transform gizmos (rotate + move). Both operate
|
||||
// on the same multi-selection: classify each participant by how its placement
|
||||
@@ -219,10 +219,26 @@ export function expandToComponent(
|
||||
return Array.from(included)
|
||||
}
|
||||
|
||||
// Frozen world matrix of the level group + its inverse. A node's placement
|
||||
// (`position` / `start` / `end`) is stored in its parent level's frame, but the
|
||||
// gizmos raycast the ground plane in WORLD space. When the building is rotated
|
||||
// those frames diverge, so a world-space drag delta / rotation pivot must be
|
||||
// converted into the level frame before it's written back to placements —
|
||||
// otherwise the move drifts off-axis from the cursor and the rotation orbits a
|
||||
// displaced centre. Returns identity matrices when the level isn't mounted, which
|
||||
// collapses to the old behaviour (world == local) for an unrotated building.
|
||||
export function levelFrame(levelId: string | null): { matrix: Matrix4; inverse: Matrix4 } {
|
||||
const obj = levelId ? sceneRegistry.nodes.get(levelId as AnyNodeId) : null
|
||||
if (!obj) return { matrix: new Matrix4(), inverse: new Matrix4() }
|
||||
obj.updateWorldMatrix(true, false)
|
||||
const matrix = obj.matrixWorld.clone()
|
||||
return { matrix, inverse: matrix.clone().invert() }
|
||||
}
|
||||
|
||||
// World-space union bounding box of the selected meshes, or null if none are
|
||||
// mounted yet. Levels are axis-aligned in XZ, so world XZ coincides with each
|
||||
// node's level-local placement — letting callers transform placement directly
|
||||
// against box-derived points without per-node frame conversion.
|
||||
// mounted yet. Used to place the gizmos (which are portalled to the scene root,
|
||||
// so they live in world space); placement writes convert back to the level frame
|
||||
// via `levelFrame`.
|
||||
export function computeGroupBox(ids: string[]): Box3 | null {
|
||||
const box = new Box3()
|
||||
const tmp = new Box3()
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
'use client'
|
||||
|
||||
import { sceneRegistry } from '@pascal-app/core'
|
||||
import { useWallSnapIndicator, type WallSnapKind } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { useFrame } from '@react-three/fiber'
|
||||
import { memo, useRef } from 'react'
|
||||
import { BoxGeometry, CircleGeometry, CylinderGeometry, type Group } from 'three'
|
||||
import { MeshBasicNodeMaterial } from 'three/webgpu'
|
||||
import { EDITOR_LAYER } from '../../lib/constants'
|
||||
|
||||
/**
|
||||
* "Magnetic" wall-snap beacon for the 3D editor — a vertical marker that
|
||||
* stands at the draft / move endpoint while it's locked onto existing wall
|
||||
* geometry. It's the spatial cue from the design reference: a standing pillar
|
||||
* so you can see *where* the snap caught even at an angle, plus a floor marker
|
||||
* whose shape tells you *what* it caught (CAD-style osnap glyphs):
|
||||
*
|
||||
* endpoint (corner) → square midpoint → triangle
|
||||
* intersection → ✕ cross wall body (edge) → circle
|
||||
*
|
||||
* Subscribes to the shared `useWallSnapIndicator` store (published by the wall
|
||||
* draft + endpoint-move tools). Shares the indigo accent of
|
||||
* `Alignment3DGuideLayer` for visual consistency.
|
||||
*
|
||||
* The point carries only XZ (building-local plan coords); like the alignment
|
||||
* guides it's lifted to the active level's building-local Y each frame so it
|
||||
* stands on the floor being edited when floors are stacked. Mounted inside
|
||||
* ToolManager's building-local group.
|
||||
*/
|
||||
|
||||
const BEACON_COLOR = 0x81_8c_f8 // indigo-400 — matches the alignment guide accent
|
||||
const BEACON_HEIGHT = 2.5 // world-meter height of the pillar
|
||||
const BEACON_RADIUS = 0.018 // world-meter radius of the pillar
|
||||
const MARKER = 0.13 // world-meter base size of the floor glyph
|
||||
const FLOOR_LIFT = 0.012 // tiny lift so the marker reads above the floor grid
|
||||
|
||||
// Shared resources — one material + unit geometries, so snap churn during a
|
||||
// drag doesn't rebuild GPU buffers (mirrors the alignment guide layer).
|
||||
const beaconMaterial = new MeshBasicNodeMaterial({
|
||||
color: BEACON_COLOR,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
toneMapped: false,
|
||||
transparent: true,
|
||||
opacity: 0.9,
|
||||
})
|
||||
const PILLAR_GEOMETRY = new CylinderGeometry(BEACON_RADIUS, BEACON_RADIUS, BEACON_HEIGHT, 8)
|
||||
// Flat unit geometries scaled per marker. Boxes are 0.002 tall so they read as
|
||||
// a flat plate; circles/triangles lie flat via an X rotation at the mesh.
|
||||
const FLAT_BOX_GEOMETRY = new BoxGeometry(1, 0.002, 1)
|
||||
const TRIANGLE_GEOMETRY = new CircleGeometry(1, 3)
|
||||
const CIRCLE_GEOMETRY = new CircleGeometry(1, 28)
|
||||
|
||||
export const WallSnapBeaconLayer = memo(function WallSnapBeaconLayer() {
|
||||
const point = useWallSnapIndicator((s) => s.point)
|
||||
const levelId = useViewer((s) => s.selection.levelId)
|
||||
const groupRef = useRef<Group>(null)
|
||||
|
||||
// Track the active level's building-local Y each frame so the beacon stands
|
||||
// on the floor being edited, not the building base — same source the
|
||||
// alignment guide layer and `grid.tsx` read.
|
||||
useFrame(() => {
|
||||
const group = groupRef.current
|
||||
if (!group) return
|
||||
const levelMesh = levelId ? sceneRegistry.nodes.get(levelId) : null
|
||||
group.position.y = levelMesh ? levelMesh.position.y : 0
|
||||
})
|
||||
|
||||
if (!point) return null
|
||||
return (
|
||||
<group ref={groupRef}>
|
||||
<mesh
|
||||
geometry={PILLAR_GEOMETRY}
|
||||
layers={EDITOR_LAYER}
|
||||
material={beaconMaterial}
|
||||
position={[point.x, BEACON_HEIGHT / 2, point.z]}
|
||||
renderOrder={1002}
|
||||
/>
|
||||
<SnapMarker kind={point.kind} x={point.x} z={point.z} />
|
||||
</group>
|
||||
)
|
||||
})
|
||||
|
||||
/** Floor glyph whose shape encodes which kind of geometry the point snapped to. */
|
||||
function SnapMarker({ kind, x, z }: { kind: WallSnapKind; x: number; z: number }) {
|
||||
const y = FLOOR_LIFT
|
||||
if (kind === 'endpoint') {
|
||||
return (
|
||||
<mesh
|
||||
geometry={FLAT_BOX_GEOMETRY}
|
||||
layers={EDITOR_LAYER}
|
||||
material={beaconMaterial}
|
||||
position={[x, y, z]}
|
||||
renderOrder={1001}
|
||||
scale={[MARKER * 2, 1, MARKER * 2]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (kind === 'midpoint') {
|
||||
return (
|
||||
<mesh
|
||||
geometry={TRIANGLE_GEOMETRY}
|
||||
layers={EDITOR_LAYER}
|
||||
material={beaconMaterial}
|
||||
position={[x, y, z]}
|
||||
renderOrder={1001}
|
||||
rotation={[-Math.PI / 2, 0, 0]}
|
||||
scale={[MARKER * 1.4, MARKER * 1.4, MARKER * 1.4]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (kind === 'intersection') {
|
||||
// Two crossed bars → an ✕, the universal "crossing" glyph.
|
||||
return (
|
||||
<>
|
||||
<mesh
|
||||
geometry={FLAT_BOX_GEOMETRY}
|
||||
layers={EDITOR_LAYER}
|
||||
material={beaconMaterial}
|
||||
position={[x, y, z]}
|
||||
renderOrder={1001}
|
||||
rotation={[0, Math.PI / 4, 0]}
|
||||
scale={[MARKER * 2.6, 1, MARKER * 0.5]}
|
||||
/>
|
||||
<mesh
|
||||
geometry={FLAT_BOX_GEOMETRY}
|
||||
layers={EDITOR_LAYER}
|
||||
material={beaconMaterial}
|
||||
position={[x, y, z]}
|
||||
renderOrder={1001}
|
||||
rotation={[0, -Math.PI / 4, 0]}
|
||||
scale={[MARKER * 2.6, 1, MARKER * 0.5]}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
// 'wall' (edge / along-wall) → circle
|
||||
return (
|
||||
<mesh
|
||||
geometry={CIRCLE_GEOMETRY}
|
||||
layers={EDITOR_LAYER}
|
||||
material={beaconMaterial}
|
||||
position={[x, y, z]}
|
||||
renderOrder={1001}
|
||||
rotation={[-Math.PI / 2, 0, 0]}
|
||||
scale={[MARKER, MARKER, MARKER]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -13,7 +13,11 @@ import * as THREE from 'three'
|
||||
// recomputation per segment when the user actually wants it back.
|
||||
function makeEmptySegmentGeometry(): THREE.BufferGeometry {
|
||||
const g = new THREE.BufferGeometry()
|
||||
g.setAttribute('position', new THREE.Float32BufferAttribute([], 3))
|
||||
// Three zero-vertices (one degenerate, invisible triangle), not an empty
|
||||
// attribute: in accessory-reveal mode the segments-wrapper is shown, so these
|
||||
// meshes are drawn. An empty position (count 0) leaves WebGPU vertex buffer
|
||||
// slot 0 unbound and the draw is rejected, poisoning the command encoder.
|
||||
g.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(9), 3))
|
||||
// Match the four material slots the roof-segment renderer's material
|
||||
// array expects (0=top, 1=side, 2=interior, 3=shingle). Without these
|
||||
// groups, mesh.material is a single-material lookup that mismatches
|
||||
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
type GridEvent,
|
||||
type LevelNode,
|
||||
resolveAlignment,
|
||||
useAlignmentGuides,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import * as THREE from 'three'
|
||||
import { resolveCurrentBuildingId, resolveElevatorSupportY } from '../../../lib/elevator-support'
|
||||
|
||||
@@ -370,16 +370,19 @@ export const ceilingStrategy = {
|
||||
// use the ceiling hit's local position rather than world position.
|
||||
const x = snapToGrid(event.localPosition[0], swapDims ? dimZ : dimX)
|
||||
const z = snapToGrid(event.localPosition[2], swapDims ? dimX : dimZ)
|
||||
const worldSnapped = event.object.localToWorld(new Vector3(x, -itemHeight, z))
|
||||
// Recessed fixtures seat flush with the ceiling plane (body rising into the
|
||||
// void above); everything else hangs its full height below the ceiling.
|
||||
const seatY = ctx.asset.recessed ? 0 : -itemHeight
|
||||
const worldSnapped = event.object.localToWorld(new Vector3(x, seatY, z))
|
||||
|
||||
return {
|
||||
stateUpdate: { surface: 'ceiling', ceilingId: event.node.id },
|
||||
nodeUpdate: {
|
||||
position: [x, -itemHeight, z],
|
||||
position: [x, seatY, z],
|
||||
parentId: event.node.id,
|
||||
},
|
||||
cursorRotationY: 0,
|
||||
gridPosition: [x, -itemHeight, z],
|
||||
gridPosition: [x, seatY, z],
|
||||
cursorPosition: [worldSnapped.x, worldSnapped.y, worldSnapped.z],
|
||||
stopPropagation: true,
|
||||
}
|
||||
@@ -401,10 +404,13 @@ export const ceilingStrategy = {
|
||||
|
||||
const x = snapToGrid(event.localPosition[0], swapDims ? dimZ : dimX)
|
||||
const z = snapToGrid(event.localPosition[2], swapDims ? dimX : dimZ)
|
||||
const worldSnapped = event.object.localToWorld(new Vector3(x, -itemHeight, z))
|
||||
// Recessed fixtures seat flush with the ceiling plane (body rising into the
|
||||
// void above); everything else hangs its full height below the ceiling.
|
||||
const seatY = ctx.draftItem.asset.recessed ? 0 : -itemHeight
|
||||
const worldSnapped = event.object.localToWorld(new Vector3(x, seatY, z))
|
||||
|
||||
return {
|
||||
gridPosition: [x, -itemHeight, z],
|
||||
gridPosition: [x, seatY, z],
|
||||
cursorPosition: [worldSnapped.x, worldSnapped.y, worldSnapped.z],
|
||||
cursorRotationY: 0,
|
||||
nodeUpdate: null,
|
||||
|
||||
@@ -14,13 +14,13 @@ import {
|
||||
resolveLevelId,
|
||||
type ShelfEvent,
|
||||
sceneRegistry,
|
||||
useAlignmentGuides,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
useSpatialQuery,
|
||||
type WallEvent,
|
||||
type WallNode,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { Html } from '@react-three/drei'
|
||||
import { useFrame, useThree } from '@react-three/fiber'
|
||||
|
||||
@@ -15,10 +15,10 @@ import {
|
||||
resolveAlignment,
|
||||
sceneRegistry,
|
||||
spatialGridManager,
|
||||
useAlignmentGuides,
|
||||
useLiveTransforms,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { markToolCancelConsumed } from '../../../hooks/use-keyboard'
|
||||
|
||||
@@ -10,9 +10,9 @@ import {
|
||||
resolveAlignment,
|
||||
sceneRegistry,
|
||||
snapScalar,
|
||||
useAlignmentGuides,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import * as THREE from 'three'
|
||||
|
||||
@@ -12,9 +12,9 @@ import {
|
||||
StairNode,
|
||||
StairSegmentNode,
|
||||
syncAutoStairOpenings,
|
||||
useAlignmentGuides,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import * as THREE from 'three'
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useViewer } from '@pascal-app/viewer'
|
||||
import { type ComponentType, lazy, Suspense } from 'react'
|
||||
import useEditor, { type Phase, type Tool } from '../../store/use-editor'
|
||||
import { Alignment3DGuideLayer } from '../editor/alignment-3d-guide-layer'
|
||||
import { WallSnapBeaconLayer } from '../editor/wall-snap-beacon-layer'
|
||||
import { ElevatorTool } from './elevator/elevator-tool'
|
||||
import { MoveTool } from './item/move-tool'
|
||||
import { RoofTool } from './roof/roof-tool'
|
||||
@@ -281,6 +282,8 @@ export const ToolManager: React.FC = () => {
|
||||
tools above. Lives inside the building-local group so the
|
||||
building-local guide coords render at the right world position. */}
|
||||
<Alignment3DGuideLayer />
|
||||
{/* "Magnetic" beacon at the active wall-draft snap point. */}
|
||||
<WallSnapBeaconLayer />
|
||||
</group>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -3,10 +3,7 @@ import {
|
||||
type AnyNodeId,
|
||||
type DoorNode,
|
||||
getScaledDimensions,
|
||||
getWallCurveFrameAt,
|
||||
getWallCurveLength,
|
||||
type ItemNode,
|
||||
isCurvedWall,
|
||||
useScene,
|
||||
type WallNode,
|
||||
WallNode as WallSchema,
|
||||
@@ -15,19 +12,30 @@ import {
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { sfxEmitter } from '../../../lib/sfx-bus'
|
||||
import useEditor from '../../../store/use-editor'
|
||||
import {
|
||||
distanceSquared,
|
||||
findWallSnapTarget,
|
||||
findWallSpecialPointSnap,
|
||||
projectPointOntoWall,
|
||||
WALL_JOIN_SNAP_RADIUS,
|
||||
type WallDraftSnapResult,
|
||||
type WallPlanPoint,
|
||||
} from './wall-snap-geometry'
|
||||
|
||||
export type WallPlanPoint = [number, number]
|
||||
// The pure snap geometry lives in `./wall-snap-geometry`; re-exported here so
|
||||
// existing importers (fence drafting, the editor barrel) keep their paths.
|
||||
export {
|
||||
findWallSnapTarget,
|
||||
WALL_JOIN_SNAP_RADIUS,
|
||||
type WallDraftSnapKind,
|
||||
type WallDraftSnapResult,
|
||||
type WallPlanPoint,
|
||||
} from './wall-snap-geometry'
|
||||
|
||||
export const WALL_GRID_STEP = 0.5
|
||||
// Smallest available grid snap. Used as a precision-mode step (Shift +
|
||||
// drag) so a drag can land on values the regular grid skips.
|
||||
export const WALL_FINE_GRID_STEP = 0.05
|
||||
export const WALL_JOIN_SNAP_RADIUS = 0.35
|
||||
// Generous radius for snapping to an *existing* wall's endpoint while
|
||||
// drafting. Larger than `WALL_JOIN_SNAP_RADIUS` because endpoint snap
|
||||
// is the strongest user intent (closing a polygon, attaching to a
|
||||
// corner) and the cursor never lands pixel-perfect on a corner.
|
||||
export const WALL_ENDPOINT_SNAP_RADIUS = 0.7
|
||||
export const WALL_MIN_LENGTH = 0.01
|
||||
const DEFAULT_WALL_ANGLE_SNAP_STEP = Math.PI / 4
|
||||
|
||||
@@ -43,12 +51,6 @@ type WallSplitIntersection = {
|
||||
point: WallPlanPoint
|
||||
}
|
||||
|
||||
function distanceSquared(a: WallPlanPoint, b: WallPlanPoint): number {
|
||||
const dx = a[0] - b[0]
|
||||
const dz = a[1] - b[1]
|
||||
return dx * dx + dz * dz
|
||||
}
|
||||
|
||||
export function getSegmentGridStep(): number {
|
||||
return useEditor.getState().gridSnapStep
|
||||
}
|
||||
@@ -83,24 +85,6 @@ export function getWallAngleSnapStep(step = getSegmentGridStep()): number {
|
||||
return WALL_ANGLE_SNAP_BY_GRID_STEP[step] ?? DEFAULT_WALL_ANGLE_SNAP_STEP
|
||||
}
|
||||
|
||||
function projectPointOntoWall(point: WallPlanPoint, wall: WallNode): WallPlanPoint | null {
|
||||
const [x1, z1] = wall.start
|
||||
const [x2, z2] = wall.end
|
||||
const dx = x2 - x1
|
||||
const dz = z2 - z1
|
||||
const lengthSquared = dx * dx + dz * dz
|
||||
if (lengthSquared < 1e-9) {
|
||||
return null
|
||||
}
|
||||
|
||||
const t = ((point[0] - x1) * dx + (point[1] - z1) * dz) / lengthSquared
|
||||
if (t <= 0 || t >= 1) {
|
||||
return null
|
||||
}
|
||||
|
||||
return [x1 + dx * t, z1 + dz * t]
|
||||
}
|
||||
|
||||
function splitWallAtPoint(wall: WallNode, splitPoint: WallPlanPoint): [WallNode, WallNode] {
|
||||
const { id: _id, parentId: _parentId, children, ...rest } = wall
|
||||
|
||||
@@ -332,84 +316,7 @@ function splitWallIfNeeded(
|
||||
}
|
||||
}
|
||||
|
||||
export function findWallSnapTarget(
|
||||
point: WallPlanPoint,
|
||||
walls: WallNode[],
|
||||
options?: { ignoreWallIds?: string[]; radius?: number },
|
||||
): WallPlanPoint | null {
|
||||
const ignoreWallIds = new Set(options?.ignoreWallIds ?? [])
|
||||
const radiusSquared = (options?.radius ?? WALL_JOIN_SNAP_RADIUS) ** 2
|
||||
let bestTarget: WallPlanPoint | null = null
|
||||
let bestDistanceSquared = Number.POSITIVE_INFINITY
|
||||
|
||||
for (const wall of walls) {
|
||||
if (ignoreWallIds.has(wall.id)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const candidates: Array<WallPlanPoint | null> = [wall.start, wall.end]
|
||||
|
||||
if (isCurvedWall(wall)) {
|
||||
const sampleCount = Math.max(8, Math.ceil(getWallCurveLength(wall) / 0.3))
|
||||
for (let index = 0; index <= sampleCount; index += 1) {
|
||||
const frame = getWallCurveFrameAt(wall, index / sampleCount)
|
||||
candidates.push([frame.point.x, frame.point.y])
|
||||
}
|
||||
} else {
|
||||
candidates.push(projectPointOntoWall(point, wall))
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) {
|
||||
continue
|
||||
}
|
||||
|
||||
const candidateDistanceSquared = distanceSquared(point, candidate)
|
||||
if (
|
||||
candidateDistanceSquared > radiusSquared ||
|
||||
candidateDistanceSquared >= bestDistanceSquared
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
bestTarget = candidate
|
||||
bestDistanceSquared = candidateDistanceSquared
|
||||
}
|
||||
}
|
||||
|
||||
return bestTarget
|
||||
}
|
||||
|
||||
/**
|
||||
* Endpoint-only snap from the *raw* cursor (no grid pre-snap), with a
|
||||
* generous radius. Use this before `findWallSnapTarget` so the strong
|
||||
* "attach to an existing wall corner" intent isn't accidentally pushed
|
||||
* out of range by an interim grid snap that moved the cursor away from
|
||||
* the endpoint.
|
||||
*/
|
||||
function findWallEndpointFromRaw(
|
||||
point: WallPlanPoint,
|
||||
walls: WallNode[],
|
||||
ignoreWallIds?: string[],
|
||||
): WallPlanPoint | null {
|
||||
const ignored = new Set(ignoreWallIds ?? [])
|
||||
const radiusSquared = WALL_ENDPOINT_SNAP_RADIUS ** 2
|
||||
let best: WallPlanPoint | null = null
|
||||
let bestDistSq = Number.POSITIVE_INFINITY
|
||||
|
||||
for (const wall of walls) {
|
||||
if (ignored.has(wall.id)) continue
|
||||
for (const corner of [wall.start, wall.end] as WallPlanPoint[]) {
|
||||
const d = distanceSquared(point, corner)
|
||||
if (d <= radiusSquared && d < bestDistSq) {
|
||||
best = corner
|
||||
bestDistSq = d
|
||||
}
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
export function snapWallDraftPoint(args: {
|
||||
type SnapWallDraftArgs = {
|
||||
point: WallPlanPoint
|
||||
walls: WallNode[]
|
||||
start?: WallPlanPoint
|
||||
@@ -417,16 +324,33 @@ export function snapWallDraftPoint(args: {
|
||||
ignoreWallIds?: string[]
|
||||
/** Override the grid step (e.g. `WALL_FINE_GRID_STEP` for precision mode). */
|
||||
step?: number
|
||||
}): WallPlanPoint {
|
||||
const { point, walls, start, angleSnap = false, ignoreWallIds, step: overrideStep } = args
|
||||
/**
|
||||
* Magnetic snapping to existing wall geometry (corners, midpoints,
|
||||
* crossings, wall bodies). When `false`, only grid/angle snap applies and
|
||||
* `snap` is always `null`. Defaults to `true` so callers that don't care
|
||||
* keep the prior behaviour.
|
||||
*/
|
||||
magnetic?: boolean
|
||||
}
|
||||
|
||||
// Endpoint of an existing wall wins outright when the cursor is
|
||||
// anywhere within `WALL_ENDPOINT_SNAP_RADIUS` — closing a polygon or
|
||||
// attaching to a corner should "just work" without needing
|
||||
// pixel-perfect aim. Done from the raw cursor so it isn't masked by
|
||||
// an interim grid snap that nudged us out of range.
|
||||
const endpointSnap = findWallEndpointFromRaw(point, walls, ignoreWallIds)
|
||||
if (endpointSnap) return endpointSnap
|
||||
export function snapWallDraftPointDetailed(args: SnapWallDraftArgs): WallDraftSnapResult {
|
||||
const {
|
||||
point,
|
||||
walls,
|
||||
start,
|
||||
angleSnap = false,
|
||||
ignoreWallIds,
|
||||
step: overrideStep,
|
||||
magnetic = true,
|
||||
} = args
|
||||
|
||||
// Discrete special points (corner / midpoint / crossing) are taken from the
|
||||
// raw cursor so an interim grid snap can't mask them. A corner always wins,
|
||||
// then the nearer of midpoint / crossing — see `findWallSpecialPointSnap`.
|
||||
if (magnetic) {
|
||||
const special = findWallSpecialPointSnap(point, walls, ignoreWallIds)
|
||||
if (special) return special
|
||||
}
|
||||
|
||||
const step = overrideStep ?? getSegmentGridStep()
|
||||
const angleStep = getWallAngleSnapStep(step)
|
||||
@@ -435,11 +359,16 @@ export function snapWallDraftPoint(args: {
|
||||
? snapPointTo45Degrees(start, point, step, angleStep)
|
||||
: snapPointToGrid(point, step)
|
||||
|
||||
return (
|
||||
findWallSnapTarget(basePoint, walls, {
|
||||
ignoreWallIds,
|
||||
}) ?? basePoint
|
||||
)
|
||||
if (magnetic) {
|
||||
const wallSnap = findWallSnapTarget(basePoint, walls, { ignoreWallIds })
|
||||
if (wallSnap) return { point: wallSnap, snap: 'wall' }
|
||||
}
|
||||
|
||||
return { point: basePoint, snap: null }
|
||||
}
|
||||
|
||||
export function snapWallDraftPoint(args: SnapWallDraftArgs): WallPlanPoint {
|
||||
return snapWallDraftPointDetailed(args).point
|
||||
}
|
||||
|
||||
export function isSegmentLongEnough(start: WallPlanPoint, end: WallPlanPoint): boolean {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import type { WallNode } from '@pascal-app/core'
|
||||
import {
|
||||
findWallSnapTarget,
|
||||
findWallSpecialPointSnap,
|
||||
type WallPlanPoint,
|
||||
} from './wall-snap-geometry'
|
||||
|
||||
function makeWall(start: WallPlanPoint, end: WallPlanPoint, id?: string): WallNode {
|
||||
return {
|
||||
object: 'node',
|
||||
id: (id ?? `wall_${start.join('_')}_${end.join('_')}`) as WallNode['id'],
|
||||
type: 'wall',
|
||||
name: 'Wall',
|
||||
parentId: null,
|
||||
visible: true,
|
||||
metadata: {},
|
||||
children: [],
|
||||
start,
|
||||
end,
|
||||
thickness: 0.1,
|
||||
frontSide: 'unknown',
|
||||
backSide: 'unknown',
|
||||
} as unknown as WallNode
|
||||
}
|
||||
|
||||
describe('findWallSpecialPointSnap', () => {
|
||||
test('snaps to a wall corner (endpoint) when near it', () => {
|
||||
const walls = [makeWall([0, 0], [4, 0])]
|
||||
const result = findWallSpecialPointSnap([0.1, 0.1], walls)
|
||||
expect(result?.snap).toBe('endpoint')
|
||||
expect(result?.point).toEqual([0, 0])
|
||||
})
|
||||
|
||||
test('snaps to a wall midpoint when near it (not a corner)', () => {
|
||||
const walls = [makeWall([0, 0], [4, 0])]
|
||||
const result = findWallSpecialPointSnap([2.1, 0.2], walls)
|
||||
expect(result?.snap).toBe('midpoint')
|
||||
expect(result?.point).toEqual([2, 0])
|
||||
})
|
||||
|
||||
test('snaps to the crossing of two walls (intersection)', () => {
|
||||
// A runs along z=0; B crosses it at x=1. B's own midpoint is [1,1], far
|
||||
// from the crossing, so the snap is the intersection, not a midpoint.
|
||||
const walls = [makeWall([0, 0], [4, 0], 'a'), makeWall([1, -1], [1, 3], 'b')]
|
||||
const result = findWallSpecialPointSnap([1.1, 0.1], walls)
|
||||
expect(result?.snap).toBe('intersection')
|
||||
expect(result?.point[0]).toBeCloseTo(1, 6)
|
||||
expect(result?.point[1]).toBeCloseTo(0, 6)
|
||||
})
|
||||
|
||||
test('corner wins over a midpoint when both are in range', () => {
|
||||
const walls = [makeWall([0, 0], [1, 0])]
|
||||
const result = findWallSpecialPointSnap([0.9, 0.1], walls)
|
||||
expect(result?.snap).toBe('endpoint')
|
||||
expect(result?.point).toEqual([1, 0])
|
||||
})
|
||||
|
||||
test('returns null when no special point is in range', () => {
|
||||
const walls = [makeWall([0, 0], [4, 0])]
|
||||
// Near the wall body but far from corner/midpoint — that's an edge snap,
|
||||
// handled separately by findWallSnapTarget, not a special point.
|
||||
expect(findWallSpecialPointSnap([1.2, 0.1], walls)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('findWallSnapTarget (edge / along-wall)', () => {
|
||||
test('projects onto a wall body within range', () => {
|
||||
const walls = [makeWall([0, 0], [4, 0])]
|
||||
const result = findWallSnapTarget([1.2, 0.1], walls)
|
||||
expect(result?.[0]).toBeCloseTo(1.2, 6)
|
||||
expect(result?.[1]).toBeCloseTo(0, 6)
|
||||
})
|
||||
|
||||
test('returns null when too far from any wall', () => {
|
||||
const walls = [makeWall([0, 0], [4, 0])]
|
||||
expect(findWallSnapTarget([1.2, 2], walls)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,270 @@
|
||||
// Pure geometry for "magnetic" wall-draft snapping — no store / viewer / React
|
||||
// deps, so it's unit-testable in isolation. Coordinates are XZ plan points
|
||||
// (building-local meters). `wall-drafting.ts` layers grid/angle snapping and
|
||||
// scene access on top of these primitives.
|
||||
|
||||
import {
|
||||
getWallCurveFrameAt,
|
||||
getWallCurveLength,
|
||||
isCurvedWall,
|
||||
type WallNode,
|
||||
} from '@pascal-app/core'
|
||||
|
||||
export type WallPlanPoint = [number, number]
|
||||
|
||||
/** Which kind of existing-geometry snap produced a drafted point. */
|
||||
export type WallDraftSnapKind = 'endpoint' | 'midpoint' | 'intersection' | 'wall'
|
||||
|
||||
export type WallDraftSnapResult = {
|
||||
point: WallPlanPoint
|
||||
/**
|
||||
* Set when `point` locked onto existing wall geometry (a corner, midpoint,
|
||||
* crossing, or wall body) rather than a plain grid/angle position. This is
|
||||
* the "magnetic" snap the beacon visualises; `null` for grid/angle-only.
|
||||
*/
|
||||
snap: WallDraftSnapKind | null
|
||||
}
|
||||
|
||||
export const WALL_JOIN_SNAP_RADIUS = 0.35
|
||||
// Generous radius for snapping to an *existing* wall's endpoint while
|
||||
// drafting. Larger than `WALL_JOIN_SNAP_RADIUS` because endpoint snap
|
||||
// is the strongest user intent (closing a polygon, attaching to a
|
||||
// corner) and the cursor never lands pixel-perfect on a corner.
|
||||
export const WALL_ENDPOINT_SNAP_RADIUS = 0.7
|
||||
// Discrete "special point" snaps taken from the raw cursor (like the
|
||||
// endpoint snap) but slightly tighter — a corner is the strongest intent,
|
||||
// a midpoint / crossing is the next tier down.
|
||||
export const WALL_MIDPOINT_SNAP_RADIUS = 0.5
|
||||
export const WALL_INTERSECTION_SNAP_RADIUS = 0.5
|
||||
|
||||
export function distanceSquared(a: WallPlanPoint, b: WallPlanPoint): number {
|
||||
const dx = a[0] - b[0]
|
||||
const dz = a[1] - b[1]
|
||||
return dx * dx + dz * dz
|
||||
}
|
||||
|
||||
export function projectPointOntoWall(point: WallPlanPoint, wall: WallNode): WallPlanPoint | null {
|
||||
const [x1, z1] = wall.start
|
||||
const [x2, z2] = wall.end
|
||||
const dx = x2 - x1
|
||||
const dz = z2 - z1
|
||||
const lengthSquared = dx * dx + dz * dz
|
||||
if (lengthSquared < 1e-9) {
|
||||
return null
|
||||
}
|
||||
|
||||
const t = ((point[0] - x1) * dx + (point[1] - z1) * dz) / lengthSquared
|
||||
if (t <= 0 || t >= 1) {
|
||||
return null
|
||||
}
|
||||
|
||||
return [x1 + dx * t, z1 + dz * t]
|
||||
}
|
||||
|
||||
export function findWallSnapTarget(
|
||||
point: WallPlanPoint,
|
||||
walls: WallNode[],
|
||||
options?: { ignoreWallIds?: string[]; radius?: number },
|
||||
): WallPlanPoint | null {
|
||||
const ignoreWallIds = new Set(options?.ignoreWallIds ?? [])
|
||||
const radiusSquared = (options?.radius ?? WALL_JOIN_SNAP_RADIUS) ** 2
|
||||
let bestTarget: WallPlanPoint | null = null
|
||||
let bestDistanceSquared = Number.POSITIVE_INFINITY
|
||||
|
||||
for (const wall of walls) {
|
||||
if (ignoreWallIds.has(wall.id)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const candidates: Array<WallPlanPoint | null> = [wall.start, wall.end]
|
||||
|
||||
if (isCurvedWall(wall)) {
|
||||
const sampleCount = Math.max(8, Math.ceil(getWallCurveLength(wall) / 0.3))
|
||||
for (let index = 0; index <= sampleCount; index += 1) {
|
||||
const frame = getWallCurveFrameAt(wall, index / sampleCount)
|
||||
candidates.push([frame.point.x, frame.point.y])
|
||||
}
|
||||
} else {
|
||||
candidates.push(projectPointOntoWall(point, wall))
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) {
|
||||
continue
|
||||
}
|
||||
|
||||
const candidateDistanceSquared = distanceSquared(point, candidate)
|
||||
if (
|
||||
candidateDistanceSquared > radiusSquared ||
|
||||
candidateDistanceSquared >= bestDistanceSquared
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
bestTarget = candidate
|
||||
bestDistanceSquared = candidateDistanceSquared
|
||||
}
|
||||
}
|
||||
|
||||
return bestTarget
|
||||
}
|
||||
|
||||
/**
|
||||
* Endpoint-only snap from the *raw* cursor (no grid pre-snap), with a
|
||||
* generous radius. Use this before `findWallSnapTarget` so the strong
|
||||
* "attach to an existing wall corner" intent isn't accidentally pushed
|
||||
* out of range by an interim grid snap that moved the cursor away from
|
||||
* the endpoint.
|
||||
*/
|
||||
export function findWallEndpointFromRaw(
|
||||
point: WallPlanPoint,
|
||||
walls: WallNode[],
|
||||
ignoreWallIds?: string[],
|
||||
): WallPlanPoint | null {
|
||||
const ignored = new Set(ignoreWallIds ?? [])
|
||||
const radiusSquared = WALL_ENDPOINT_SNAP_RADIUS ** 2
|
||||
let best: WallPlanPoint | null = null
|
||||
let bestDistSq = Number.POSITIVE_INFINITY
|
||||
|
||||
for (const wall of walls) {
|
||||
if (ignored.has(wall.id)) continue
|
||||
for (const corner of [wall.start, wall.end] as WallPlanPoint[]) {
|
||||
const d = distanceSquared(point, corner)
|
||||
if (d <= radiusSquared && d < bestDistSq) {
|
||||
best = corner
|
||||
bestDistSq = d
|
||||
}
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** Midpoint of a wall — curve midpoint for curved walls, segment midpoint otherwise. */
|
||||
function wallMidpoint(wall: WallNode): WallPlanPoint {
|
||||
if (isCurvedWall(wall)) {
|
||||
const frame = getWallCurveFrameAt(wall, 0.5)
|
||||
return [frame.point.x, frame.point.y]
|
||||
}
|
||||
return [(wall.start[0] + wall.end[0]) / 2, (wall.start[1] + wall.end[1]) / 2]
|
||||
}
|
||||
|
||||
/** Nearest wall midpoint to the raw cursor, within `WALL_MIDPOINT_SNAP_RADIUS`. */
|
||||
export function findWallMidpointFromRaw(
|
||||
point: WallPlanPoint,
|
||||
walls: WallNode[],
|
||||
ignoreWallIds?: string[],
|
||||
): WallPlanPoint | null {
|
||||
const ignored = new Set(ignoreWallIds ?? [])
|
||||
const radiusSquared = WALL_MIDPOINT_SNAP_RADIUS ** 2
|
||||
let best: WallPlanPoint | null = null
|
||||
let bestDistSq = Number.POSITIVE_INFINITY
|
||||
|
||||
for (const wall of walls) {
|
||||
if (ignored.has(wall.id)) continue
|
||||
const mid = wallMidpoint(wall)
|
||||
const d = distanceSquared(point, mid)
|
||||
if (d <= radiusSquared && d < bestDistSq) {
|
||||
best = mid
|
||||
bestDistSq = d
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** Crossing point of two straight segments, or null if they don't intersect within both. */
|
||||
function segmentIntersection(
|
||||
a1: WallPlanPoint,
|
||||
a2: WallPlanPoint,
|
||||
b1: WallPlanPoint,
|
||||
b2: WallPlanPoint,
|
||||
): WallPlanPoint | null {
|
||||
const rx = a2[0] - a1[0]
|
||||
const rz = a2[1] - a1[1]
|
||||
const sx = b2[0] - b1[0]
|
||||
const sz = b2[1] - b1[1]
|
||||
const denom = rx * sz - rz * sx
|
||||
if (Math.abs(denom) < 1e-9) return null // parallel / collinear
|
||||
|
||||
const qpx = b1[0] - a1[0]
|
||||
const qpz = b1[1] - a1[1]
|
||||
const t = (qpx * sz - qpz * sx) / denom
|
||||
const u = (qpx * rz - qpz * rx) / denom
|
||||
if (t < 0 || t > 1 || u < 0 || u > 1) return null
|
||||
|
||||
return [a1[0] + t * rx, a1[1] + t * rz]
|
||||
}
|
||||
|
||||
/**
|
||||
* Nearest point where two existing straight walls cross, within
|
||||
* `WALL_INTERSECTION_SNAP_RADIUS`. Curved walls are skipped. O(n²) over the
|
||||
* level's walls — fine at editor scale.
|
||||
*/
|
||||
export function findWallIntersectionFromRaw(
|
||||
point: WallPlanPoint,
|
||||
walls: WallNode[],
|
||||
ignoreWallIds?: string[],
|
||||
): WallPlanPoint | null {
|
||||
const ignored = new Set(ignoreWallIds ?? [])
|
||||
const straight = walls.filter((wall) => !ignored.has(wall.id) && !isCurvedWall(wall))
|
||||
const radiusSquared = WALL_INTERSECTION_SNAP_RADIUS ** 2
|
||||
let best: WallPlanPoint | null = null
|
||||
let bestDistSq = Number.POSITIVE_INFINITY
|
||||
|
||||
for (let i = 0; i < straight.length; i += 1) {
|
||||
for (let j = i + 1; j < straight.length; j += 1) {
|
||||
const crossing = segmentIntersection(
|
||||
straight[i]!.start,
|
||||
straight[i]!.end,
|
||||
straight[j]!.start,
|
||||
straight[j]!.end,
|
||||
)
|
||||
if (!crossing) continue
|
||||
const d = distanceSquared(point, crossing)
|
||||
if (d <= radiusSquared && d < bestDistSq) {
|
||||
best = crossing
|
||||
bestDistSq = d
|
||||
}
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** Pick the candidate nearest to `point`, ignoring nulls. */
|
||||
function nearestCandidate(
|
||||
point: WallPlanPoint,
|
||||
candidates: Array<WallDraftSnapResult | null | false>,
|
||||
): WallDraftSnapResult | null {
|
||||
let best: WallDraftSnapResult | null = null
|
||||
let bestDistSq = Number.POSITIVE_INFINITY
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue
|
||||
const d = distanceSquared(point, candidate.point)
|
||||
if (d < bestDistSq) {
|
||||
best = candidate
|
||||
bestDistSq = d
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/**
|
||||
* Discrete "special point" snap from the raw cursor, in priority order:
|
||||
* 1. corners (endpoints) — strongest intent, largest radius
|
||||
* 2. midpoints / crossings — next tier; the nearer of the two wins
|
||||
* A corner within range always wins over a midpoint/crossing. Returns null
|
||||
* when no special point is in range (caller falls back to grid/edge snap).
|
||||
*/
|
||||
export function findWallSpecialPointSnap(
|
||||
point: WallPlanPoint,
|
||||
walls: WallNode[],
|
||||
ignoreWallIds?: string[],
|
||||
): WallDraftSnapResult | null {
|
||||
const endpoint = findWallEndpointFromRaw(point, walls, ignoreWallIds)
|
||||
if (endpoint) return { point: endpoint, snap: 'endpoint' }
|
||||
|
||||
const midpoint = findWallMidpointFromRaw(point, walls, ignoreWallIds)
|
||||
const intersection = findWallIntersectionFromRaw(point, walls, ignoreWallIds)
|
||||
return nearestCandidate(point, [
|
||||
midpoint && { point: midpoint, snap: 'midpoint' },
|
||||
intersection && { point: intersection, snap: 'intersection' },
|
||||
])
|
||||
}
|
||||
@@ -628,6 +628,7 @@ export const CATALOG_ITEMS: AssetInput[] = [
|
||||
rotation: [0, 0, 0],
|
||||
scale: [1, 1, 1],
|
||||
attachTo: 'ceiling',
|
||||
recessed: true,
|
||||
interactive: {
|
||||
controls: [
|
||||
{ kind: 'toggle' },
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import {
|
||||
type AnyNodeId,
|
||||
type CeilingEvent,
|
||||
type CeilingNode,
|
||||
emitter,
|
||||
resolveLevelId,
|
||||
sceneRegistry,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useViewer } from '@pascal-app/viewer'
|
||||
import { useThree } from '@react-three/fiber'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { type Object3D, Plane, Raycaster, Vector2, Vector3 } from 'three'
|
||||
import useEditor from '../store/use-editor'
|
||||
|
||||
const UP = new Vector3(0, 1, 0)
|
||||
|
||||
/** Ray-casting point-in-polygon on ceiling-local [x, z] tuples. */
|
||||
function pointInPolygon(x: number, z: number, polygon: Array<[number, number]>): boolean {
|
||||
let inside = false
|
||||
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
|
||||
const a = polygon[i]!
|
||||
const b = polygon[j]!
|
||||
const intersects =
|
||||
a[1] > z !== b[1] > z && x < ((b[0] - a[0]) * (z - a[1])) / (b[1] - a[1]) + a[0]
|
||||
if (intersects) inside = !inside
|
||||
}
|
||||
return inside
|
||||
}
|
||||
|
||||
/**
|
||||
* Reliable pointer events for placing ceiling-attached items.
|
||||
*
|
||||
* Mirrors {@link useGridEvents} (the floor path): rather than relying on the
|
||||
* thin, single-sided `ceiling-grid` overlay mesh to be hit by R3F's raycaster —
|
||||
* which misses from the "wrong" camera side, near polygon edges/holes, or while
|
||||
* the overlay is mid-reveal, dropping the commit click even though the green box
|
||||
* still shows — it intersects a math plane at each ceiling's height (double-sided,
|
||||
* so it hits from above or below) and point-in-polygon tests the hit. Emits
|
||||
* `ceiling:enter/move/leave/click` so both the placement coordinator and the 2D
|
||||
* floor-plan item preview keep working.
|
||||
*
|
||||
* Active only while a ceiling-attached item is being placed or moved. The
|
||||
* `ceiling-grid` mesh no longer emits these events (see `CeilingRenderer`), so
|
||||
* this is the single, reliable source.
|
||||
*/
|
||||
export function useCeilingEvents() {
|
||||
const { camera, gl } = useThree()
|
||||
const raycaster = useRef(new Raycaster())
|
||||
const pointer = useRef(new Vector2())
|
||||
const plane = useRef(new Plane(UP.clone(), 0))
|
||||
const worldHit = useRef(new Vector3())
|
||||
const meshWorld = useRef(new Vector3())
|
||||
const hoveredRef = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = gl.domElement
|
||||
|
||||
const isActive = (): boolean => {
|
||||
const ed = useEditor.getState()
|
||||
if (ed.selectedItem?.attachTo === 'ceiling') return true
|
||||
const moving = ed.movingNode
|
||||
return moving?.type === 'item' && moving.asset?.attachTo === 'ceiling'
|
||||
}
|
||||
|
||||
type Hit = { node: CeilingNode; mesh: Object3D; world: Vector3; local: Vector3 }
|
||||
|
||||
// The ceiling on the active level whose plane the cursor ray crosses inside
|
||||
// its polygon, nearest the camera.
|
||||
const pick = (nativeEvent: PointerEvent | MouseEvent): Hit | null => {
|
||||
const activeLevelId = useViewer.getState().selection.levelId
|
||||
if (!activeLevelId) return null
|
||||
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
pointer.current.x = ((nativeEvent.clientX - rect.left) / rect.width) * 2 - 1
|
||||
pointer.current.y = -((nativeEvent.clientY - rect.top) / rect.height) * 2 + 1
|
||||
raycaster.current.setFromCamera(pointer.current, camera)
|
||||
|
||||
const nodes = useScene.getState().nodes
|
||||
const ceilingIds = sceneRegistry.byType.ceiling
|
||||
if (!ceilingIds) return null
|
||||
|
||||
let best: Hit | null = null
|
||||
let bestDist = Number.POSITIVE_INFINITY
|
||||
|
||||
for (const id of ceilingIds) {
|
||||
const node = nodes[id as AnyNodeId] as CeilingNode | undefined
|
||||
if (!node || node.type !== 'ceiling' || node.polygon.length < 3) continue
|
||||
if (resolveLevelId(node, nodes) !== activeLevelId) continue
|
||||
const mesh = sceneRegistry.nodes.get(id)
|
||||
if (!mesh) continue
|
||||
|
||||
mesh.getWorldPosition(meshWorld.current)
|
||||
plane.current.set(UP, -meshWorld.current.y)
|
||||
if (!raycaster.current.ray.intersectPlane(plane.current, worldHit.current)) continue
|
||||
|
||||
const local = mesh.worldToLocal(worldHit.current.clone())
|
||||
if (!pointInPolygon(local.x, local.z, node.polygon)) continue
|
||||
|
||||
const dist = raycaster.current.ray.origin.distanceToSquared(worldHit.current)
|
||||
if (dist < bestDist) {
|
||||
bestDist = dist
|
||||
best = { node, mesh, world: worldHit.current.clone(), local }
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
const buildEvent = (hit: Hit, nativeEvent: PointerEvent | MouseEvent): CeilingEvent => ({
|
||||
node: hit.node,
|
||||
position: [hit.world.x, hit.world.y, hit.world.z],
|
||||
localPosition: [hit.local.x, hit.local.y, hit.local.z],
|
||||
normal: [0, 1, 0],
|
||||
object: hit.mesh,
|
||||
stopPropagation: () => {},
|
||||
nativeEvent: nativeEvent as never,
|
||||
})
|
||||
|
||||
const emitLeave = (nativeEvent: PointerEvent | MouseEvent) => {
|
||||
const id = hoveredRef.current
|
||||
if (!id) return
|
||||
hoveredRef.current = null
|
||||
const node = useScene.getState().nodes[id as AnyNodeId] as CeilingNode | undefined
|
||||
const mesh = sceneRegistry.nodes.get(id)
|
||||
if (!node || !mesh) return
|
||||
emitter.emit(
|
||||
'ceiling:leave',
|
||||
buildEvent(
|
||||
{ node, mesh, world: meshWorld.current.clone(), local: new Vector3() },
|
||||
nativeEvent,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const onMove = (e: PointerEvent) => {
|
||||
if (!isActive()) {
|
||||
emitLeave(e)
|
||||
return
|
||||
}
|
||||
const hit = pick(e)
|
||||
if (!hit) {
|
||||
emitLeave(e)
|
||||
return
|
||||
}
|
||||
const ev = buildEvent(hit, e)
|
||||
if (hoveredRef.current !== hit.node.id) {
|
||||
if (hoveredRef.current) emitLeave(e)
|
||||
hoveredRef.current = hit.node.id
|
||||
emitter.emit('ceiling:enter', ev)
|
||||
}
|
||||
emitter.emit('ceiling:move', ev)
|
||||
}
|
||||
|
||||
const onClick = (e: MouseEvent) => {
|
||||
if (useViewer.getState().cameraDragging) return
|
||||
if (e.button !== 0) return
|
||||
if (!isActive()) return
|
||||
const hit = pick(e)
|
||||
if (!hit) return
|
||||
emitter.emit('ceiling:click', buildEvent(hit, e))
|
||||
}
|
||||
|
||||
const onPointerLeave = (e: PointerEvent) => emitLeave(e)
|
||||
|
||||
canvas.addEventListener('pointermove', onMove)
|
||||
canvas.addEventListener('click', onClick)
|
||||
canvas.addEventListener('pointerleave', onPointerLeave)
|
||||
|
||||
return () => {
|
||||
canvas.removeEventListener('pointermove', onMove)
|
||||
canvas.removeEventListener('click', onClick)
|
||||
canvas.removeEventListener('pointerleave', onPointerLeave)
|
||||
}
|
||||
}, [camera, gl])
|
||||
}
|
||||
@@ -102,7 +102,10 @@ export {
|
||||
snapPointToGrid,
|
||||
snapScalarToGrid,
|
||||
snapWallDraftPoint,
|
||||
snapWallDraftPointDetailed,
|
||||
WALL_FINE_GRID_STEP,
|
||||
type WallDraftSnapKind,
|
||||
type WallDraftSnapResult,
|
||||
type WallPlanPoint,
|
||||
} from './components/tools/wall/wall-drafting'
|
||||
// `ToolbarLeft` / `ToolbarRight` are the headless-spec aliases for the
|
||||
@@ -234,6 +237,7 @@ export {
|
||||
// nodes` so they don't need their own copy / their own tailwind-merge
|
||||
// dependency.
|
||||
export { cn } from './lib/utils'
|
||||
export { default as useAlignmentGuides } from './store/use-alignment-guides'
|
||||
export { default as useAudio } from './store/use-audio'
|
||||
export { type CommandAction, useCommandRegistry } from './store/use-command-registry'
|
||||
export type {
|
||||
@@ -255,3 +259,8 @@ export {
|
||||
export { default as usePlacementPreview } from './store/use-placement-preview'
|
||||
export { useUploadStore } from './store/use-upload'
|
||||
export { useWallMoveGhosts, type WallMoveGhostBridge } from './store/use-wall-move-ghosts'
|
||||
export {
|
||||
default as useWallSnapIndicator,
|
||||
type WallSnapKind,
|
||||
type WallSnapPoint,
|
||||
} from './store/use-wall-snap-indicator'
|
||||
|
||||
@@ -3,9 +3,9 @@ import {
|
||||
type AlignmentGuide,
|
||||
collectAlignmentAnchors,
|
||||
resolveAlignment,
|
||||
useAlignmentGuides,
|
||||
useScene,
|
||||
} from '@pascal-app/core'
|
||||
import { useAlignmentGuides } from '@pascal-app/editor'
|
||||
|
||||
/**
|
||||
* Fixed Figma-style alignment threshold (meters) for floor-plan placement /
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Ephemeral store for Figma-style alignment guides published during a
|
||||
// move / placement drag. The producer (a tool or move overlay) writes
|
||||
// guides on pointermove; the renderer (a 2D / 3D guide layer) subscribes
|
||||
// and draws them. Both sides clear on commit, cancel, and unmount.
|
||||
|
||||
import type { AlignmentGuide } from '@pascal-app/core'
|
||||
import { create } from 'zustand'
|
||||
|
||||
type AlignmentGuidesState = {
|
||||
guides: AlignmentGuide[]
|
||||
set(guides: AlignmentGuide[]): void
|
||||
clear(): void
|
||||
}
|
||||
|
||||
const useAlignmentGuides = create<AlignmentGuidesState>((set) => ({
|
||||
guides: [],
|
||||
set: (guides) => set({ guides }),
|
||||
clear: () => set({ guides: [] }),
|
||||
}))
|
||||
|
||||
export default useAlignmentGuides
|
||||
@@ -344,6 +344,11 @@ type EditorState = {
|
||||
setFloorplanSelectionTool: (tool: FloorplanSelectionTool) => void
|
||||
gridSnapStep: GridSnapStep
|
||||
setGridSnapStep: (step: GridSnapStep) => void
|
||||
// Magnetic snapping while drafting — snaps wall endpoints onto existing
|
||||
// wall corners / wall bodies (the "magnetic" beacon). Independent of grid
|
||||
// snap. On by default; toggled from the Display menu.
|
||||
magneticSnap: boolean
|
||||
setMagneticSnap: (enabled: boolean) => void
|
||||
showReferenceFloor: boolean
|
||||
toggleReferenceFloor: () => void
|
||||
setShowReferenceFloor: (show: boolean) => void
|
||||
@@ -386,6 +391,7 @@ type PersistedEditorLayoutState = Pick<
|
||||
| 'splitOrientation'
|
||||
| 'floorplanSelectionTool'
|
||||
| 'gridSnapStep'
|
||||
| 'magneticSnap'
|
||||
| 'showReferenceFloor'
|
||||
| 'referenceFloorOffset'
|
||||
| 'referenceFloorOpacity'
|
||||
@@ -408,6 +414,7 @@ export const DEFAULT_PERSISTED_EDITOR_LAYOUT_STATE: PersistedEditorLayoutState =
|
||||
splitOrientation: 'horizontal',
|
||||
floorplanSelectionTool: 'click',
|
||||
gridSnapStep: 0.5,
|
||||
magneticSnap: true,
|
||||
showReferenceFloor: false,
|
||||
referenceFloorOffset: 1,
|
||||
referenceFloorOpacity: 0.35,
|
||||
@@ -520,6 +527,8 @@ function normalizePersistedEditorLayoutState(
|
||||
gridSnapStep: GRID_SNAP_STEPS.includes(state?.gridSnapStep as GridSnapStep)
|
||||
? (state?.gridSnapStep as GridSnapStep)
|
||||
: DEFAULT_PERSISTED_EDITOR_LAYOUT_STATE.gridSnapStep,
|
||||
// Default on: only an explicit persisted `false` disables it.
|
||||
magneticSnap: state?.magneticSnap !== false,
|
||||
showReferenceFloor: state?.showReferenceFloor === true,
|
||||
referenceFloorOffset:
|
||||
typeof state?.referenceFloorOffset === 'number' && state.referenceFloorOffset >= 1
|
||||
@@ -876,6 +885,8 @@ const useEditor = create<EditorState>()(
|
||||
setFloorplanSelectionTool: (tool) => set({ floorplanSelectionTool: tool }),
|
||||
gridSnapStep: DEFAULT_PERSISTED_EDITOR_LAYOUT_STATE.gridSnapStep,
|
||||
setGridSnapStep: (step) => set({ gridSnapStep: step }),
|
||||
magneticSnap: DEFAULT_PERSISTED_EDITOR_LAYOUT_STATE.magneticSnap,
|
||||
setMagneticSnap: (enabled) => set({ magneticSnap: enabled }),
|
||||
showReferenceFloor: DEFAULT_PERSISTED_EDITOR_LAYOUT_STATE.showReferenceFloor,
|
||||
toggleReferenceFloor: () =>
|
||||
set((state) => ({ showReferenceFloor: !state.showReferenceFloor })),
|
||||
@@ -965,6 +976,7 @@ const useEditor = create<EditorState>()(
|
||||
splitOrientation: state.splitOrientation,
|
||||
floorplanSelectionTool: state.floorplanSelectionTool,
|
||||
gridSnapStep: state.gridSnapStep,
|
||||
magneticSnap: state.magneticSnap,
|
||||
showReferenceFloor: state.showReferenceFloor,
|
||||
referenceFloorOffset: state.referenceFloorOffset,
|
||||
referenceFloorOpacity: state.referenceFloorOpacity,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Ephemeral store for the "magnetic" wall-snap beacon shown during wall
|
||||
// drafting. The wall tool writes the active snap point on pointermove when
|
||||
// the draft endpoint locks onto existing wall geometry (a corner or a point
|
||||
// along a wall); the 3D beacon layer subscribes and draws a vertical marker
|
||||
// there. Cleared on commit, cancel, and unmount — same lifecycle as
|
||||
// `use-alignment-guides`.
|
||||
|
||||
import { create } from 'zustand'
|
||||
|
||||
/** Which kind of wall geometry the draft point snapped to. */
|
||||
export type WallSnapKind = 'endpoint' | 'midpoint' | 'intersection' | 'wall'
|
||||
|
||||
export type WallSnapPoint = {
|
||||
/** Building-local plan coordinates (XZ meters). */
|
||||
x: number
|
||||
z: number
|
||||
kind: WallSnapKind
|
||||
}
|
||||
|
||||
type WallSnapIndicatorState = {
|
||||
point: WallSnapPoint | null
|
||||
set(point: WallSnapPoint | null): void
|
||||
clear(): void
|
||||
}
|
||||
|
||||
const useWallSnapIndicator = create<WallSnapIndicatorState>((set) => ({
|
||||
point: null,
|
||||
set: (point) => set({ point }),
|
||||
clear: () => set({ point: null }),
|
||||
}))
|
||||
|
||||
export default useWallSnapIndicator
|
||||
Reference in New Issue
Block a user