Phase 5 Stage E: full kind migration into packages/nodes

Wholesale move of every remaining kind into its own subdirectory under
`packages/nodes/src/`, finishing the registry-driven migration. Each
kind now ships its definition, schema (re-exported from core), and any
of `geometry` / `renderer` / `system` / `floorplan` / `tool` /
`move-tool` / `panel` / `floorplan-move` / `floorplan-affordances` /
`parametrics` / `preview` it needs — no per-kind code remains under
`packages/editor/src/components/tools/` or
`packages/viewer/src/components/renderers/`.

Deleted (replaced by registry-driven equivalents):
- `tools/{ceiling,column,door,fence,item,slab,spawn,wall,window}/...`
  (boundary editors, hole editors, placement tools, move tools,
  endpoint movers, curve tools, helpers, math libs)
- `ui/helpers/{ceiling,slab,wall}-helper.tsx`
- `ui/panels/{column,door,elevator,item,roof,roof-segment,spawn,
  stair,stair-segment,wall,window}-panel.tsx`
- `viewer/src/components/renderers/{building,ceiling,column,door,
  elevator,fence,guide,item,level,roof,roof-segment,scan,site,slab,
  spawn,stair,stair-segment,wall,window,zone}-renderer.tsx`
- `viewer/src/components/viewer/legacy-system.tsx`

Added under `packages/nodes/src/`:
- `building/`, `column/`, `elevator/`, `guide/`, `level/`, `roof/`,
  `roof-segment/`, `scan/`, `shared/`, `site/`, `stair/`,
  `stair-segment/` packages with definition + schema + renderer / system
  / floorplan / panel as appropriate.
- New `floorplan-move.ts` for every kind that supports 2D moves
  (ceiling, door, item, shelf, slab, window) — single registry-driven
  dispatch path via `def.floorplanMoveTarget`.
- New `floorplan-affordances.ts` for kinds with polygon / endpoint
  drags (ceiling, fence, slab, wall) — using the shared
  `polygon-vertex-affordance` factories.
- New per-kind `panel.tsx` for kinds with custom inspector content
  (door, item, shelf, spawn, wall, window).
- New per-kind `tool.tsx` for placement (door, item, shelf, window).
- New per-kind `move-tool.tsx` for kinds with custom 3D move flows
  (door, item, slab, window).

Coordinator + manager updates in `packages/editor/`:
- `tool-manager.tsx` resolves tools from the registry only — no
  hardcoded type→component map.
- `panel-manager.tsx` resolves inspector panels the same way.
- `placement-{coordinator,strategies,types}.ts` extended with
  shelf-surface placement.
- `selection-manager.tsx` adds the registry-selectable fallback.
- `floorplan-panel.tsx`, `floorplan-background-placement.ts`,
  `floorplan-render-context.tsx` updated for the registry layer's new
  contract (props, affordance dispatch, render context).

Viewer updates:
- `viewer/index.tsx` drops legacy renderer mounts.
- `node-renderer.tsx` resolves by registry only.
- `scene-bvh.tsx`, `use-node-events.ts`, `level-system.tsx`,
  `wall-cutout.tsx`, `zone-system.tsx`, `materials.ts` adjusted for
  the registry-only world.

Sidebar tree nodes for ceiling / fence / slab / shelf / tree-node
updated to read from the registered nodes instead of the deleted
legacy renderer trees.

Wiki: new `plugin-authoring.md` page, README index updated.

