* 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 * Add modular cabinet node * Add modular cabinet run and tall cabinet workflows * Add cabinet paint slots and material groups * Improve modular cabinet presets and wall snapping * Improve cabinet wall snapping * Fix cabinet wall snapping and countertop joins * Improve cabinet appliance compartments * Improve fridge visuals and smooth cabinet animations Fridge exterior is now brushed silver with brass accents and the interior is all white. Door/drawer animation no longer rebuilds the full cabinet geometry per frame — animated parts carry pose metadata that a new per-frame cabinet system applies directly to transforms. Co-Authored-By: Claude <noreply@anthropic.com> * Improve gas hob flames and cooktop knob controls Port the curved-flame look from reference gas-burner photos: each burner gets a ring of vertex-coloured tube flames (blue body, orange-yellow tips) whose spines breathe and flicker per frame at ~30fps, plus a flat ignition glow and a faded heat halo. Fix the knob pointer notch to rotate with the knob instead of drifting sideways. Also includes cooktop compartment presets/panels and cabinet selection/move affordance work. Co-Authored-By: Claude <noreply@anthropic.com> * Fix cabinet UVs and registry actions * Fix registry move snap typecheck * Fix cabinet knob animation concurrency * Fix cabinet material disposal, undo flood, and 2D move parity - Flag shared cabinet appliance materials (and the viewer's cached material factories) as cached so geometry rebuilds no longer dispose materials still referenced by other nodes, forcing scene-wide shader recompiles. - Route the door/drawer open animation through useLiveNodeOverrides with a single final commit, so one play is one undo step instead of ~20. - Add a cabinet-module floorplanMoveTarget: 2D drags now convert through planToLocal + magneticSnap like the 3D path, instead of writing plan coords into the run-local position (teleporting modules on rotated runs). - Re-key sibling runs (cabinetAdjacencyRevision) when a run's neighbor-affecting inputs change, so countertop overhang joins re-trim when a neighbor moves/resizes/deletes. - Narrow the cabinet panel's scene subscriptions (useShallow module selector) so it stops re-rendering on every scene mutation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Restructure cabinet schema and centralize run math/mutations Prepares the cabinet node for the queued specialty units (corner L-shape, sink base, appliance gap, open shelving): - Add a `moduleKind` discriminator (default 'standard') on CabinetModuleNode so new unit types extend an enum instead of overloading the stack, and split CabinetCompartment into a z.discriminatedUnion so invalid field combos (drawer with rack style, fridge with burner state) are unrepresentable. Shared box fields now come from one `cabinetBoxFields` object so run/module schemas can't drift. - Extract the straight-line run assumption (sort-by-x, edges, adjacency, spans, side-insert, reflow, frame transforms) into run-layout.ts — previously spread across definition/geometry/quick-actions/stack/ move-frame, so corner support would have meant five parallel edits. - Consolidate the run mutations (add module, wall cabinet/hood above, base↔tall switch, layout-revision bump) into run-ops.ts on SceneApi. Panel and quick-actions had drifted copies: the panel's add-module skipped gap checks, revision-bump scope differed per surface. - Remove dead code: node-level doorStyle (with a migrateNodes entry — geometry only ever read per-compartment doorType), the unreachable slot-handle mesh block, the no-op handlePosition 'edge' enum value, wallLocalX, and duplicate totalCabinetHeight definitions. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add cabinet snap tests and split the cabinet panel - New tests: cabinetModuleParentFrame.magneticSnap (flush snap, threshold, Z alignment, nearest-edge) and wall-snap's resolveCabinetWallFaceOffset / collectCabinetWallSnapNeighbors (straight face, miter taper, ray-miss fallback, yaw/face/parent filtering) — 87 cabinet tests, up from 71. - De-brittle geometry test lookups: coordinate-encoded mesh names are now matched by pattern, so dimension-default changes don't break them. - Split panel.tsx (1,541 → 679 lines): CompartmentCard + option constants into compartment-card.tsx, CabinetRunPanel + reflow wiring into run-panel.tsx, and the compartment type-transition tables into a pure resolveCompartmentTransition in stack-transitions.ts. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Split cabinet geometry.ts into per-appliance modules Pure code motion: geometry.ts (4,728 lines) becomes a 336-line orchestrator dispatching into geometry/ — shared helpers + cached appliance materials (shared.ts), CSG fronts/handles/doors/drawers (fronts.ts), run spans + countertop (run.ts), and self-contained hood/fridge/cooktop/dishwasher/ oven-microwave/pantry builders. No mesh names, userData stamps, materials, or math changed; the './geometry' import path is unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add undermount sink compartment with CSG-cut countertops New 'sink' compartment type (single / double / 60-40 bowl layouts) following the cooktop pattern: zero stack height, countertop-plane geometry, panel card with a bowl-layout selector, and a Sink Base preset. Bowl openings are subtracted from both module- and run-owned countertop slabs via three-bvh-csg; the basin shells, drain plumbing, and a spec-sheet-proportioned gooseneck faucet (Grohe Minta-style pin lever) render beneath the cut. Sink modules skip the carcass top panel and the deck under the sink row so the basin hangs through. Also scope the viewer mock in roof-surface-placement-guides.test.ts to only stub useViewer — the bare module stub leaked into later suites and broke real CSG imports. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Update ifc-converter next-env reference to build-mode route types Regenerated by `next typegen` during check-types; points at .next/types instead of the dev-mode .next/dev/types path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Draw cabinet floor plans with kitchen drafting symbols Replace the per-module box soup with NKBA/architectural-convention symbols: the run draws one heavier countertop outline per span (extended by the overhang), base modules draw their front edge plus compartment symbols — rounded bowl rects + faucet dot for sinks, burner/zone rings for cooktops (reusing the 3D layout tables so 2D and 3D always agree) — and appliance modules carry standard upright labels (DW / REF / OV / MW / PAN). Nested wall cabinets and hood-only modules draw as dashed open outlines per the above-cut-plane convention. * Play cabinet open/close animation on the E interaction key Add an `e` slot to registry KeyboardActions and dispatch it in the keyboard hook ahead of the legacy door/window arms, so kinds opt into the E interaction on their NodeDefinition. Cabinets register it: E on a module eases its doors/drawers open or closed, E on a run swings every child module together, and hood-only modules fall through. The panel's rAF animator moves into cabinet/interaction.ts (live-override frames, single undo commit) so the Play button and E share one animation, and the shortcuts dialog now documents E. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add kitchen island and bar counter support to cabinet runs Islands: run-level countertopBackOverhang (seating side) and withFinishedBack (decorative back panel), plus an I-key island placement mode in the cabinet tool that skips wall snap. Bar counters: optional barLedge {edge, height, depth} drawing a knee wall and raised slab along the back or either run end, superseding the seating overhang on its edge. withWaterfall drops slab-material panels to the floor on exposed run ends. 2D floorplan outlines, selection bounds, geometry keys, and run panel controls updated in parity; schemaVersion 3 -> 6. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Merge quick-action arrow and plus into one directional add glyph The add-left/add-right buttons showed two unrelated icons; a single plus-on-tail arrow reads as "add on this side". Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Extend plugin discovery instead of replacing the host source Also track the ifc-converter next-env routes reference update. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add L-corner runs to modular cabinets with run-scoped grouping An "L Left/Right" quick action spawns a perpendicular base leg, wall leg, and wall bridge as metadata-linked runs parented to the SOURCE RUN, so the run stays the single group: selecting a base module selects only it, and the clicked module never becomes a container. Corner runs re-anchor when the source module resizes or moves (new MovableParentFrame.onCommit hook, mirrored in the 2D floorplan commit), run bounds fold in child leg runs, and deleting one corner member removes only that node while unlink patches keep the survivors' link metadata consistent. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Delete emptied cabinet run groups in the same delete gesture Removing a run's last child (module or derived corner leg) left an empty group node in the scene graph and persisted data. onDeleteCascade now receives the gesture's pending delete ids so multi-select deletes count siblings as gone, and both cabinet kinds cascade the orphaned parent run away in one undo step. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Remove filler front gap treatment * Apply architecture review fixes across cabinet, plugin-trees, and framework Move cabinet semantics out of packages/editor behind registry capabilities (def.tree, selectionProxy.bypassDirectPick, IconRef quick-action icons, catalog tool field), route cabinet selection through a core selection-proxy helper, and make PanelWorkspace an opaque host tag. Fix the cabinet placement undo flood, dirtyNodes.add bypasses, normalized UVs on paintable slots, plugin-trees ghost layers/stale level transforms/untyped find-sync event, and cross-file store-mock pollution plus orphaned dist tests that broke combined test runs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Propagate front styling to L-corner runs even when re-layout bails Group style changes rode entirely on syncDerivedCornerRun, which bails silently when a later-drawn wall blocks the corner layout or a leg run gained modules outside the derived-run spec — leaving the L legs styled stale. Apply the style patch directly to every linked corner run before attempting the geometric re-layout. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * Improve editor viewer integration * Refactor plugin panels and floorplan invalidation * UV-unwrap and material-assign roof-segment trim planes * Fix cabinet placement snap feedback * Add cabinet wall snap bypass * Fix cabinet continuous placement flow * Implement wall band material slots * Add corner addition preview functionality and related tests * Fix cabinet and wall band behavior * Fix architecture review blockers * Fix post-merge quality check * fix cursor review feedback * Fix cabinet placement type and quick action history * Improve cabinet placement feedback * Make wall bands configurable * Add wall trim profiles and default materials * Fix architecture review issues * Fix cabinet rotation and wall band visibility * Fix sink appliance paint persistence * Bake cabinet animations and preserve wall band material * Fix cabinet group duplication and module snapping * Fix cabinet duplication architecture * Fix cabinet floorplan test and make placement-type hint a live chip - floorplan.test.ts: pass the required liveTransforms map to cabinetFloorplanSiblingOverrides (the runtime callers always supply it) - ToolHint gains an optional generic `chip` contract (subscribe/value/ cycle/labels) so a kind can render a tool hint as a live mode chip — like the snapping/continuation chips — without the editor knowing the kind's store - cabinet: the I hint now shows the current value (Type: Cabinet / Type: Island) and is clickable to toggle Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Wassim SAMAD <wass08@gmail.com>
422 lines
16 KiB
TypeScript
422 lines
16 KiB
TypeScript
'use client'
|
|
|
|
import {
|
|
type AnyNode,
|
|
type AnyNodeId,
|
|
type GeometryContext,
|
|
getEffectiveNode,
|
|
nodeRegistry,
|
|
type SurfaceRole,
|
|
sceneRegistry,
|
|
useLiveNodeOverrides,
|
|
useScene,
|
|
} from '@pascal-app/core'
|
|
import { useFrame } from '@react-three/fiber'
|
|
import { useEffect, useRef } from 'react'
|
|
import { FrontSide, type Group, type Material, type Mesh, type Object3D } from 'three'
|
|
import {
|
|
type ColorPreset,
|
|
createSurfaceRoleMaterial,
|
|
type RenderShading,
|
|
} from '../../lib/materials'
|
|
import useViewer from '../../store/use-viewer'
|
|
|
|
/**
|
|
* Generic geometry system.
|
|
*
|
|
* For every node in `dirtyNodes` whose definition exposes `def.geometry`,
|
|
* this system:
|
|
* 1. Looks up the registered `Group` from `sceneRegistry` (mounted by the
|
|
* framework's `<ParametricNodeRenderer>`, or a custom renderer that
|
|
* opts into the same mount contract).
|
|
* 2. Builds a `GeometryContext` from the current scene snapshot.
|
|
* 3. Calls `def.geometry(node, ctx)` to get the new `Object3D`.
|
|
* 4. Disposes the registered group's existing children + their geometries
|
|
* and materials.
|
|
* 5. Reparents the returned object's children onto the registered group.
|
|
* 6. Clears the dirty flag.
|
|
*
|
|
* This is the "no per-kind system needed" path documented in
|
|
* `wiki/architecture/node-definitions.md`. A kind that only rebuilds on
|
|
* dirty (shelf, item, fence segment, etc.) ships nothing more than a pure
|
|
* `geometry` function — no `renderer.tsx`, no `system.tsx`.
|
|
*
|
|
* Kinds with `def.system` declared run their own systems *in addition* to
|
|
* this one — animation + cascade + named-mesh material poking stay
|
|
* kind-specific.
|
|
*
|
|
* Frame priority 2 mirrors the per-kind shelf system it replaces. Door
|
|
* animation systems run at priority 2 today too, marking dirty so the
|
|
* geometry rebuild lands at priority 3-4 next frame. Door/window/wall
|
|
* still have their own systems (they need cross-cutting work this system
|
|
* doesn't cover) — they coexist; this system only acts on kinds that
|
|
* declare `def.geometry`.
|
|
*/
|
|
export const GeometrySystem = () => {
|
|
const dirtyNodes = useScene((s) => s.dirtyNodes)
|
|
const clearDirty = useScene((s) => s.clearDirty)
|
|
const shading = useViewer((s) => s.shading)
|
|
const textures = useViewer((s) => s.textures)
|
|
const colorPreset = useViewer((s) => s.colorPreset)
|
|
const sceneTheme = useViewer((s) => s.sceneTheme)
|
|
const bumpGeometryRevision = useViewer((s) => s.bumpGeometryRevision)
|
|
// The shared scene-material library, threaded into each builder's ctx so
|
|
// pure geometry builders can resolve `scene:<id>` slot refs without
|
|
// importing `useScene`.
|
|
const sceneMaterials = useScene((s) => s.materials)
|
|
// Per-node cache of the last-built geometry key (for kinds that declare
|
|
// `def.geometryKey`). Lets us skip a dispose+rebuild when a node is dirty
|
|
// but its geometry inputs are unchanged — e.g. an item reparenting onto a
|
|
// shelf dirties the shelf without altering its boards.
|
|
const builtGeometryKeyRef = useRef<Map<string, GeometryBuildCacheEntry>>(new Map())
|
|
|
|
// Re-mark every geometry-backed node dirty whenever a viewer appearance
|
|
// value changes, so `def.geometry` builders re-run and pick up the new
|
|
// shading / texture / preset / theme. These four are deliberate re-run
|
|
// TRIGGERS, not values read in the body — the effect re-fires on any
|
|
// change. They're primitives (stable by value), so listing them is safe;
|
|
// biome flags them as "unnecessary" because the body doesn't reference
|
|
// them, but dropping them silently breaks appearance-mode switching.
|
|
// biome-ignore lint/correctness/useExhaustiveDependencies: shading/textures/colorPreset/sceneTheme are intentional re-run triggers; removing them stops geometry from rebuilding on appearance change.
|
|
useEffect(() => {
|
|
const nodes = useScene.getState().nodes
|
|
for (const node of Object.values(nodes)) {
|
|
const def = nodeRegistry.get(node.type)
|
|
if (def?.geometry) {
|
|
useScene.getState().markDirty(node.id as AnyNodeId)
|
|
}
|
|
}
|
|
}, [shading, textures, colorPreset, sceneTheme])
|
|
|
|
// Editing a scene material must re-colour every geometry node that
|
|
// references it through a `scene:<id>` slot ref. Such a node's
|
|
// `geometryKey` is unchanged (only the referenced material's contents
|
|
// moved), so clear its cached key to defeat the skip in the rebuild loop,
|
|
// then mark it dirty. Scoped to nodes carrying a `scene:` ref so an
|
|
// unrelated material edit doesn't churn the whole scene.
|
|
useEffect(() => {
|
|
void sceneMaterials
|
|
const nodes = useScene.getState().nodes
|
|
for (const node of Object.values(nodes)) {
|
|
const def = nodeRegistry.get(node.type)
|
|
if (!def?.geometry) continue
|
|
if (!nodeReferencesSceneMaterial(node)) continue
|
|
builtGeometryKeyRef.current.delete(node.id)
|
|
useScene.getState().markDirty(node.id as AnyNodeId)
|
|
}
|
|
}, [sceneMaterials])
|
|
|
|
useFrame(() => {
|
|
if (dirtyNodes.size === 0) return
|
|
const nodes = useScene.getState().nodes
|
|
let rebuiltGeometry = false
|
|
|
|
// Phase 1 — group dirty nodes by (kind, parentId). Kinds that
|
|
// declare `def.computeLevelData` get one batch precompute per
|
|
// group; the result lands in `ctx.levelData` for every node in
|
|
// the same batch. Avoids O(N²) recomputation when many siblings
|
|
// of the same kind are dirty in one frame (wall mitering is the
|
|
// motivating case).
|
|
type BatchKey = string // `${kind}::${parentId ?? ''}`
|
|
const batches = new Map<
|
|
BatchKey,
|
|
{ kind: string; parentId: AnyNodeId | null; ids: AnyNodeId[] }
|
|
>()
|
|
const dirtyIds: AnyNodeId[] = []
|
|
dirtyNodes.forEach((id) => {
|
|
const node = nodes[id]
|
|
if (!node) return
|
|
const def = nodeRegistry.get(node.type)
|
|
if (!def?.geometry) return
|
|
dirtyIds.push(id as AnyNodeId)
|
|
const parentId = (node.parentId ?? null) as AnyNodeId | null
|
|
const key: BatchKey = `${node.type}::${parentId ?? ''}`
|
|
const existing = batches.get(key)
|
|
if (existing) existing.ids.push(id as AnyNodeId)
|
|
else batches.set(key, { kind: node.type, parentId, ids: [id as AnyNodeId] })
|
|
})
|
|
|
|
// Phase 2 — for each batch whose kind declares `computeLevelData`,
|
|
// collect every sibling in the level + run the precompute once.
|
|
const levelDataByBatch = new Map<BatchKey, unknown>()
|
|
for (const [key, batch] of batches) {
|
|
const def = nodeRegistry.get(batch.kind)
|
|
if (!def?.computeLevelData) continue
|
|
const siblings: AnyNode[] = []
|
|
if (batch.parentId) {
|
|
const parent = nodes[batch.parentId]
|
|
const childIds = (parent as unknown as { children?: AnyNodeId[] })?.children
|
|
if (Array.isArray(childIds)) {
|
|
for (const cid of childIds) {
|
|
const child = nodes[cid]
|
|
if (child?.type === batch.kind) siblings.push(child)
|
|
}
|
|
}
|
|
} else {
|
|
for (const node of Object.values(nodes)) {
|
|
if (node?.type === batch.kind && !node.parentId) siblings.push(node)
|
|
}
|
|
}
|
|
levelDataByBatch.set(
|
|
key,
|
|
(def.computeLevelData as (s: ReadonlyArray<AnyNode>) => unknown)(siblings),
|
|
)
|
|
}
|
|
|
|
// Phase 3 — per-node rebuild. Each node receives its batch's
|
|
// precomputed `levelData` in ctx.
|
|
for (const id of dirtyIds) {
|
|
const node = nodes[id]
|
|
if (!node) continue
|
|
|
|
const def = nodeRegistry.get(node.type)
|
|
const builder = def?.geometry
|
|
if (!builder) continue
|
|
|
|
const group = sceneRegistry.nodes.get(id) as Group | undefined
|
|
if (!group) continue // mount hasn't run — keep dirty for next frame
|
|
|
|
// Merge any live drag override into the node so resize arrows /
|
|
// 2D affordances see their in-flight patch on every pointer move
|
|
// — zustand only learns about the final value on commit. Mirrors
|
|
// the WallSystem / DoorSystem / WindowSystem hook-up; any kind
|
|
// that drives its mesh through `def.geometry` (fence, shelf, item)
|
|
// now smooths drags through this single line.
|
|
const effectiveNode = getEffectiveNode(node)
|
|
|
|
// Skip the rebuild when the geometry inputs are unchanged (kinds that
|
|
// opt in via `def.geometryKey`). Fold in the global rendering inputs so
|
|
// a theme / shading change — which re-dirties every geometry node — is
|
|
// never skipped. This kills the board remount + pointer enter/leave
|
|
// churn when an item reparents onto a shelf.
|
|
if (def.geometryKey) {
|
|
const childLiveOverrideKey = liveChildOverrideKey(node)
|
|
const builtKey = `${shading}|${textures}|${colorPreset}|${sceneTheme}|${def.geometryKey(effectiveNode)}|${childLiveOverrideKey}`
|
|
if (shouldReuseGeometryBuild(builtGeometryKeyRef.current, id, group, builtKey)) {
|
|
clearDirty(id as AnyNodeId)
|
|
continue
|
|
}
|
|
}
|
|
|
|
const parentId = (node.parentId ?? null) as AnyNodeId | null
|
|
const key: BatchKey = `${node.type}::${parentId ?? ''}`
|
|
const levelData = levelDataByBatch.get(key)
|
|
const ctx = buildGeometryContext(effectiveNode, nodes, levelData, sceneMaterials)
|
|
|
|
// The builder is typed against the kind's specific node — at the
|
|
// generic system level we lose that refinement, so the cast lands
|
|
// here. Builders are responsible for trusting their schema.
|
|
const built = (
|
|
builder as (
|
|
n: AnyNode,
|
|
c: GeometryContext,
|
|
shading: RenderShading,
|
|
textures: boolean,
|
|
colorPreset: ColorPreset,
|
|
sceneTheme: string,
|
|
) => { children: unknown[] }
|
|
)(effectiveNode, ctx, shading, textures, colorPreset, sceneTheme) as unknown as Group
|
|
|
|
if (!textures && def.surfaceRole) {
|
|
applyDefaultSurfaceRole(built, def.surfaceRole, colorPreset, sceneTheme)
|
|
}
|
|
|
|
disposeChildren(group)
|
|
for (const child of [...built.children]) {
|
|
markGeometryBuildOutput(child)
|
|
group.add(child)
|
|
}
|
|
rebuiltGeometry = true
|
|
// NOTE: we intentionally do NOT reset `group.position` / `group.rotation`
|
|
// here. The `ParametricNodeRenderer` binds them via JSX (`position={...}`
|
|
// / `rotation={...}`) driven by `useLiveTransforms` during drag and
|
|
// `node.position` / `node.rotation` after commit. Zeroing them out
|
|
// during a rebuild would clobber the React-applied transform — and
|
|
// because the renderer doesn't necessarily re-render on the rebuild
|
|
// tick, R3F wouldn't re-apply the props, leaving the group stuck at
|
|
// origin. Geometry builders are expected to emit local-space children.
|
|
|
|
clearDirty(id as AnyNodeId)
|
|
}
|
|
if (rebuiltGeometry) bumpGeometryRevision()
|
|
}, 2)
|
|
|
|
return null
|
|
}
|
|
|
|
function liveChildOverrideKey(node: AnyNode): string {
|
|
const childIds = (node as unknown as { children?: AnyNodeId[] }).children
|
|
if (!Array.isArray(childIds) || childIds.length === 0) return ''
|
|
|
|
const overrides = useLiveNodeOverrides.getState().overrides
|
|
const entries: Array<[AnyNodeId, unknown]> = []
|
|
for (const childId of childIds) {
|
|
const override = overrides.get(childId)
|
|
if (override) entries.push([childId, override])
|
|
}
|
|
return entries.length === 0 ? '' : JSON.stringify(entries)
|
|
}
|
|
|
|
function nodeReferencesSceneMaterial(node: AnyNode): boolean {
|
|
const slots = (node as { slots?: Record<string, string> }).slots
|
|
if (!slots) return false
|
|
for (const ref of Object.values(slots)) {
|
|
if (typeof ref === 'string' && ref.startsWith('scene:')) return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
function buildGeometryContext(
|
|
node: AnyNode,
|
|
nodes: Record<string, AnyNode>,
|
|
levelData: unknown,
|
|
materials: GeometryContext['materials'],
|
|
): GeometryContext {
|
|
const resolve = <N = AnyNode>(id: AnyNodeId): N | undefined => {
|
|
const resolved = nodes[id]
|
|
return resolved ? (getEffectiveNode(resolved) as N) : undefined
|
|
}
|
|
|
|
const childIds = (node as unknown as { children?: AnyNodeId[] }).children
|
|
const children: AnyNode[] = Array.isArray(childIds)
|
|
? childIds.map((cid) => resolve<AnyNode>(cid)).filter((n): n is AnyNode => n !== undefined)
|
|
: []
|
|
|
|
const parentId = node.parentId as AnyNodeId | null
|
|
const parent: AnyNode | null = parentId ? (resolve<AnyNode>(parentId) ?? null) : null
|
|
|
|
// Siblings = same kind, same parent, excluding self. Walks the parent's
|
|
// children array; falls back to scanning the whole scene if the parent
|
|
// doesn't carry a `children` list (rare — most parents do).
|
|
let siblings: AnyNode[] = []
|
|
if (parent) {
|
|
const parentChildIds = (parent as unknown as { children?: AnyNodeId[] }).children
|
|
if (Array.isArray(parentChildIds)) {
|
|
for (const sid of parentChildIds) {
|
|
if (sid === node.id) continue
|
|
const s = resolve<AnyNode>(sid)
|
|
if (s && s.type === node.type) siblings.push(s)
|
|
}
|
|
} else {
|
|
siblings = Object.values(nodes)
|
|
.filter((n) => n !== node && n.type === node.type && n.parentId === parentId)
|
|
.map((n) => getEffectiveNode(n))
|
|
}
|
|
}
|
|
|
|
return { resolve, children, siblings, parent, levelData, materials }
|
|
}
|
|
|
|
function disposeChildren(group: Group) {
|
|
// Only dispose meshes the geometry builder produced on the previous
|
|
// rebuild (marked via `userData.__fromGeometry`). React-managed
|
|
// children (hosted node renderers) get left in place — they have
|
|
// their own React-driven lifecycle and would lose their meshes /
|
|
// materials if we disposed them here.
|
|
for (const child of [...group.children]) {
|
|
const fromGeometry = (child as { userData?: { __fromGeometry?: boolean } }).userData
|
|
?.__fromGeometry
|
|
if (!fromGeometry) continue
|
|
group.remove(child)
|
|
const mesh = child as Partial<Mesh> & { geometry?: { dispose?: () => void } }
|
|
if (mesh.geometry?.dispose) mesh.geometry.dispose()
|
|
if ('material' in mesh) {
|
|
const m = (mesh as { material: unknown }).material
|
|
if (Array.isArray(m)) {
|
|
for (const mat of m) {
|
|
if (isCachedMaterial(mat)) continue
|
|
if (mat && typeof (mat as { dispose?: () => void }).dispose === 'function') {
|
|
;(mat as { dispose: () => void }).dispose()
|
|
}
|
|
}
|
|
} else if (isCachedMaterial(m)) {
|
|
} else if (m && typeof (m as { dispose?: () => void }).dispose === 'function') {
|
|
;(m as { dispose: () => void }).dispose()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function applyDefaultSurfaceRole(
|
|
root: Group,
|
|
defaultRole: SurfaceRole,
|
|
colorPreset: ColorPreset,
|
|
sceneTheme?: string,
|
|
) {
|
|
root.traverse((child) => {
|
|
const mesh = child as Partial<Mesh> & {
|
|
material?: Material | Material[]
|
|
userData: Record<string, unknown>
|
|
}
|
|
if (!('material' in mesh) || !mesh.material) return
|
|
|
|
const role = getMeshSurfaceRole(mesh.userData.surfaceRole, defaultRole)
|
|
mesh.userData.surfaceRole = role
|
|
mesh.material = createSurfaceRoleMaterial(
|
|
role,
|
|
colorPreset,
|
|
getMaterialSide(mesh.material),
|
|
sceneTheme,
|
|
)
|
|
})
|
|
}
|
|
|
|
function getMeshSurfaceRole(value: unknown, fallback: SurfaceRole): SurfaceRole {
|
|
return typeof value === 'string' && isSurfaceRole(value) ? value : fallback
|
|
}
|
|
|
|
function isSurfaceRole(value: string): value is SurfaceRole {
|
|
return (
|
|
value === 'wall' ||
|
|
value === 'floor' ||
|
|
value === 'ceiling' ||
|
|
value === 'roof' ||
|
|
value === 'joinery' ||
|
|
value === 'glazing' ||
|
|
value === 'furnishing'
|
|
)
|
|
}
|
|
|
|
function getMaterialSide(material: Material | Material[]): Material['side'] {
|
|
const source = Array.isArray(material) ? material[0] : material
|
|
return source?.side ?? FrontSide
|
|
}
|
|
|
|
function isCachedMaterial(value: unknown): boolean {
|
|
return Boolean(
|
|
(value as { userData?: { __pascalCachedMaterial?: boolean } } | null)?.userData
|
|
?.__pascalCachedMaterial,
|
|
)
|
|
}
|
|
|
|
export default GeometrySystem
|
|
|
|
export type GeometryBuildCacheEntry = {
|
|
group: Group
|
|
key: string
|
|
}
|
|
|
|
export function markGeometryBuildOutput(child: Object3D): void {
|
|
// Tag the builder subtree so paint previews can reach nested meshes (for
|
|
// example a cabinet sink faucet handle), while disposal still removes only
|
|
// top-level builder children from the registered group.
|
|
child.traverse((object) => {
|
|
object.userData = {
|
|
...object.userData,
|
|
__fromGeometry: true,
|
|
}
|
|
})
|
|
}
|
|
|
|
export function shouldReuseGeometryBuild(
|
|
cache: Map<string, GeometryBuildCacheEntry>,
|
|
id: string,
|
|
group: Group,
|
|
key: string,
|
|
): boolean {
|
|
const cached = cache.get(id)
|
|
if (cached?.group === group && cached.key === key) return true
|
|
cache.set(id, { group, key })
|
|
return false
|
|
}
|