Tests in `packages/nodes/src/index.test.ts` validate every registered
kind has the required shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Wassim SAMAD
2026-05-19 15:14:12 -04:00
co-authored by Claude Opus 4.7
parent 11015ea1ed
commit d747d2f0ea
204 changed files with 6888 additions and 7877 deletions
+18
View File
@@ -1,5 +1,11 @@
import type { NodeDefinition } from '@pascal-app/core'
import { buildCeilingFloorplan } from './floorplan'
import {
ceilingAddVertexAffordance,
ceilingMoveEdgeAffordance,
ceilingMoveVertexAffordance,
} from './floorplan-affordances'
import { ceilingFloorplanMoveTarget } from './floorplan-move'
import { ceilingParametrics } from './parametrics'
import { CeilingNode } from './schema'
@@ -76,6 +82,18 @@ export const ceilingDefinition: NodeDefinition<typeof CeilingNode> = {
priority: 4,
},
floorplan: buildCeilingFloorplan,
// 2D move handler — translates polygon by cursor delta from first
// pointer position. Mirror of slab; 3D `MoveCeilingTool` skips
// 2D-sourced grid events so they don't double-write on commit.
floorplanMoveTarget: ceilingFloorplanMoveTarget,
// Sister to `affordanceTools['boundary-edit']`. Same `polygon` field;
// SVG vertex handles dispatch to this affordance via the floor-plan
// registry layer.
floorplanAffordances: {
'move-vertex': ceilingMoveVertexAffordance,
'add-vertex': ceilingAddVertexAffordance,
'move-edge': ceilingMoveEdgeAffordance,
},
toolHints: [
{ key: 'Left click', label: 'Trace ceiling outline' },
@@ -0,0 +1,16 @@
import type { CeilingNode } from '@pascal-app/core'
import {
createPolygonAddVertexAffordance,
createPolygonMoveEdgeAffordance,
createPolygonVertexAffordance,
} from '../shared/polygon-vertex-affordance'
/**
* 2D drag affordances for ceiling. Same three operations as slab
* (`move-vertex`, `add-vertex`, `move-edge`), each accepting an
* optional `holeIndex`. See `slab/floorplan-affordances.ts` for the
* full contract.
*/
export const ceilingMoveVertexAffordance = createPolygonVertexAffordance<CeilingNode>('ceiling')
export const ceilingAddVertexAffordance = createPolygonAddVertexAffordance<CeilingNode>('ceiling')
export const ceilingMoveEdgeAffordance = createPolygonMoveEdgeAffordance<CeilingNode>('ceiling')
@@ -0,0 +1,88 @@
import {
type AnyNodeId,
type CeilingNode,
type FloorplanMoveTarget,
type FloorplanMoveTargetSession,
sceneRegistry,
useLiveTransforms,
useScene,
} from '@pascal-app/core'
import { snapPointToGrid, type WallPlanPoint } from '@pascal-app/editor'
import type * as THREE from 'three'
/**
* 2D floor-plan move handler for ceiling — mirrors the 3D `MoveCeilingTool`
* live-drag pattern. See the equivalent module in `slab/floorplan-move.ts`
* for the full rationale; the only ceiling-specific detail is the
* preserved Y offset (`CeilingSystem` positions the mesh at `height 0.01`
* on rebuild, so the direct `mesh.position.y` mirrors that to avoid a
* vertical teleport when the React group position is reconciled).
*/
const GRID_STEP = 0.5
function translatePolygon(
polygon: ReadonlyArray<readonly [number, number]>,
dx: number,
dz: number,
): Array<[number, number]> {
return polygon.map(([x, z]) => [x + dx, z + dz] as [number, number])
}
export const ceilingFloorplanMoveTarget: FloorplanMoveTarget<CeilingNode> = ({ node }) => {
const ceilingId = node.id as AnyNodeId
const originalPolygon = node.polygon.map(([x, z]) => [x, z] as [number, number])
const originalHoles = (node.holes ?? []).map((hole) =>
hole.map(([x, z]) => [x, z] as [number, number]),
)
const height = node.height ?? 2.5
let anchor: [number, number] | null = null
let lastDelta: [number, number] = [0, 0]
const session: FloorplanMoveTargetSession = {
affectedIds: [ceilingId],
apply({ planPoint, modifiers }) {
const snapped: WallPlanPoint = modifiers.shiftKey
? ([planPoint[0], planPoint[1]] as WallPlanPoint)
: snapPointToGrid([planPoint[0], planPoint[1]] as WallPlanPoint, GRID_STEP)
if (!anchor) {
anchor = [snapped[0], snapped[1]]
return
}
const dx = snapped[0] - anchor[0]
const dz = snapped[1] - anchor[1]
lastDelta = [dx, dz]
useLiveTransforms.getState().set(ceilingId, {
position: [dx, 0, dz],
rotation: 0,
})
const mesh = sceneRegistry.nodes.get(ceilingId) as THREE.Object3D | undefined
// Preserve ceiling height — `CeilingSystem` sets `mesh.position.y =
// height 0.01` on each rebuild; mirror that during the drag so
// the mesh stays at ceiling height (not collapsed to y=0).
if (mesh) mesh.position.set(dx, height - 0.01, dz)
},
canCommit() {
const live = useScene.getState().nodes[ceilingId] as CeilingNode | undefined
if (!live || live.type !== 'ceiling') return false
const [dx, dz] = lastDelta
if (dx === 0 && dz === 0) return false
// Sync commit sequence — see `slab/floorplan-move.ts` for the
// full ordering rationale (scene write → direct markDirty →
// useLiveTransforms.clear, all sync in this handler so React
// render + CeilingSystem rebuild land in the same paint).
useScene.getState().updateNodes([
{
id: ceilingId,
data: {
polygon: translatePolygon(originalPolygon, dx, dz),
holes: originalHoles.map((h) => translatePolygon(h, dx, dz)),
},
},
])
useScene.getState().markDirty(ceilingId)
useLiveTransforms.getState().clear(ceilingId)
return true
},
}
return session
}
+86 -14
View File
@@ -1,15 +1,29 @@
import type { CeilingNode, FloorplanGeometry, FloorplanPoint } from '@pascal-app/core'
import type {
CeilingNode,
FloorplanGeometry,
FloorplanPoint,
GeometryContext,
} from '@pascal-app/core'
/**
* Stage C floor-plan builder for ceiling. Renders the polygon outline
* as a dashed boundary (ceilings are above and would visually obscure
* the slab/walls if drawn solid). Same shape as slab but visually
* distinct.
* Stage C floor-plan builder for ceiling. Dashed boundary (ceilings sit
* above the slab); when selected, mounts the same boundary editor as
* slab — vertex + midpoint + edge handles on the outer ring AND every
* hole, with `holeIndex` carried in the handle payloads.
*/
export function buildCeilingFloorplan(node: CeilingNode): FloorplanGeometry | null {
export function buildCeilingFloorplan(
node: CeilingNode,
ctx: GeometryContext,
): FloorplanGeometry | null {
const polygon = node.polygon
if (!polygon || polygon.length < 3) return null
const view = ctx.viewState
const palette = view?.palette
const isSelected = view?.selected ?? false
const isHighlighted = view?.highlighted ?? false
const showSelectedChrome = isSelected || isHighlighted
const outer: FloorplanPoint[] = polygon.map(([x, z]) => [x, z] as FloorplanPoint)
const ring = (points: FloorplanPoint[]) => {
@@ -25,13 +39,71 @@ export function buildCeilingFloorplan(node: CeilingNode): FloorplanGeometry | nu
segments.push(ring(hole.map(([x, z]) => [x, z] as FloorplanPoint)))
}
return {
kind: 'path',
d: segments.join(' '),
fill: 'none',
stroke: '#94a3b8',
strokeWidth: 0.03,
strokeDasharray: '0.15 0.1',
opacity: 0.7,
const stroke = showSelectedChrome && palette ? palette.selectedStroke : '#94a3b8'
const children: FloorplanGeometry[] = [
{
kind: 'path',
d: segments.join(' '),
fill: 'none',
stroke,
strokeWidth: showSelectedChrome ? 0.04 : 0.03,
strokeDasharray: '0.15 0.1',
opacity: showSelectedChrome ? 0.95 : 0.7,
},
]
if (isSelected) {
appendRingEditor(children, polygon, undefined)
holes.forEach((hole, holeIndex) => {
if (hole.length >= 3) appendRingEditor(children, hole, holeIndex)
})
}
return { kind: 'group', children }
}
/**
* Same boundary editor as slab — see `nodes/src/slab/floorplan.ts` for
* the contract. The kinds differ only in their fill / stroke chrome;
* the editor primitives are identical.
*/
function appendRingEditor(
children: FloorplanGeometry[],
ring: ReadonlyArray<readonly [number, number]>,
holeIndex: number | undefined,
): void {
for (let i = 0; i < ring.length; i++) {
const a = ring[i]!
const b = ring[(i + 1) % ring.length]!
children.push({
kind: 'edge-handle',
x1: a[0],
y1: a[1],
x2: b[0],
y2: b[1],
affordance: 'move-edge',
payload: { holeIndex, edgeIndex: i },
})
}
for (let i = 0; i < ring.length; i++) {
const a = ring[i]!
const b = ring[(i + 1) % ring.length]!
children.push({
kind: 'midpoint-handle',
point: [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2],
affordance: 'add-vertex',
payload: { holeIndex, edgeIndex: i },
})
}
for (let i = 0; i < ring.length; i++) {
const [x, z] = ring[i]!
children.push({
kind: 'endpoint-handle',
point: [x, z],
state: 'idle',
affordance: 'move-vertex',
payload: { holeIndex, vertexIndex: i },
})
}
}
+137 -1
View File
@@ -11,8 +11,9 @@ import {
} from '@pascal-app/core'
import { CursorSphere, markToolCancelConsumed, triggerSFX, useEditor } from '@pascal-app/editor'
import { useViewer } from '@pascal-app/viewer'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type * as THREE from 'three'
import { BufferGeometry, DoubleSide, Path, Shape, ShapeGeometry, Vector3 } from 'three'
/**
* Phase 5 Stage D — ceiling whole-move tool.
@@ -57,6 +58,24 @@ function setMeshOffset(id: AnyNodeId, deltaX: number, deltaZ: number, height: nu
if (mesh) mesh.position.set(deltaX, height - 0.01, deltaZ)
}
/**
* Distinguish 3D-canvas grid events (this tool) from 2D floor-plan
* grid events (`ceilingFloorplanMoveTarget` + `FloorplanRegistryMoveOverlay`
* Path 1). See the equivalent helper in `slab/move-tool.tsx` for the
* full rationale.
*/
function isFloorplanSourcedEvent(event: GridEvent): boolean {
const native: unknown = event.nativeEvent
const candidate =
(native as { target?: unknown; nativeEvent?: { target?: unknown } } | null) ?? null
const target =
(candidate?.target as Element | null | undefined) ??
(candidate?.nativeEvent as { target?: Element | null } | undefined)?.target ??
null
if (!target || typeof (target as Element).closest !== 'function') return false
return (target as Element).closest('[data-floorplan-scene]') != null
}
export const MoveCeilingTool: React.FC<{ node: CeilingNode }> = ({ node }) => {
const activatedAtRef = useRef<number>(Date.now())
const originalPolygonRef = useRef(node.polygon.map(([x, z]) => [x, z] as [number, number]))
@@ -112,6 +131,7 @@ export const MoveCeilingTool: React.FC<{ node: CeilingNode }> = ({ node }) => {
}
const onGridMove = (event: GridEvent) => {
if (isFloorplanSourcedEvent(event)) return
const localX = snap(event.localPosition[0])
const localZ = snap(event.localPosition[2])
@@ -130,6 +150,7 @@ export const MoveCeilingTool: React.FC<{ node: CeilingNode }> = ({ node }) => {
}
const onGridClick = (event: GridEvent) => {
if (isFloorplanSourcedEvent(event)) return
if (Date.now() - activatedAtRef.current < 150) {
event.nativeEvent?.stopPropagation?.()
return
@@ -176,11 +197,126 @@ export const MoveCeilingTool: React.FC<{ node: CeilingNode }> = ({ node }) => {
}
}, [exitMoveMode, node.id])
return (
<CeilingMovePreview
ceilingId={node.id}
cursorLocalPos={cursorLocalPos}
height={node.height ?? 2.5}
originalHoles={originalHolesRef.current}
originalPolygon={originalPolygonRef.current}
/>
)
}
/**
* Translucent fill + bright outline showing where the ceiling will land
* during the drag. Mirrors the legacy `MoveCeilingTool` overlay so the
* 3D viewer has a visible cue from above (the ceiling's child grid mesh
* is hidden by default — without this preview the only mesh that shows
* from above is the (translated) translucent ceiling itself, which is
* easy to miss). Works for both the 3D `grid:move` path (this tool
* writes `useLiveTransforms.position = [Δx, 0, Δz]` directly) and the
* 2D floor-plan move path (`slab/ceiling/floorplan-move.ts` writes the
* same value); we subscribe to that store so the preview tracks the
* current delta regardless of which mover is driving it.
*/
function CeilingMovePreview({
ceilingId,
cursorLocalPos,
height,
originalHoles,
originalPolygon,
}: {
ceilingId: AnyNodeId
cursorLocalPos: [number, number, number]
height: number
originalHoles: Array<Array<[number, number]>>
originalPolygon: Array<[number, number]>
}) {
const live = useLiveTransforms((s) => s.get(ceilingId))
const dx = live?.position[0] ?? 0
const dz = live?.position[2] ?? 0
const previewPolygon = useMemo(
() => originalPolygon.map(([x, z]) => [x + dx, z + dz] as [number, number]),
[originalPolygon, dx, dz],
)
const previewHoles = useMemo(
() => originalHoles.map((hole) => hole.map(([x, z]) => [x + dx, z + dz] as [number, number])),
[originalHoles, dx, dz],
)
const previewFillGeometry = useMemo(
() => createCeilingPreviewGeometry(previewPolygon, previewHoles),
[previewPolygon, previewHoles],
)
const previewOutlineGeometry = useMemo(
() => createCeilingOutlineGeometry(previewPolygon),
[previewPolygon],
)
return (
<group>
<mesh geometry={previewFillGeometry} position={[0, height + 0.012, 0]}>
<meshBasicMaterial
color="#f5f5f4"
depthWrite={false}
opacity={0.3}
side={DoubleSide}
transparent
/>
</mesh>
{/* @ts-ignore - `<line>` is a valid R3F intrinsic but conflicts with SVG line typing */}
<line geometry={previewOutlineGeometry} position={[0, height + 0.02, 0]}>
<lineBasicMaterial color="#ffffff" depthWrite={false} opacity={0.95} transparent />
</line>
<CursorSphere position={cursorLocalPos} showTooltip={false} />
</group>
)
}
function createCeilingPreviewGeometry(
polygon: Array<[number, number]>,
holes: Array<Array<[number, number]>>,
): BufferGeometry {
if (polygon.length < 3) return new BufferGeometry()
const shape = new Shape()
const first = polygon[0]!
shape.moveTo(first[0], -first[1])
for (let i = 1; i < polygon.length; i++) {
const pt = polygon[i]!
shape.lineTo(pt[0], -pt[1])
}
shape.closePath()
for (const holePolygon of holes) {
if (holePolygon.length < 3) continue
const hole = new Path()
const hf = holePolygon[0]!
hole.moveTo(hf[0], -hf[1])
for (let i = 1; i < holePolygon.length; i++) {
const pt = holePolygon[i]!
hole.lineTo(pt[0], -pt[1])
}
hole.closePath()
shape.holes.push(hole)
}
const geometry = new ShapeGeometry(shape)
geometry.rotateX(-Math.PI / 2)
geometry.computeVertexNormals()
return geometry
}
function createCeilingOutlineGeometry(polygon: Array<[number, number]>): BufferGeometry {
const geometry = new BufferGeometry()
if (polygon.length < 2) return geometry
const points = polygon.map(([x, z]) => new Vector3(x, 0, z))
const first = polygon[0]!
points.push(new Vector3(first[0], 0, first[1]))
geometry.setFromPoints(points)
return geometry
}
export default MoveCeilingTool
+102 -11
View File
@@ -1,15 +1,106 @@
'use client'
import { CeilingRenderer } from '@pascal-app/viewer'
import {
type CeilingNode,
getMaterialPresetByRef,
resolveMaterial,
useRegistry,
} from '@pascal-app/core'
import { NodeRenderer, useNodeEvents } from '@pascal-app/viewer'
import { useEffect, useMemo, useRef } from 'react'
import { BufferGeometry, Float32BufferAttribute } from 'three'
import { float, mix, positionWorld, smoothstep } from 'three/tsl'
import { BackSide, FrontSide, type Mesh, MeshBasicNodeMaterial } from 'three/webgpu'
function createEmptyGeometry() {
const geometry = new BufferGeometry()
geometry.setAttribute('position', new Float32BufferAttribute([], 3))
return geometry
}
const gridScale = 5
const gridX = positionWorld.x.mul(gridScale).fract()
const gridY = positionWorld.z.mul(gridScale).fract()
const lineWidth = 0.05
const lineX = smoothstep(lineWidth, 0, gridX).add(smoothstep(1.0 - lineWidth, 1.0, gridX))
const lineY = smoothstep(lineWidth, 0, gridY).add(smoothstep(1.0 - lineWidth, 1.0, gridY))
const gridPattern = lineX.max(lineY)
const gridOpacity = mix(float(0.2), float(0.6), gridPattern)
function createCeilingMaterials(color = '#999999') {
const topMaterial = new MeshBasicNodeMaterial({
color,
transparent: true,
depthWrite: false,
side: FrontSide,
})
topMaterial.opacityNode = gridOpacity
const bottomMaterial = new MeshBasicNodeMaterial({
color,
transparent: true,
side: BackSide,
})
return { topMaterial, bottomMaterial }
}
const ceilingMaterialCache = new Map<string, ReturnType<typeof createCeilingMaterials>>()
function getCeilingMaterials(color = '#999999') {
const cacheKey = color
const cached = ceilingMaterialCache.get(cacheKey)
if (cached) return cached
const materials = createCeilingMaterials(color)
ceilingMaterialCache.set(cacheKey, materials)
return materials
}
export const CeilingRenderer = ({ node }: { node: CeilingNode }) => {
const ref = useRef<Mesh>(null!)
const placeholderGeometry = useMemo(createEmptyGeometry, [])
const gridPlaceholderGeometry = useMemo(createEmptyGeometry, [])
useRegistry(node.id, 'ceiling', ref)
const handlers = useNodeEvents(node, 'ceiling')
useEffect(
() => () => {
placeholderGeometry.dispose()
gridPlaceholderGeometry.dispose()
},
[gridPlaceholderGeometry, placeholderGeometry],
)
const materials = useMemo(() => {
const preset = getMaterialPresetByRef(node.materialPreset)
const props = preset?.mapProperties ?? resolveMaterial(node.material)
const color = props.color || '#999999'
return getCeilingMaterials(color)
}, [
node.materialPreset,
node.material,
node.material?.preset,
node.material?.properties,
node.material?.texture,
])
return (
<mesh geometry={placeholderGeometry} material={materials.bottomMaterial} ref={ref}>
<mesh
geometry={gridPlaceholderGeometry}
material={materials.topMaterial}
name="ceiling-grid"
{...handlers}
scale={0}
visible={false}
/>
{node.children.map((childId) => (
<NodeRenderer key={childId} nodeId={childId} />
))}
</mesh>
)
}
/**
* Wrap-export of the legacy `CeilingRenderer`.
*
* Ceiling's renderer uses TSL shader code for the grid-line pattern
* (~100 lines incl. material setup) — too much to duplicate at Stage A.
* The legacy file stays in viewer; the registry imports it through the
* public export. Phase 5 Stage B/F (per-kind migration stages, see
* plans/editor-node-registry.md) moves the renderer body into this
* folder and deletes the legacy file.
*/
export default CeilingRenderer
+3 -6
View File
@@ -3,13 +3,10 @@
import { CeilingSystem } from '@pascal-app/viewer'
/**
* Registry-driven ceiling system bundle. Re-exports the legacy
* `CeilingSystem` so it mounts via `RegisteredSystems` when ceiling is
* registry-driven. `<LegacySystem kind="ceiling">` in viewer/components/
* viewer/index.tsx short-circuits whenever `nodeRegistry.has('ceiling')`
* is true — same shape wall / fence / slab use.
* Registry-driven ceiling system bundle. Wraps `CeilingSystem` so it
* mounts via `RegisteredSystems`.
*
* Future Phase 5+: extract polygon triangulation + hole CSG into a pure
* Future: extract polygon triangulation + hole CSG into a pure
* `buildCeilingGeometry(node)` and migrate to `def.geometry`.
*/
const CeilingSystems = () => {