diff --git a/apps/editor/components/build-tab.tsx b/apps/editor/components/build-tab.tsx index 545d19b5d7..efd3092f49 100644 --- a/apps/editor/components/build-tab.tsx +++ b/apps/editor/components/build-tab.tsx @@ -36,7 +36,6 @@ import { import { activateBuildTool, activateFenceFeaturePlacement, - activateModularCabinetTool, activateRoofFeatureTool, activateRoofType, activateTerrainSculptMode, @@ -47,10 +46,10 @@ import { MEP_ITEMS, MEP_TOOL_KINDS, type MepItem, - MODULAR_CABINET_ICON, } from '@/lib/build-palette' import { getActiveRoofFeatureId, ROOF_TYPE_OPTIONS } from '@/lib/build-tab-state' import { cn } from '@/lib/utils' +import { KitchenBrowser } from './kitchen-browser' const subscribeToClientMount = () => () => {} @@ -61,6 +60,8 @@ const subscribeToClientMount = () => () => {} */ export function BuildTab() { const [mepOpen, setMepOpen] = useState(false) + const [kitchenOpen, setKitchenOpen] = useState(false) + const [buildSearch, setBuildSearch] = useState('') const activeTool = useEditor((s) => s.tool) const selectedId = useViewer((s) => s.selection.selectedIds[0]) const selectedFenceFeature = useScene((s) => { @@ -118,7 +119,7 @@ export function BuildTab() { const isMepActive = (mode === 'build' && !!activeTool && MEP_TOOL_KINDS.has(activeTool)) || (mode === 'select' && mepOpen) - const isKitchenActive = mode === 'build' && activeTool === 'cabinet' + const isKitchenActive = kitchenOpen || (mode === 'build' && activeTool === 'cabinet') const parsedRoofType = RoofTypeSchema.safeParse(roofDefaults?.roofType) const activeRoofType = parsedRoofType.success ? parsedRoofType.data : 'gable' @@ -136,6 +137,8 @@ export function BuildTab() { const handleTypeClick = useCallback( (type: BuildType) => { setMepOpen(type.id === 'mep') + setKitchenOpen(type.id === 'kitchen') + setBuildSearch('') if (type.id === 'fence' && selectedFence) return if (type.mode === 'terrain-sculpt') { activateTerrainSculptMode() @@ -146,7 +149,7 @@ export function BuildTab() { ed.setMode('build') ed.setTool(null) } else if (type.id === 'kitchen') { - activateModularCabinetTool() + useEditor.getState().setMode('select') } else if (type.id === 'terrace') { startTerraceDraft() } else if (type.kind) { @@ -193,393 +196,404 @@ export function BuildTab() { return (
-
- triggerSFX('sfx:menu-hover')} - onSelect={(variant) => { - triggerSFX('sfx:menu-click') - selectWallDrawVariant(variant) - const editor = useEditor.getState() - if (!(editor.mode === 'build' && editor.tool === 'wall')) activateBuildTool('wall') - }} - /> - - {typesIn('add').map(renderTile)} - - - {typesIn('outdoor').map(renderTile)} - - - {advancedTypes.map(renderTile)} - -
+ + setBuildSearch(event.target.value)} + className="h-9 w-full shrink-0 rounded-lg border border-border bg-background px-3 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" + /> + {buildSearch.trim() ? ( + <> + + {buildTypes + .filter((type) => type.label.toLowerCase().includes(buildSearch.toLowerCase())) + .map(renderTile)} + + + + ) : ( + <> + {isKitchenActive ? ( + + ) : ( +
+ triggerSFX('sfx:menu-hover')} + onSelect={(variant) => { + triggerSFX('sfx:menu-click') + selectWallDrawVariant(variant) + const editor = useEditor.getState() + if (!(editor.mode === 'build' && editor.tool === 'wall')) + activateBuildTool('wall') + }} + /> + + {typesIn('add').map(renderTile)} + + + {typesIn('outdoor').map(renderTile)} + + + {advancedTypes.map(renderTile)} + +
+ )} - {mode === 'terrain-sculpt' ? ( -
- -
- ) : mode === 'build' && (activeTool === 'roof' || isRoofFeatureActive) ? ( -
-
-
Roof type
-
- {ROOF_TYPE_OPTIONS.map((roofType) => { - const active = activeTool === 'roof' && activeRoofType === roofType.value - return ( -
+ ) : mode === 'build' && (activeTool === 'roof' || isRoofFeatureActive) ? ( +
+
+
+ Roof type +
+
+ {ROOF_TYPE_OPTIONS.map((roofType) => { + const active = activeTool === 'roof' && activeRoofType === roofType.value + return ( + + ) + })} +
+
+ + { + const editor = useEditor.getState() + if (!(editor.mode === 'build' && editor.tool === 'roof')) + activateBuildTool('roof') + }} + /> + {activeRoofType === 'conical' && ( +

+ Select a curved wall to match its radius and arc. +

+ )} + + {roofFeatures.length > 0 ? ( +
+
+ Features & extensions +
+ +
+ {roofFeatures.map((feature) => { + const active = mode === 'build' && feature.id === activeRoofFeatureId + return ( + + + + + + {feature.label} + + + ) + })} +
+
+
+ ) : null} +
+ ) : fenceContext ? ( +
+
Fence features
+ + {(['gate', 'opening'] as const).map((kind) => ( + { triggerSFX('sfx:menu-click') - activateRoofType(roofType.value) + activateFenceFeaturePlacement(kind) }} onMouseEnter={() => triggerSFX('sfx:menu-hover')} - type="button" - > - {roofType.label} - - ) - })} + title={kind === 'gate' ? 'Add Gate' : 'Add Open Passage'} + /> + ))} + + {selectedFenceFeature && ( + + )} + {!!placingFenceFeature && ( +
+

+ Hover a fence to preview. Click to place. Esc cancels. Leave room between + openings. +

+ {typeof fenceDefaults?.featurePlacementFeedback === 'string' && ( +

+ {fenceDefaults.featurePlacementFeedback} +

+ )} + + {fenceDefaults?.featureMatchStyle === false && placingFenceFeature === 'gate' && ( + + )} + + {placingFenceFeature === 'gate' && ( + + )} +
+ )} +

+ Choose Gate or Open Passage, then click its position on any fence. Find placed gates + and openings under their fence in the scene graph. +

-
- - { - const editor = useEditor.getState() - if (!(editor.mode === 'build' && editor.tool === 'roof')) activateBuildTool('roof') - }} - /> - {activeRoofType === 'conical' && ( -

- Select a curved wall to match its radius and arc. -

- )} - - {roofFeatures.length > 0 ? ( -
-
- Features & extensions -
+ ) : isKitchenActive ? ( + + ) : isMepActive ? ( +
+
MEP
- {roofFeatures.map((feature) => { - const active = mode === 'build' && feature.id === activeRoofFeatureId + {MEP_ITEMS.map((item) => { + const active = isMepItemActive(item) return ( - + - {feature.label} + {item.label} ) })}
-
- ) : null} -
- ) : fenceContext ? ( -
-
Fence features
- - {(['gate', 'opening'] as const).map((kind) => ( - { - triggerSFX('sfx:menu-click') - activateFenceFeaturePlacement(kind) - }} - onMouseEnter={() => triggerSFX('sfx:menu-hover')} - title={kind === 'gate' ? 'Add Gate' : 'Add Open Passage'} - /> - ))} - - {selectedFenceFeature && ( - - )} - {!!placingFenceFeature && ( -
-

- Hover a fence to preview. Click to place. Esc cancels. Leave room between openings. -

- {typeof fenceDefaults?.featurePlacementFeedback === 'string' && ( -

- {fenceDefaults.featurePlacementFeedback} -

- )} - - {fenceDefaults?.featureMatchStyle === false && placingFenceFeature === 'gate' && ( - - )} - - {placingFenceFeature === 'gate' && ( - - )} -
- )} -

- Choose Gate or Open Passage, then click its position on any fence. Find placed gates and - openings under their fence in the scene graph. -

-
- ) : isKitchenActive ? ( -
-
Kitchen
- -
- - + + {(['duct-fitting', 'pipe-fitting'] as const) + .filter((kind) => (kind === 'duct-fitting' ? ductContext : pipeContext)) + .map((kind) => ( + { + if (option.id !== 'fittingType') return undefined + if (kind === 'duct-fitting' && value === 'elbow') + return '/icons/duct-fitting.webp' + return `/icons/fittings/${kind === 'duct-fitting' ? 'duct' : 'pipe'}-${value}.webp` + }} + kind={kind} + onSelect={(option, value) => { + if (activeTool !== kind) { + const defaults = useEditor.getState().toolDefaults[kind] + activateBuildTool(kind) + if (defaults) useEditor.getState().setToolDefaults(kind, defaults) + } + option.set(value) + }} + /> + ))} + + {liquidLineContext ? ( +
+ Liquid Line - - - Modular Cabinet - - -
- -
- ) : isMepActive ? ( -
-
MEP
- -
- {MEP_ITEMS.map((item) => { - const active = isMepItemActive(item) - return ( - - - - - - {item.label} - - - ) - })} -
-
- - {(['duct-fitting', 'pipe-fitting'] as const) - .filter((kind) => (kind === 'duct-fitting' ? ductContext : pipeContext)) - .map((kind) => ( - { - if (option.id !== 'fittingType') return undefined - if (kind === 'duct-fitting' && value === 'elbow') - return '/icons/duct-fitting.webp' - return `/icons/fittings/${kind === 'duct-fitting' ? 'duct' : 'pipe'}-${value}.webp` - }} - kind={kind} - onSelect={(option, value) => { - if (activeTool !== kind) { - const defaults = useEditor.getState().toolDefaults[kind] - activateBuildTool(kind) - if (defaults) useEditor.getState().setToolDefaults(kind, defaults) - } - option.set(value) - }} - /> - ))} - - {liquidLineContext ? ( -
- Liquid Line - - - {follow - ? 'Click a lineset to lay the line beside it.' - : 'Trace a line alongside an existing lineset (F).'} - + + {follow + ? 'Click a lineset to lay the line beside it.' + : 'Trace a line alongside an existing lineset (F).'} + +
+ ) : null}
) : null} -
- ) : null} + + )}
) } diff --git a/apps/editor/components/kitchen-browser.tsx b/apps/editor/components/kitchen-browser.tsx new file mode 100644 index 0000000000..d8175f72e1 --- /dev/null +++ b/apps/editor/components/kitchen-browser.tsx @@ -0,0 +1,133 @@ +'use client' + +import { + type AnyNodeId, + type CabinetNode, + emitter, + resolveLevelId, + useScene, +} from '@pascal-app/core' +import { useCommandPalette, useCommandRegistry, useEditor } from '@pascal-app/editor' +import { + beginKitchenPlacement, + findKitchenItems, + KITCHEN_ITEMS, + KitchenCollection, + kitchenPresetForModule, +} from '@pascal-app/nodes' +import { useViewer } from '@pascal-app/viewer' +import { useEffect } from 'react' +import { useShallow } from 'zustand/react/shallow' + +const NO_ITEMS: never[] = [] + +function focusKitchenItem(id: AnyNodeId) { + const nodes = useScene.getState().nodes + const node = nodes[id] + if (!node) return + const levelId = resolveLevelId(node, nodes) + const level = levelId ? nodes[levelId as AnyNodeId] : undefined + const building = level?.parentId ? nodes[level.parentId as AnyNodeId] : undefined + useEditor.getState().setMode('select') + useViewer.getState().setSelection({ + selectedIds: [id], + ...(level?.type === 'level' ? { levelId: level.id } : {}), + ...(building?.type === 'building' ? { buildingId: building.id } : {}), + }) + emitter.emit('camera-controls:focus', { nodeId: id }) + emitter.emit('selection:find-node', node) +} + +export function KitchenBrowser({ query = '' }: { query?: string }) { + const defaults = useEditor((state) => state.toolDefaults.cabinet) + const mode = useEditor((state) => state.mode) + // Read the scene only while a query asks for placed items. + const matches = useScene( + useShallow((state) => (query.trim() ? findKitchenItems(state.nodes, query) : NO_ITEMS)), + ) + const active = KITCHEN_ITEMS.find((item) => item.id === defaults?.kitchenPreset) + return ( +
+
+

Add to kitchen

+

+ Choose an item, then click to place it. Appliances include their cabinetry. +

+
+ + {query.trim() && ( +
+

Find in this project · {matches.length}

+ {matches.map((node) => ( + + ))} + {!matches.length && ( +

No matching kitchen items placed yet.

+ )} +
+ )} +
+ ) +} + +export function KitchenCommands() { + const register = useCommandRegistry((state) => state.register) + // Always mounted: the placed items are read only while the palette is open to list them. + const paletteOpen = useCommandPalette((state) => state.open) + const modules = useScene( + useShallow((state) => (paletteOpen ? findKitchenItems(state.nodes, '') : NO_ITEMS)), + ) + useEffect( + () => + register( + KITCHEN_ITEMS.map((item) => ({ + id: `kitchen.add.${item.id}`, + label: `Add ${item.label}`, + group: 'Kitchen · Add', + keywords: item.keywords.split(' '), + execute: () => beginKitchenPlacement(item.id), + })), + ), + [register], + ) + useEffect( + () => + register( + modules.map((node) => { + const nodes = useScene.getState().nodes + const parent = node.parentId ? nodes[node.parentId as AnyNodeId] : undefined + const preset = + node.type === 'cabinet-module' + ? kitchenPresetForModule( + node, + parent?.type === 'cabinet' ? (parent as CabinetNode) : undefined, + ) + : 'base-door' + const item = KITCHEN_ITEMS.find((entry) => entry.id === preset)! + return { + id: `kitchen.find.${node.id}`, + label: `Find ${node.name || item.label}`, + group: 'Kitchen · In this project', + keywords: item.keywords.split(' '), + execute: () => focusKitchenItem(node.id), + } + }), + ), + [register, modules], + ) + return null +} diff --git a/apps/editor/components/scene-loader.tsx b/apps/editor/components/scene-loader.tsx index 251c1bb030..9a1263f3ef 100644 --- a/apps/editor/components/scene-loader.tsx +++ b/apps/editor/components/scene-loader.tsx @@ -21,6 +21,7 @@ import { type PersistedSceneGraph, sceneGraphSignature } from '@/lib/scene-signa import { useThumbnailAutosave } from '@/lib/use-thumbnail-autosave' import { BuildTab } from './build-tab' import { EditorNavbar } from './editor-navbar' +import { KitchenCommands } from './kitchen-browser' import { PaintPanel } from './paint-panel' import { EditorViewerToolbarLeft, EditorViewerToolbarRight } from './viewer-toolbar' import { useWebXRFeature, useWebXRInstalled, WebXRFeatureRuntime } from './webxr-feature-gate' @@ -368,6 +369,7 @@ function SceneEditor({ initialScene, meta: initialMeta }: SceneLoaderProps) {

{saveError}

)} + , 'children' | iconSrc: string label: string size?: 'lg' | 'sm' + tone?: 'primary' | 'neutral' } /** * One tool tile: the isometric icon over its name. Inactive icons stay grey and - * take their colour on hover; the armed tool keeps it, on the primary tint. + * take their colour on hover. Neutral tiles keep that behavior when armed. */ export function BuildToolTile({ active, @@ -141,6 +142,7 @@ export function BuildToolTile({ iconSrc, label, size = 'sm', + tone = 'primary', ...buttonProps }: BuildToolTileProps) { return ( @@ -152,7 +154,9 @@ export function BuildToolTile({ // tiles stretch together, so a row keeps one height. size === 'lg' ? 'h-[104px] gap-1.5 px-1.5 pt-2 pb-2.5' : 'min-h-[74px] gap-1 px-1 pt-1.5 pb-2', active - ? 'bg-primary/10 ring-1 ring-primary/50' + ? tone === 'neutral' + ? 'bg-black/8 ring-1 ring-foreground/30 dark:bg-muted' + : 'bg-primary/10 ring-1 ring-primary/50' : 'bg-black/4 hover:bg-black/8 dark:bg-muted/40 dark:hover:bg-muted', className, )} @@ -164,7 +168,8 @@ export function BuildToolTile({ className={cn( 'min-h-0 object-contain transition duration-200 group-hover:scale-110', size === 'lg' ? 'size-14' : 'size-9', - !active && 'opacity-70 grayscale group-hover:opacity-100 group-hover:grayscale-0', + (!active || tone === 'neutral') && + 'opacity-70 grayscale group-hover:opacity-100 group-hover:grayscale-0', )} draggable={false} src={iconSrc} diff --git a/packages/editor/src/components/ui/controls/action-button.tsx b/packages/editor/src/components/ui/controls/action-button.tsx index 50713d018e..fbef7817cf 100644 --- a/packages/editor/src/components/ui/controls/action-button.tsx +++ b/packages/editor/src/components/ui/controls/action-button.tsx @@ -15,12 +15,12 @@ export function ActionButton({ icon, label, className, ...props }: ActionButtonP // The fill runs through custom properties so a caller's `bg-*` or // `hover:bg-*` replaces it in both themes; tailwind-merge would keep a // `dark:bg-*` fill alive under the caller's class. - 'flex h-9 flex-1 items-center justify-center gap-1.5 rounded-lg border border-border/50 bg-(--action-fill) px-3 font-medium text-foreground text-xs transition-colors [--action-fill-hover:rgb(0_0_0/0.08)] [--action-fill:rgb(0_0_0/0.04)] hover:bg-(--action-fill-hover) active:bg-(--action-fill-hover) dark:[--action-fill-hover:#3e3e3e] dark:[--action-fill:#2C2C2E]', + 'flex min-h-9 min-w-0 flex-1 shrink-0 items-center justify-center gap-1.5 rounded-lg border border-border/50 bg-(--action-fill) px-3 py-2 font-medium text-foreground text-xs leading-4 transition-colors [&>svg]:shrink-0 [--action-fill-hover:rgb(0_0_0/0.08)] [--action-fill:rgb(0_0_0/0.04)] hover:bg-(--action-fill-hover) active:bg-(--action-fill-hover) dark:[--action-fill-hover:#3e3e3e] dark:[--action-fill:#2C2C2E]', className, )} > {icon} - {label} + {label} ) } diff --git a/packages/editor/src/components/ui/controls/segmented-control.tsx b/packages/editor/src/components/ui/controls/segmented-control.tsx index ecbe6bfb8a..fa43f725df 100644 --- a/packages/editor/src/components/ui/controls/segmented-control.tsx +++ b/packages/editor/src/components/ui/controls/segmented-control.tsx @@ -22,7 +22,7 @@ export function SegmentedControl({ return (
({ ) })} diff --git a/packages/editor/src/components/ui/helpers/helper-manager.tsx b/packages/editor/src/components/ui/helpers/helper-manager.tsx index 61770b4ae5..a64a9454e6 100644 --- a/packages/editor/src/components/ui/helpers/helper-manager.tsx +++ b/packages/editor/src/components/ui/helpers/helper-manager.tsx @@ -314,7 +314,7 @@ export function HelperManager() { // A tool whose kind gives placement notices: its transient draft is the node in hand. const toolNotices = !!(tool && nodeRegistry.get(tool)?.placementNotice) const toolDraftId = useScene((s) => (toolNotices ? transientDraftId(s.nodes) : null)) - const placementNotice = usePlacementNotice(movingNode?.id ?? toolDraftId) + const placementNotice = usePlacementNotice(movingNode?.id ?? toolDraftId, toolNotices) const reshapingNode = useReshapingNode() const activeHandleDrag = useActiveHandleDrag() const mezzanineHandle = useScene((s) => mezzanineGesture(activeHandleDrag, s.nodes)) diff --git a/packages/editor/src/hooks/use-placement-notice.test.ts b/packages/editor/src/hooks/use-placement-notice.test.ts index c16aafd7b6..28eb0c6ece 100644 --- a/packages/editor/src/hooks/use-placement-notice.test.ts +++ b/packages/editor/src/hooks/use-placement-notice.test.ts @@ -1,6 +1,10 @@ import { describe, expect, test } from 'bun:test' import { type AnyNode, registerNode } from '@pascal-app/core' -import { placementNoticeOf, transientDraftId } from './use-placement-notice' +import { + placementNoticeOf, + previewPlacementNoticeOf, + transientDraftId, +} from './use-placement-notice' // The editor asks a node's definition for its placement notice; it names no kind. function registerKind(placementNotice?: unknown): string { @@ -46,3 +50,22 @@ describe('the placement notice of the node in hand', () => { expect(transientDraftId({ kept: nodes.kept })).toBeNull() }) }) + +test('ephemeral preview notices see their context without inserting a draft into the scene', () => { + const kind = registerKind((node: AnyNode, ctx: { nodes: Record }) => ({ + line: `${node.id}:${ctx.nodes.child?.name}`, + })) + const nodes = {} + const draft = nodeOf('preview', kind) + expect( + previewPlacementNoticeOf(nodes, { + node: draft, + parentNode: null, + contextNodes: [{ ...nodeOf('child', kind), name: 'draft child' }], + }), + ).toEqual({ line: 'preview:draft child' }) + expect(nodes).toEqual({}) + expect( + previewPlacementNoticeOf(nodes, { node: null, parentNode: null, contextNodes: [] }), + ).toBeNull() +}) diff --git a/packages/editor/src/hooks/use-placement-notice.ts b/packages/editor/src/hooks/use-placement-notice.ts index 2dcc0c25d2..e1a28f1c3a 100644 --- a/packages/editor/src/hooks/use-placement-notice.ts +++ b/packages/editor/src/hooks/use-placement-notice.ts @@ -8,6 +8,8 @@ import { useScene, } from '@pascal-app/core' import { useMemo } from 'react' +import { useShallow } from 'zustand/react/shallow' +import usePlacementPreview from '../store/use-placement-preview' /** The notice `nodeId`'s kind gives for where it stands (`placementNotice`), if it declares one. */ export function placementNoticeOf( @@ -21,18 +23,47 @@ export function placementNoticeOf( return notice(node as never, live ? { nodes, live } : { nodes }) } +export function previewPlacementNoticeOf( + nodes: Readonly>, + draft: Pick< + ReturnType, + 'node' | 'parentNode' | 'contextNodes' + >, +): PlacementNotice | null { + if (!draft.node) return null + const context = { + ...nodes, + ...Object.fromEntries(draft.contextNodes.map((node) => [node.id, node])), + ...(draft.parentNode ? { [draft.parentNode.id]: draft.parentNode } : {}), + [draft.node.id]: draft.node, + } + return placementNoticeOf(context, draft.node.id) +} + /** * What the node in hand, or the selected node, says about where it stands, read at its live pose * while it is placed or moved. Subscribes to the scene only while a node is given, so an * always-mounted caller doesn't re-render on every write. */ -export function usePlacementNotice(nodeId: string | null | undefined): PlacementNotice | null { - const nodes = useScene((state) => (nodeId ? state.nodes : null)) - const live = useLiveTransforms((state) => (nodeId ? state.get(nodeId) : undefined)) - return useMemo( - () => (nodeId && nodes ? placementNoticeOf(nodes, nodeId, live) : null), - [nodes, live, nodeId], +export function usePlacementNotice( + nodeId: string | null | undefined, + preview = false, +): PlacementNotice | null { + const draft = usePlacementPreview( + useShallow((state) => + preview + ? { node: state.node, parentNode: state.parentNode, contextNodes: state.contextNodes } + : null, + ), ) + const nodes = useScene((state) => (nodeId || draft?.node ? state.nodes : null)) + const live = useLiveTransforms((state) => (nodeId ? state.get(nodeId) : undefined)) + return useMemo(() => { + if (!nodes) return null + if (nodeId) return placementNoticeOf(nodes, nodeId, live) + if (!draft?.node) return null + return previewPlacementNoticeOf(nodes, draft) + }, [nodes, live, nodeId, draft]) } /** The node a construction tool is placing: its transient draft. */ diff --git a/packages/nodes/README.md b/packages/nodes/README.md index 6b9c4ffbf3..731c9910e7 100644 --- a/packages/nodes/README.md +++ b/packages/nodes/README.md @@ -32,3 +32,47 @@ for bootstrap ordering in a React application. ## License MIT + +## Kitchen agent tools + +The built-in plugin exports `builtinAgentTools` from `@pascal-app/nodes/agent-tools` +(zod-only contracts) and `builtinAgentOperations` from +`@pascal-app/nodes/agent-operations` (headless planners). Both the inspector and +agents execute the same finishing planner, including hosted-item support checks. + +- `kitchen_finish_run({ runId, action: 'align' | 'fill' })` aligns a run or closes + 50–150 mm wall gaps. Results apply in one undo step. Missing runs and unsupported + hosted items return `cabinet_run_not_found` and `hosted_items_unsupported`. +- `kitchen_check_clearance({ nodeId })` returns an advisory opening warning for a + run or module. It shares the registry notice used during placement, movement, + and inspection. It checks conservative envelopes against visible floor objects + and straight walls; curved walls and wall openings are not resolved. + +A host that installs the plugin registers its tools on its MCP server with +`registerOperationTool`, the shared tools' runner, under its own reviewed +annotations (see the MCP README's plugin tools). Load the plugin definitions into +the scene registry as usual: clearance queries read each installed kind's +floor-placement capability. + +```ts +import { registerOperationTool } from '@pascal-app/mcp/tools/shared-tools' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' +import { builtinAgentTools } from '@pascal-app/nodes/agent-tools' + +for (const contract of builtinAgentTools.tools) { + registerOperationTool(server, operations, { + contract, + operation: builtinAgentOperations[contract.name], + annotations: { + readOnlyHint: contract.name === 'kitchen_check_clearance', + destructiveHint: false, + openWorldHint: false, + }, + }) +} +``` + +Hosted chat declares the same contracts and applies the same operation outcomes +through its shared executor. These tools run as `operation` tools, so they do not +need a browser executor or custom chat card. Hosts retain control of which tools +are offered. The generic MCP server does not install a node plugin implicitly. diff --git a/packages/nodes/package.json b/packages/nodes/package.json index 35d2729609..bcc5875a7f 100644 --- a/packages/nodes/package.json +++ b/packages/nodes/package.json @@ -15,6 +15,16 @@ "types": "./dist/procedural-item/index.d.ts", "import": "./dist/procedural-item/index.js", "default": "./dist/procedural-item/index.js" + }, + "./agent-tools": { + "types": "./dist/agent-tools/index.d.ts", + "import": "./dist/agent-tools/index.js", + "default": "./dist/agent-tools/index.js" + }, + "./agent-operations": { + "types": "./dist/agent-operations/index.d.ts", + "import": "./dist/agent-operations/index.js", + "default": "./dist/agent-operations/index.js" } }, "files": [ @@ -22,7 +32,7 @@ "README.md" ], "scripts": { - "build": "NODE_OPTIONS=--max-old-space-size=6144 tsc --build", + "build": "NODE_OPTIONS=--max-old-space-size=6144 tsc --build && bun ../../scripts/fix-node-esm-imports.ts dist", "dev": "tsgo --build --watch", "test": "bun test", "prepublishOnly": "bun run build && bun test" @@ -40,8 +50,10 @@ "zustand": "^5" }, "devDependencies": { + "@modelcontextprotocol/sdk": "^1.30.0", "@pascal-app/core": "^1.0.4", "@pascal-app/editor": "^1.0.4", + "@pascal-app/mcp": "^1.0.4", "@pascal-app/viewer": "^1.0.4", "@pascal/typescript-config": "*", "@react-three/test-renderer": "^9.1.1", diff --git a/packages/nodes/src/agent-operations/index.ts b/packages/nodes/src/agent-operations/index.ts new file mode 100644 index 0000000000..2702c42586 --- /dev/null +++ b/packages/nodes/src/agent-operations/index.ts @@ -0,0 +1,8 @@ +import type { AgentOperations } from '@pascal-app/core/agent-operations' +import { checkKitchenClearance, finishKitchenRun } from '../cabinet/finish-operation' + +export { checkKitchenClearance, finishKitchenRun } +export const builtinAgentOperations = { + kitchen_finish_run: finishKitchenRun, + kitchen_check_clearance: checkKitchenClearance, +} satisfies AgentOperations diff --git a/packages/nodes/src/agent-operations/kitchen-tools.test.ts b/packages/nodes/src/agent-operations/kitchen-tools.test.ts new file mode 100644 index 0000000000..7afc755b2b --- /dev/null +++ b/packages/nodes/src/agent-operations/kitchen-tools.test.ts @@ -0,0 +1,105 @@ +import { expect, test } from 'bun:test' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { nodeRegistry, registerNode } from '@pascal-app/core' +import { CabinetModuleNode, CabinetNode, LevelNode, WallNode } from '@pascal-app/core/schema' +import { SceneBridge } from '@pascal-app/mcp/bridge' +import { createSceneOperations } from '@pascal-app/mcp/operations' +import { registerOperationTool } from '@pascal-app/mcp/tools/shared-tools' +import { cabinetDefinition, cabinetModuleDefinition } from '@pascal-app/nodes' +import { builtinAgentOperations } from '@pascal-app/nodes/agent-operations' +import { builtinAgentTools } from '@pascal-app/nodes/agent-tools' + +// The kitchen tools as a host registers them: the plugin's contracts and operations, the host's +// annotations, through the shared-tool runner and a real client. +for (const action of ['fill', 'align'] as const) { + test(`kitchen ${action}: shared operation and real MCP client agree and undo together`, async () => { + const restore = nodeRegistry._snapshot() + registerNode(cabinetDefinition) + registerNode(cabinetModuleDefinition) + const level = LevelNode.parse({}) + const run = CabinetNode.parse({ parentId: level.id, depth: 0.6, carcassHeight: 0.72 }) + const module = CabinetModuleNode.parse({ + parentId: run.id, + width: 0.6, + depth: 0.6, + carcassHeight: 0.8, + position: [0, 0.1, 0], + }) + run.children = [module.id] + const walls = [-0.5, 0.5].map((x) => + WallNode.parse({ parentId: level.id, start: [x, -1], end: [x, 1], thickness: 0.2 }), + ) + level.children = [run.id, ...walls.map((wall) => wall.id)] + const nodes = Object.fromEntries([level, run, module, ...walls].map((node) => [node.id, node])) + const direct = builtinAgentOperations.kitchen_finish_run( + nodes, + { runId: run.id, action }, + { activeLevelId: null }, + ) + const bridge = new SceneBridge() + bridge.setScene(nodes, [level.id]) + bridge.clearHistory() + const server = new McpServer({ name: 'kitchen-test', version: '0.0.0' }) + const operations = createSceneOperations({ bridge }) + for (const contract of builtinAgentTools.tools) { + if (contract.runsIn !== 'operation') continue + registerOperationTool(server, operations, { + contract, + operation: builtinAgentOperations[contract.name]!, + annotations: { + readOnlyHint: contract.name === 'kitchen_check_clearance', + destructiveHint: false, + openWorldHint: false, + }, + }) + } + const client = new Client({ name: 'kitchen-test', version: '0.0.0' }) + const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair() + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) + try { + const list = await client.listTools() + expect(list.tools.find((tool) => tool.name === 'kitchen_finish_run')?.description).toBe( + builtinAgentTools.tools[0]!.description, + ) + const result = await client.callTool({ + name: 'kitchen_finish_run', + arguments: { runId: run.id, action }, + }) + expect(result.isError).not.toBe(true) + const after = bridge.getNodes() + if (action === 'fill') { + expect(direct.changes?.create).toHaveLength(2) + expect( + Object.values(after).filter( + (node) => node.type === 'cabinet-module' && node.moduleKind === 'wall-filler', + ), + ).toHaveLength(2) + } else { + expect(after[module.id]?.carcassHeight).toBe(0.72) + expect(direct.changes?.update?.find((entry) => entry.id === module.id)?.data).toMatchObject( + { carcassHeight: 0.72 }, + ) + } + const check = await client.callTool({ + name: 'kitchen_check_clearance', + arguments: { nodeId: run.id }, + }) + expect(check.isError).not.toBe(true) + bridge.undo() + expect(bridge.getNodes()[run.id]?.children).toEqual([module.id]) + expect(bridge.getNodes()[module.id]?.carcassHeight).toBe(0.8) + const missing = await client.callTool({ + name: 'kitchen_finish_run', + arguments: { runId: 'cabinet_missing', action }, + }) + expect(missing.isError).toBe(true) + expect(JSON.stringify(missing.content)).toContain('cabinet_run_not_found') + } finally { + await client.close() + await server.close() + restore() + } + }) +} diff --git a/packages/nodes/src/agent-tools/contracts.test.ts b/packages/nodes/src/agent-tools/contracts.test.ts new file mode 100644 index 0000000000..643c38ff9a --- /dev/null +++ b/packages/nodes/src/agent-tools/contracts.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { bareNumberPaths, unshownDefaultPaths } from '@pascal-app/core/agent-tools' +import { builtinAgentTools } from '@pascal-app/nodes/agent-tools' + +// The plugin's contracts are declared where core's are, including the hosted chat's sandbox, +// which rejects packages that depend on Node modules: they import zod and core's types only. +test('the kitchen tool contracts reach only zod', () => { + const source = readFileSync(resolve(import.meta.dir, 'index.ts'), 'utf8') + const runtime = [ + ...source.matchAll(/^(?:import|export)\s+(?!type\s)[^'"]*?from\s+['"]([^'"]+)['"]/gm), + ].map((match) => match[1]) + expect(runtime).toEqual(['zod']) +}) + +test('the kitchen tools take no bare length and show every default', () => { + expect(bareNumberPaths(builtinAgentTools.tools)).toEqual([]) + expect(unshownDefaultPaths(builtinAgentTools.tools)).toEqual([]) +}) diff --git a/packages/nodes/src/agent-tools/index.ts b/packages/nodes/src/agent-tools/index.ts new file mode 100644 index 0000000000..a9c78de942 --- /dev/null +++ b/packages/nodes/src/agent-tools/index.ts @@ -0,0 +1,25 @@ +import type { PluginAgentTools } from '@pascal-app/core/agent-tools' +import { z } from 'zod' + +export const finishKitchenRunTool = { + name: 'kitchen_finish_run' as const, + title: 'Finish kitchen run', + description: + 'Align a cabinet run or fit wall fillers. align matches base heights, backs, reveals and handles while preserving tall appliances, compartments and hosted-item support. fill closes 50–150 mm gaps at exposed ends beside perpendicular walls without moving existing modules. Repeating fill is a no-op. Refuses cabinet_run_not_found or hosted_items_unsupported. One undo step.', + input: { runId: z.string(), action: z.enum(['align', 'fill']) }, + runsIn: 'operation' as const, +} +export const checkKitchenClearanceTool = { + name: 'kitchen_check_clearance' as const, + title: 'Check kitchen opening clearance', + description: + 'Check a cabinet run or module for advisory door and drawer opening clearance against visible floor-placed objects and straight walls on its level. Accounts for hosting transforms and floor support. Conservative envelopes, not exact hinge sweeps; curved walls and wall openings are not resolved. Does not change the scene. Requires the scene’s node definitions in the registry; refuses cabinet_not_found or node_capability_unavailable.', + input: { nodeId: z.string() }, + runsIn: 'operation' as const, +} +export const builtinAgentTools = { + pluginId: 'pascal:core', + apiVersion: 1, + version: '1.0.0', + tools: [finishKitchenRunTool, checkKitchenClearanceTool], +} satisfies PluginAgentTools diff --git a/packages/nodes/src/cabinet/__bench__/geometry.ts b/packages/nodes/src/cabinet/__bench__/geometry.ts new file mode 100644 index 0000000000..54b061b388 --- /dev/null +++ b/packages/nodes/src/cabinet/__bench__/geometry.ts @@ -0,0 +1,21 @@ +import { Mesh } from 'three' +import { buildCabinetGeometry } from '../geometry' +import { CABINET_PRESETS } from '../presets' +import { CabinetModuleNode } from '../schema' + +// Run with: bun packages/nodes/src/cabinet/__bench__/geometry.ts +// Counts include interiors and interaction meshes, even when hidden by closed doors. +const results = CABINET_PRESETS.map((preset) => { + const root = buildCabinetGeometry(CabinetModuleNode.parse(preset.createPatch())) + let triangles = 0 + let meshes = 0 + root.traverse((object) => { + if (!(object instanceof Mesh)) return + meshes++ + triangles += + (object.geometry.index?.count ?? object.geometry.getAttribute('position').count) / 3 + object.geometry.dispose() + }) + return { item: preset.id, triangles, meshes } +}) +console.table(results) diff --git a/packages/nodes/src/cabinet/__tests__/defaults.test.ts b/packages/nodes/src/cabinet/__tests__/defaults.test.ts index 96e892da1c..97383be57c 100644 --- a/packages/nodes/src/cabinet/__tests__/defaults.test.ts +++ b/packages/nodes/src/cabinet/__tests__/defaults.test.ts @@ -7,6 +7,7 @@ import { CabinetNode, type SceneApi, } from '@pascal-app/core' +import { kitchenItemMatches, kitchenPresetForModule } from '@pascal-app/nodes' import { cabinetDefinition, cabinetModuleDefinition } from '../definition' import { CABINET_PRESETS, cabinetPresetById } from '../presets' import { addWallChildAbove } from '../run-ops' @@ -77,10 +78,30 @@ test('cabinet creation defaults use the metric 600 mm family', () => { carcassHeight: CABINET_METRIC_DEFAULTS.carcassHeight, }) for (const preset of CABINET_PRESETS) { - expect(preset.createPatch().depth).toBeCloseTo(CABINET_METRIC_DEFAULTS.depth) + expect(preset.createPatch().depth).toBeCloseTo( + preset.id === 'wall-cabinet' ? 0.35 : CABINET_METRIC_DEFAULTS.depth, + ) } }) +test('kitchen search discovers appliances by familiar names and finds renamed modules by their contents', () => { + expect(kitchenItemMatches('fridge-single', 'refrigerator')).toBe(true) + expect(kitchenItemMatches('drawer-base', 'drawers')).toBe(true) + expect(kitchenItemMatches('cooktop-gas', 'gas stove')).toBe(true) + expect(kitchenItemMatches('dishwasher', 'refrigerator')).toBe(false) + const fridge = CabinetModuleNode.parse({ + ...cabinetPresetById('fridge-single').createPatch(), + name: 'My cold storage', + }) + expect(kitchenPresetForModule(fridge)).toBe('fridge-single') + expect(fridge.carcassHeight).toBeGreaterThan(1.5) + expect(fridge.withCountertop).toBe(false) + const wall = CabinetModuleNode.parse(cabinetPresetById('wall-cabinet').createPatch()) + expect(wall.showPlinth).toBe(false) + expect(wall.withCountertop).toBe(false) + expect(kitchenPresetForModule(wall, CabinetNode.parse({ runTier: 'wall' }))).toBe('wall-cabinet') +}) + test('placed cabinet runs and modules opt into ordinary body dragging', () => { expect(cabinetDefinition.capabilities.movable?.directDrag).toBe(true) expect(cabinetModuleDefinition.capabilities.movable?.directDrag).toBe(true) diff --git a/packages/nodes/src/cabinet/__tests__/front-style.test.ts b/packages/nodes/src/cabinet/__tests__/front-style.test.ts index f41cb428e9..74d7de50ce 100644 --- a/packages/nodes/src/cabinet/__tests__/front-style.test.ts +++ b/packages/nodes/src/cabinet/__tests__/front-style.test.ts @@ -25,12 +25,22 @@ function findMeshByNamePrefix(root: { children: unknown[] }, prefix: string): Me function frontProfileStats(mesh: Mesh, recessTolerance = 0.001) { const position = mesh.geometry.getAttribute('position') as BufferAttribute + mesh.geometry.computeBoundingBox() + const bounds = mesh.geometry.boundingBox! let frameMaxZ = -Infinity for (let i = 0; i < position.count; i += 1) frameMaxZ = Math.max(frameMaxZ, position.getZ(i)) let panelMaxZ = -Infinity for (let i = 0; i < position.count; i += 1) { const z = position.getZ(i) + // Measure the recessed panel, excluding the outer edge chamfer. + if ( + position.getX(i) < bounds.min.x + 0.01 || + position.getX(i) > bounds.max.x - 0.01 || + position.getY(i) < bounds.min.y + 0.01 || + position.getY(i) > bounds.max.y - 0.01 + ) + continue if (z < frameMaxZ - recessTolerance) panelMaxZ = Math.max(panelMaxZ, z) } return { frameMaxZ, panelMaxZ } diff --git a/packages/nodes/src/cabinet/__tests__/geometry.test.ts b/packages/nodes/src/cabinet/__tests__/geometry.test.ts index a61a7430fe..ddf6066a3e 100644 --- a/packages/nodes/src/cabinet/__tests__/geometry.test.ts +++ b/packages/nodes/src/cabinet/__tests__/geometry.test.ts @@ -8,7 +8,7 @@ import type { } from '@pascal-app/core' import { cabinetSlots } from '@pascal-app/core' import type { BufferAttribute, Mesh, Object3D } from 'three' -import { Box3 } from 'three' +import { Box3, Raycaster, Vector3 } from 'three' import { bakeCabinetAnimationClip } from '../animation' import { cabinetDefinition, cabinetModuleDefinition } from '../definition' import { buildCabinetGeometry } from '../geometry' @@ -217,11 +217,10 @@ function boxTopUvSpan(mesh: Mesh) { function boxFrontUvSpan(mesh: Mesh) { const uv = mesh.geometry.getAttribute('uv') as BufferAttribute - const faceStart = 16 - const values = Array.from({ length: 4 }, (_, index) => ({ - u: uv.getX(faceStart + index), - v: uv.getY(faceStart + index), - })) + const normals = mesh.geometry.getAttribute('normal') + const values = Array.from({ length: uv.count }, (_, index) => index) + .filter((index) => normals.getZ(index) > 0.99) + .map((index) => ({ u: uv.getX(index), v: uv.getY(index) })) return { u: Math.max(...values.map((value) => value.u)) - Math.min(...values.map((value) => value.u)), v: Math.max(...values.map((value) => value.v)) - Math.min(...values.map((value) => value.v)), @@ -430,6 +429,36 @@ describe('buildCabinetGeometry — raised arch fronts', () => { }) describe('buildCabinetGeometry — inset internals', () => { + test('drawer runners separate fixed and moving parts and the bottom is recessed', () => { + const group = buildCabinetGeometry( + CabinetModuleNode.parse({ + operationState: 1, + stack: [{ id: 'drawer', type: 'drawer', drawerCount: 3 }], + }), + ) + const fixed = findMeshByNamePrefix(group, 'cabinet-drawer-fixed-runner-') + const moving = findMeshByNamePrefix(group, 'cabinet-drawer-moving-runner-') + const side = findMeshByNamePrefix(group, 'cabinet-drawer-side-left-') + const bottom = findMeshByNamePrefix(group, 'cabinet-drawer-bottom-') + expect(fixed.parent).toBe(group) + expect(moving.parent).toBe(side.parent) + expect(worldBounds(moving).max.z).toBeGreaterThan(worldBounds(fixed).max.z + 0.1) + expect(worldBounds(bottom).min.y).toBeGreaterThan(worldBounds(side).min.y + 0.004) + }) + + test('a narrow drawer keeps its bar pull within the front', () => { + const group = buildCabinetGeometry( + CabinetModuleNode.parse({ + width: 0.15, + handleStyle: 'bar', + stack: [{ id: 'drawer', type: 'drawer', drawerCount: 3 }], + }), + ) + const front = worldBounds(findMeshByNamePrefix(group, 'cabinet-drawer-front-')) + const handle = worldBounds(findMeshByNamePattern(group, /^cabinet-drawer-handle-[\d.]+-0$/)) + expect(handle.min.x).toBeGreaterThan(front.min.x) + expect(handle.max.x).toBeLessThan(front.max.x) + }) test('inset drawer boxes stay set back behind the front plane', () => { const node = CabinetModuleNode.parse({ frontStyle: 'shaker', @@ -717,11 +746,57 @@ describe('buildCabinetGeometry — appliance compartments', () => { expect(findMeshByName(group, 'cabinet-microwave-0-start-button')).toBeDefined() expect(findMeshByName(group, 'cabinet-microwave-0-cancel-button')).toBeDefined() expect(findMeshByName(group, 'cabinet-microwave-0-top-vent-0')).toBeDefined() - expect(findMeshByName(group, 'cabinet-microwave-0-window-dot-0-0')).toBeDefined() + const screen = findMeshByName(group, 'cabinet-microwave-0-window-screen') + const glass = findMeshByName(group, 'cabinet-microwave-0-door-glass') + const screenBounds = worldBounds(screen) + const glassBounds = worldBounds(glass) + expect(screen.userData.slotId).toBe('glass') + expect(screen.parent).toBe(glass.parent) + expect(screenBounds.min.x).toBeGreaterThan(glassBounds.min.x) + expect(screenBounds.max.x).toBeLessThan(glassBounds.max.x) + expect(screenBounds.min.y).toBeGreaterThan(glassBounds.min.y) + expect(screenBounds.max.y).toBeLessThan(glassBounds.max.y) expect(findMeshByName(group, 'cabinet-microwave-0-turntable')).toBeDefined() expect(findMeshByName(group, 'cabinet-microwave-0-roller-ring')).toBeDefined() }) + test.each(['none', 'knob'] as const)( + 'pull-out pantry respects the %s handle style', + (handleStyle) => { + const group = buildCabinetGeometry( + CabinetModuleNode.parse({ + cabinetType: 'tall', + carcassHeight: 1.8, + handleStyle, + stack: [{ id: 'pantry', type: 'pull-out-pantry', height: 1.8 }], + }), + ) + const handles: Object3D[] = [] + group.traverse((object) => { + if (object.name.startsWith('cabinet-pull-out-pantry-0-handle')) handles.push(object) + }) + if (handleStyle === 'none') expect(handles).toHaveLength(0) + else { + const handle = worldBounds(findMeshByName(group, 'cabinet-pull-out-pantry-0-handle')) + expect(handle.max.y - handle.min.y).toBeLessThan(0.03) + } + }, + ) + + test('microwave liner does not overlap the cabinet top exterior', () => { + const node = CabinetModuleNode.parse({ + width: 0.76, + carcassHeight: 0.4, + showPlinth: false, + withCountertop: false, + stack: [{ id: 'micro', type: 'microwave', height: 0.4 }], + }) + const group = buildCabinetGeometry(node) + const top = worldBounds(findMeshByName(group, 'cabinet-top')) + const liner = worldBounds(findMeshByName(group, 'cabinet-microwave-0-cavity-top')) + expect(top.max.y - liner.max.y).toBeGreaterThan(0.001) + }) + test('microwave keypad stays compact inside the control panel', () => { const node = CabinetModuleNode.parse({ width: 0.61, @@ -796,6 +871,9 @@ describe('buildCabinetGeometry — appliance compartments', () => { expect(findMeshByName(group, 'cabinet-dishwasher-0-tub-back')).toBeDefined() expect(findMeshByName(group, 'cabinet-dishwasher-0-upper-rack-bar-1')).toBeDefined() + const rackFloor = worldBounds(findMeshByName(group, 'cabinet-dishwasher-0-upper-rack-bar-1')) + const rackSide = worldBounds(findMeshByName(group, 'cabinet-dishwasher-0-upper-rack-frame-0')) + expect(rackSide.max.y - rackFloor.max.y).toBeGreaterThan(0.04) expect(findMeshByName(group, 'cabinet-dishwasher-0-lower-rack-bar-1')).toBeDefined() expect(findMeshByName(group, 'cabinet-dishwasher-0-spray-arm')).toBeDefined() expect(findMeshByName(group, 'cabinet-dishwasher-0-control-panel')).toBeDefined() @@ -845,6 +923,9 @@ describe('buildCabinetGeometry — appliance compartments', () => { 'hardware', ) expect(findMeshByName(group, 'cabinet-cooktop-gas-1-continuous-grate-front')).toBeDefined() + const supports = worldBounds(findMeshByName(group, 'cabinet-cooktop-gas-1-pan-supports')) + const burner = worldBounds(findMeshByName(group, 'cabinet-cooktop-gas-1-burner-0-cap')) + expect(supports.min.y).toBeGreaterThan(burner.max.y) expect(findMeshByName(group, 'cabinet-cooktop-gas-1-continuous-grate-row-1')).toBeDefined() expect(findMeshByName(group, 'cabinet-cooktop-gas-1-continuous-grate-column-1')).toBeDefined() expect(findMeshByName(group, 'cabinet-cooktop-gas-1-knob-4')).toBeDefined() @@ -877,6 +958,7 @@ describe('buildCabinetGeometry — appliance compartments', () => { const group = buildCabinetGeometry(node, undefined, 'rendered', false) expect(hasObjectByName(group, 'cabinet-cooktop-gas-1-continuous-grate-front')).toBe(false) + expect(hasObjectByName(group, 'cabinet-cooktop-gas-1-pan-supports')).toBe(false) expect(findMeshByName(group, 'cabinet-cooktop-gas-1-burner-0-flame-ring')).toBeDefined() expect(findMeshByName(group, 'cabinet-cooktop-gas-1-burner-0-flame-core')).toBeDefined() expect(findMeshByName(group, 'cabinet-cooktop-gas-1-burner-0-flame-0')).toBeDefined() @@ -899,6 +981,9 @@ describe('buildCabinetGeometry — appliance compartments', () => { 'appliance', ) expect(findMeshByName(group, 'cabinet-cooktop-induction-1-zone-0-ring-0')).toBeDefined() + expect( + findMeshByName(group, 'cabinet-cooktop-induction-1-zone-0-ring-0').material, + ).toHaveProperty('emissiveIntensity', 0) expect(findMeshByName(group, 'cabinet-cooktop-induction-1-zone-0-fill')).toBeDefined() expect(findMeshByName(group, 'cabinet-cooktop-induction-1-zone-0-ring-2')).toBeDefined() expect(findMeshByName(group, 'cabinet-cooktop-induction-1-zone-3-ring-1')).toBeDefined() @@ -1074,6 +1159,16 @@ describe('buildCabinetGeometry — appliance compartments', () => { findMeshByName(group, 'cabinet-fridge-single-0-single-rear-diffuser-channel-0'), ).toBeDefined() expect(findMeshByName(group, 'cabinet-fridge-single-0-single-crisper-drawer-0')).toBeDefined() + const crisper = findMeshByName(group, 'cabinet-fridge-single-0-single-crisper-drawer-0') + const crisperBounds = worldBounds(crisper) + const center = crisperBounds.getCenter(new Vector3()) + const ray = new Raycaster( + new Vector3(center.x, crisperBounds.max.y + 0.01, center.z), + new Vector3(0, -1, 0), + ) + const hit = ray.intersectObject(crisper, false)[0] + expect(hit).toBeDefined() + expect(hit!.point.y).toBeCloseTo(crisperBounds.min.y + 0.008, 4) expect( findMeshByName(group, 'cabinet-fridge-single-0-single-crisper-drawer-0-handle'), ).toBeDefined() @@ -2887,6 +2982,18 @@ describe('cabinet handles', () => { }) describe('buildCabinetGeometry — range hood compartments', () => { + test.each(['hood-pyramid', 'hood-curved-glass'] as const)( + '%s exposes its filter and lights below the canopy', + (type) => { + const group = buildCabinetGeometry(hoodModule(type, 0.4)) + const filter = worldBounds(findMeshByName(group, `cabinet-${type}-0-filter`)) + const light = worldBounds(findMeshByName(group, `cabinet-${type}-0-light-1`)) + expect(filter.min.y).toBeLessThan(0) + expect(light.min.y).toBeLessThan(0) + expect(light.min.x).toBeGreaterThan(filter.max.x) + expect(filter.max.z).toBeLessThan(HOOD_CANOPY_DEPTH - 0.16) + }, + ) function hoodModule(type: 'hood-pyramid' | 'hood-curved-glass', hoodHeight: number) { return CabinetModuleNode.parse({ id: 'cabinet-module_hood', @@ -3035,6 +3142,25 @@ describe('buildCabinetGeometry — sink compartments', () => { expect(findMeshByName(group, 'cabinet-sink-1-faucet-handle-pin')).toBeDefined() }) + test('sink bowl narrows toward the drain while keeping its opening', () => { + const group = buildCabinetGeometry(sinkModule()) + const wall = findMeshByName(group, 'cabinet-sink-1-0-basin-front') + const positions = wall.geometry.getAttribute('position') + let topWidth = 0 + let bottomWidth = 0 + for (let i = 0; i < positions.count; i++) { + const width = Math.abs(positions.getX(i)) * 2 + if (positions.getY(i) > 0) topWidth = Math.max(topWidth, width) + else bottomWidth = Math.max(bottomWidth, width) + } + expect(topWidth - bottomWidth).toBeGreaterThan(0.03) + const bottom = worldBounds(findMeshByName(group, 'cabinet-sink-1-0-basin-bottom')) + const drain = worldBounds(findMeshByName(group, 'cabinet-sink-1-0-drain')) + expect(drain.min.x).toBeGreaterThan(bottom.min.x) + expect(drain.max.x).toBeLessThan(bottom.max.x) + expect(drain.min.y).toBeCloseTo(bottom.max.y) + }) + test('sink appliance paint persists onto faucet and basin after rebuild', () => { const ctx: GeometryContext = { ...geometryContext({ children: [] }), @@ -3201,3 +3327,33 @@ describe('buildCabinetGeometry — sink compartments', () => { expect(bounds.max.x).toBeGreaterThan(0.45) }) }) + +test('toe-kick stays continuous below a base and tall unit', () => { + const run = CabinetNode.parse({ showPlinth: true, plinthHeight: 0.1 }) + const modules = [ + CabinetModuleNode.parse({ parentId: run.id, width: 0.6, position: [-0.3, 0.1, 0] }), + CabinetModuleNode.parse({ + parentId: run.id, + width: 0.6, + position: [0.3, 0.1, 0], + cabinetType: 'tall', + carcassHeight: 2.1, + }), + ] + const group = buildCabinetGeometry(run, geometryContext({ children: modules }), 'rendered', false) + expect(group.children.filter((child) => child.name === 'cabinet-run-plinth')).toHaveLength(1) + const bounds = worldBounds(findMeshByName(group, 'cabinet-run-plinth')) + expect(bounds.max.x - bounds.min.x).toBeCloseTo(1.2) +}) + +test('wall fillers render a solid front without handles or opening animation', () => { + const node = CabinetModuleNode.parse({ + moduleKind: 'wall-filler', + width: 0.08, + stack: [], + handleStyle: 'bar', + }) + const group = buildCabinetGeometry(node, undefined, 'rendered', false) + expect(group.children).toHaveLength(1) + expect(group.children[0]!.name).toBe('cabinet-wall-filler') +}) diff --git a/packages/nodes/src/cabinet/__tests__/kitchen-catalog.test.ts b/packages/nodes/src/cabinet/__tests__/kitchen-catalog.test.ts new file mode 100644 index 0000000000..1e080a875f --- /dev/null +++ b/packages/nodes/src/cabinet/__tests__/kitchen-catalog.test.ts @@ -0,0 +1,15 @@ +import { expect, test } from 'bun:test' +import { CabinetModuleNode, CabinetNode } from '@pascal-app/core' +import { findKitchenItems } from '@pascal-app/nodes' + +test('finding placed kitchen items lists modules, not the fillers of their run', () => { + const run = CabinetNode.parse({}) + const cabinet = CabinetModuleNode.parse({ parentId: run.id, name: 'Base' }) + const fillers = (['corner-filler', 'wall-filler'] as const).map((moduleKind) => + CabinetModuleNode.parse({ parentId: run.id, moduleKind }), + ) + const nodes = Object.fromEntries([run, cabinet, ...fillers].map((node) => [node.id, node])) + expect(findKitchenItems(nodes, '').map((node) => node.id)).toEqual([cabinet.id]) + expect(findKitchenItems(nodes, 'cupboard').map((node) => node.id)).toEqual([cabinet.id]) + expect(findKitchenItems(nodes, 'dishwasher')).toEqual([]) +}) diff --git a/packages/nodes/src/cabinet/__tests__/neighbor-placement.test.ts b/packages/nodes/src/cabinet/__tests__/neighbor-placement.test.ts new file mode 100644 index 0000000000..5c1afa30d2 --- /dev/null +++ b/packages/nodes/src/cabinet/__tests__/neighbor-placement.test.ts @@ -0,0 +1,243 @@ +import { expect, test } from 'bun:test' +import { + type AnyNode, + type AnyNodeId, + CabinetModuleNode, + CabinetNode, + createSceneApi, + getSurfaceProvider, + ItemNode, + LevelNode, + nodeRegistry, + registerNode, + runAsSingleSceneHistoryStep, + useScene, + WallNode, +} from '@pascal-app/core' +import { finishKitchenRun } from '../../agent-operations' +import { cabinetDefinition, cabinetModuleDefinition } from '../definition' +import { applyCabinetModuleInsertion } from '../insertion' +import { resolveCabinetNeighborPlacement } from '../neighbor-placement' +import { runLocalToPlan } from '../run-layout' + +function fixture(rotation = 0) { + const run = CabinetNode.parse({ + parentId: 'level_test', + position: [3, 0, 2], + rotation, + depth: 0.75, + }) + const neighbor = CabinetModuleNode.parse({ + parentId: run.id, + width: 0.6, + depth: 0.75, + position: [0, 0.1, 0], + }) + run.children = [neighbor.id] + const module = CabinetModuleNode.parse({ width: 0.8, depth: 0.6 }) + const nodes: Record = { [run.id]: run, [neighbor.id]: neighbor } + return { run, neighbor, module, nodes } +} + +for (const rotation of [0, Math.PI / 2, Math.PI / 4]) { + for (const side of ['left', 'right'] as const) { + test(`joins ${side} at rotation ${rotation} with the neighbor depth`, () => { + const { run, neighbor, module, nodes } = fixture(rotation) + const x = side === 'left' ? -0.7 : 0.7 + const result = resolveCabinetNeighborPlacement({ + nodes, + module, + levelId: 'level_test', + wallTier: false, + position: runLocalToPlan(run, [x + 0.05, 0, 0.04]), + }) + expect(result?.run.id).toBe(run.id) + expect(result?.side).toBe(side) + expect(result?.depth).toBe(0.75) + expect(result?.result.ok).toBe(true) + if (!result?.result.ok) throw new Error('Expected insertion') + expect(result.result.inserted.position).toEqual([x, 0.1, 0]) + expect(result.result.modules[0]?.position).toEqual(neighbor.position) + expect(run.children).toEqual([neighbor.id]) + }) + } +} + +test('does not join distant, hidden, other-level, or incompatible-tier runs', () => { + const { run, module, nodes } = fixture() + const input = { + nodes, + module, + levelId: 'level_test', + wallTier: false, + position: runLocalToPlan(run, [0.7, 0, 0]), + } + expect(resolveCabinetNeighborPlacement({ ...input, position: [20, 0, 20] })).toBeNull() + expect(resolveCabinetNeighborPlacement({ ...input, levelId: 'level_other' })).toBeNull() + expect(resolveCabinetNeighborPlacement({ ...input, wallTier: true })).toBeNull() + run.visible = false + expect(resolveCabinetNeighborPlacement(input)).toBeNull() +}) + +test('joining preserves the run and existing module and undoes as one step', () => { + const previous = useScene.getState() + const history = useScene.temporal.getState() + const raf = globalThis.requestAnimationFrame + const cancelRaf = globalThis.cancelAnimationFrame + globalThis.requestAnimationFrame = () => 0 + globalThis.cancelAnimationFrame = () => {} + const { run, neighbor, module, nodes } = fixture(Math.PI / 4) + try { + useScene.setState({ nodes, rootNodeIds: [run.id] }) + useScene.temporal.getState().clear() + const planned = resolveCabinetNeighborPlacement({ + nodes, + module, + levelId: 'level_test', + wallTier: false, + position: runLocalToPlan(run, [0.7, 0, 0]), + }) + if (!planned?.result.ok) throw new Error('Expected join') + runAsSingleSceneHistoryStep(useScene, () => + applyCabinetModuleInsertion({ + module: { ...module, depth: planned.depth }, + plan: planned.result as Extract, + run, + sceneApi: createSceneApi(useScene), + }), + ) + expect(useScene.getState().nodes[module.id]?.parentId).toBe(run.id) + expect((useScene.getState().nodes[module.id] as typeof module).depth).toBe(0.75) + expect(useScene.getState().nodes[run.id]?.children).toContain(module.id) + expect(useScene.getState().nodes[neighbor.id]?.position).toEqual(neighbor.position) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes[module.id]).toBeUndefined() + expect(useScene.getState().nodes[run.id]?.children).toEqual([neighbor.id]) + } finally { + useScene.setState(previous) + useScene.temporal.setState(history) + globalThis.requestAnimationFrame = raf + globalThis.cancelAnimationFrame = cancelRaf + } +}) + +test('filling both run ends undoes together and preserves original modules', () => { + const previous = useScene.getState(), + history = useScene.temporal.getState() + const raf = globalThis.requestAnimationFrame, + cancelRaf = globalThis.cancelAnimationFrame + globalThis.requestAnimationFrame = () => 0 + globalThis.cancelAnimationFrame = () => {} + const level = LevelNode.parse({}) + const run = CabinetNode.parse({ parentId: level.id, depth: 0.6 }) + const module = CabinetModuleNode.parse({ parentId: run.id, width: 0.6, depth: 0.6 }) + run.children = [module.id] + const walls = [-0.5, 0.5].map((x) => + WallNode.parse({ parentId: level.id, start: [x, -1], end: [x, 1], thickness: 0.2 }), + ) + const nodes = Object.fromEntries([level, run, module, ...walls].map((node) => [node.id, node])) + try { + useScene.setState({ nodes, rootNodeIds: [level.id] }) + useScene.temporal.getState().clear() + const outcome = finishKitchenRun( + nodes, + { runId: run.id, action: 'fill' }, + { activeLevelId: null }, + ) + expect(nodes[run.id]!.children).toEqual([module.id]) + runAsSingleSceneHistoryStep(useScene, () => + useScene.getState().applyNodeChanges(outcome.changes as never), + ) + const again = finishKitchenRun( + useScene.getState().nodes, + { runId: run.id, action: 'fill' }, + { activeLevelId: null }, + ) + expect(again.changes?.create).toEqual([]) + expect(again.changes?.update).toEqual([]) + expect(useScene.getState().nodes[run.id]!.children).toHaveLength(3) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes[run.id]!.children).toEqual([module.id]) + expect(useScene.getState().nodes[module.id]).toEqual(module) + } finally { + useScene.setState(previous) + useScene.temporal.setState(history) + globalThis.requestAnimationFrame = raf + globalThis.cancelAnimationFrame = cancelRaf + } +}) + +test('finishing refuses a missing run without changing the input', () => { + const nodes = {} + expect(() => + finishKitchenRun(nodes, { runId: 'cabinet_missing', action: 'align' }, { activeLevelId: null }), + ).toThrow('Choose a kitchen run') + expect(nodes).toEqual({}) +}) + +for (const topologyChange of [false, true]) { + test(`finishing ${topologyChange ? 'refuses a disappearing support' : 'carries a hosted item'} without mutating its input`, () => { + const restore = nodeRegistry._snapshot() + try { + registerNode(cabinetDefinition) + registerNode(cabinetModuleDefinition) + const level = LevelNode.parse({}) + const run = CabinetNode.parse({ + parentId: level.id, + carcassHeight: 0.72, + withCountertop: true, + }) + const modules = [0, 1].map((i) => + CabinetModuleNode.parse({ + parentId: run.id, + width: 0.6, + depth: 0.6, + carcassHeight: topologyChange && i === 1 ? 0.9 : 0.8, + showPlinth: false, + position: [i * 0.6, 0.1, 0], + }), + ) + run.children = modules.map((node) => node.id) + const nodes = Object.fromEntries([level, run, ...modules].map((node) => [node.id, node])) + const surfaces = getSurfaceProvider(run).surfaces!(run, { + scene: { nodes: () => nodes, get: (id) => nodes[id] as never }, + }) + const surface = surfaces.at(-1)! + const item = ItemNode.parse({ + parentId: run.id, + position: [topologyChange ? 0.6 : 0, surface.position[1], 0], + asset: { + id: 'cup', + name: 'Cup', + category: 'fixture', + thumbnail: '', + src: '/cup.glb', + dimensions: [0.1, 0.1, 0.1], + }, + }) + nodes[item.id] = item + run.children.push(item.id) + const before = JSON.stringify(nodes) + // The operation must preserve support even before a browser loads definitions. + nodeRegistry._reset() + if (topologyChange) + expect(() => + finishKitchenRun(nodes, { runId: run.id, action: 'align' }, { activeLevelId: null }), + ).toThrow('keeping hosted items supported') + else { + const result = finishKitchenRun( + nodes, + { runId: run.id, action: 'align' }, + { activeLevelId: null }, + ) + const patch = result.changes?.update?.find((entry) => entry.id === item.id)?.data + expect((patch as typeof item).position[1]).toBeCloseTo(item.position[1] - 0.08) + } + expect(JSON.stringify(nodes)).toBe(before) + } finally { + restore() + } + }) +} diff --git a/packages/nodes/src/cabinet/__tests__/opening-clearance.test.ts b/packages/nodes/src/cabinet/__tests__/opening-clearance.test.ts new file mode 100644 index 0000000000..1516a9652f --- /dev/null +++ b/packages/nodes/src/cabinet/__tests__/opening-clearance.test.ts @@ -0,0 +1,238 @@ +import { expect, test } from 'bun:test' +import { + CabinetModuleNode, + CabinetNode, + ItemNode, + LevelNode, + nodeRegistry, + registerNode, + SlabNode, + WallNode, +} from '@pascal-app/core' +import { checkKitchenClearance } from '../../agent-operations' +import { itemDefinition } from '../../item/definition' +import { cabinetDefinition, cabinetModuleDefinition } from '../definition' +import { + cabinetOpeningConflicts, + cabinetOpeningFootprints, + openingFootprintsOverlap, +} from '../opening-clearance' + +test('drawer clearance follows cabinet rotation and excludes upper objects', () => { + const node = CabinetModuleNode.parse({ + depth: 0.6, + showPlinth: false, + stack: [{ id: 'drawer', type: 'drawer', height: 0.72 }], + }) + const [front] = cabinetOpeningFootprints(node, [2, 0, 3], Math.PI / 2) + expect(front!.position[0]).toBeGreaterThan(2.3) + expect(front!.position[2]).toBeCloseTo(3) + expect( + openingFootprintsOverlap(front!, { ...front!, position: [front!.position[0], 1.5, 3] }), + ).toBe(false) + expect(openingFootprintsOverlap(front!, { ...front! })).toBe(true) +}) + +test('open shelves and fillers do not request opening space', () => { + expect( + cabinetOpeningFootprints( + CabinetModuleNode.parse({ stack: [{ id: 'shelf', type: 'shelf', height: 0.72 }] }), + [0, 0, 0], + 0, + ), + ).toEqual([]) + expect( + cabinetOpeningFootprints(CabinetModuleNode.parse({ moduleKind: 'wall-filler' }), [0, 0, 0], 0), + ).toEqual([]) +}) + +test('diagonal clearance rectangles use oriented edges instead of bounding boxes', () => { + const a = { + position: [0, 0, 0] as [number, number, number], + dimensions: [2, 1, 0.1] as [number, number, number], + rotation: [0, Math.PI / 4, 0] as [number, number, number], + } + expect(openingFootprintsOverlap(a, { ...a, position: [0.3, 0, 0.3] })).toBe(false) + expect(openingFootprintsOverlap(a, { ...a, position: [0.01, 0, 0.01] })).toBe(true) +}) + +test('opening warnings detect a front wall and ignore hidden walls and other levels', () => { + const module = CabinetModuleNode.parse({ + width: 0.6, + depth: 0.6, + showPlinth: false, + stack: [{ id: 'door', type: 'door', height: 0.72 }], + }) + const level = LevelNode.parse({}) + const wall = WallNode.parse({ + parentId: level.id, + start: [-1, 0.55], + end: [1, 0.55], + thickness: 0.1, + }) + const nodes = { [level.id]: level, [wall.id]: wall } + expect(cabinetOpeningConflicts(module, [0, 0, 0], 0, level.id, nodes)).toEqual([wall.id]) + expect( + cabinetOpeningConflicts(module, [0, 1.5, 0], 0, level.id, { + ...nodes, + [wall.id]: { ...wall, height: 1 }, + }), + ).toEqual([]) + expect( + cabinetOpeningConflicts(module, [0, 0, 0], 0, level.id, { + ...nodes, + [wall.id]: { ...wall, visible: false }, + }), + ).toEqual([]) + expect(cabinetOpeningConflicts(module, [0, 0, 0], 0, 'level_elsewhere', nodes)).toEqual([]) +}) + +test('opening warnings include catalog furniture with node-local footprint positions', () => { + const restore = nodeRegistry._snapshot() + try { + nodeRegistry._reset() + registerNode(itemDefinition) + const level = LevelNode.parse({}) + const module = CabinetModuleNode.parse({ showPlinth: false, width: 0.6, depth: 0.6 }) + const chair = ItemNode.parse({ + parentId: level.id, + position: [0, 0, 0.6], + asset: { + id: 'chair', + name: 'Chair', + category: 'furniture', + thumbnail: '', + src: '/chair.glb', + dimensions: [0.3, 0.8, 0.3], + }, + }) + expect( + cabinetOpeningConflicts(module, [0, 0, 0], 0, level.id, { + [level.id]: level, + [chair.id]: chair, + }), + ).toEqual([chair.id]) + } finally { + restore() + } +}) + +for (const yaw of [0, Math.PI / 2]) { + test(`hosted furniture clearance composes translation, yaw ${yaw}, and height`, () => { + const restore = nodeRegistry._snapshot() + try { + registerNode(itemDefinition) + const level = LevelNode.parse({}) + const asset = { + id: 'fixture', + name: 'Fixture', + category: 'furniture', + thumbnail: '', + src: '/fixture.glb', + dimensions: [0.3, 0.8, 0.3], + } + const host = ItemNode.parse({ + parentId: level.id, + position: [10, 2, 4], + rotation: [0, yaw, 0], + asset, + }) + const child = ItemNode.parse({ parentId: host.id, position: [0, 0, 0.6], asset }) + const module = CabinetModuleNode.parse({ showPlinth: false, width: 0.6, depth: 0.6 }) + const nodes = { [level.id]: level, [host.id]: host, [child.id]: child } + expect(cabinetOpeningConflicts(module, [10, 2, 4], yaw, level.id, nodes)).toContain(child.id) + expect(cabinetOpeningConflicts(module, [0, 0, 0], 0, level.id, nodes)).not.toContain(child.id) + expect(cabinetOpeningConflicts(module, [10, 0, 4], yaw, level.id, nodes)).not.toContain( + child.id, + ) + } finally { + restore() + } + }) +} + +test('registry notices and agent checks share clearance at rest, during moves, and on raised slabs', () => { + const restore = nodeRegistry._snapshot() + try { + registerNode(itemDefinition) + registerNode(cabinetDefinition) + registerNode(cabinetModuleDefinition) + const level = LevelNode.parse({}) + const slab = SlabNode.parse({ + parentId: level.id, + polygon: [ + [8, 2], + [12, 2], + [12, 6], + [8, 6], + ], + elevation: 2, + }) + const run = CabinetNode.parse({ parentId: level.id, position: [10, 0, 4], showPlinth: false }) + const module = CabinetModuleNode.parse({ + parentId: run.id, + position: [0, 0, 0], + showPlinth: false, + width: 0.6, + depth: 0.6, + }) + run.children = [module.id] + const chair = ItemNode.parse({ + parentId: level.id, + position: [10, 0, 4.6], + asset: { + id: 'chair', + name: 'Chair', + category: 'furniture', + thumbnail: '', + src: '/chair.glb', + dimensions: [0.3, 0.8, 0.3], + }, + }) + const nodes = Object.fromEntries( + [level, slab, run, module, chair].map((node) => [node.id, node]), + ) + const notice = cabinetDefinition.placementNotice!(run, { nodes }) + expect(notice?.line).toContain('Opening clearance') + expect( + checkKitchenClearance(nodes, { nodeId: run.id }, { activeLevelId: null }).result.warning, + ).toBe(notice?.line) + expect( + cabinetDefinition.placementNotice!(run, { + nodes, + live: { position: [0, 0, 0], rotation: 0 }, + }), + ).toBeNull() + expect( + cabinetModuleDefinition.placementNotice!(module, { + nodes, + live: { position: [3, 0, 0], rotation: 0 }, + }), + ).toBeNull() + const high = { + ...nodes, + [chair.id]: { ...chair, position: [10, 2, 4.6] as [number, number, number] }, + } + expect(cabinetDefinition.placementNotice!(run, { nodes: high })).toBeNull() + } finally { + restore() + } +}) + +test('headless clearance refuses missing capabilities instead of claiming the scene is clear', () => { + const restore = nodeRegistry._snapshot() + try { + nodeRegistry._reset() + const level = LevelNode.parse({}) + const run = CabinetNode.parse({ parentId: level.id }) + expect(() => + checkKitchenClearance( + { [level.id]: level, [run.id]: run }, + { nodeId: run.id }, + { activeLevelId: null }, + ), + ).toThrow('plugin definitions') + } finally { + restore() + } +}) diff --git a/packages/nodes/src/cabinet/__tests__/placement-alignment.test.ts b/packages/nodes/src/cabinet/__tests__/placement-alignment.test.ts new file mode 100644 index 0000000000..33a8af758d --- /dev/null +++ b/packages/nodes/src/cabinet/__tests__/placement-alignment.test.ts @@ -0,0 +1,50 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + CabinetNode, + collectAlignmentAnchors, + movingAlignmentAnchors, + nodeRegistry, + registerNode, + resolveAlignment, +} from '@pascal-app/core' +import { cabinetDefinition } from '@pascal-app/nodes' + +let restoreRegistry: () => void +beforeEach(() => { + restoreRegistry = nodeRegistry._snapshot() + registerNode(cabinetDefinition) +}) +afterEach(() => restoreRegistry()) + +for (const yaw of [0, Math.PI / 2]) { + test(`cabinet ghost magnetically aligns its bounds at yaw ${yaw}`, () => { + const target = CabinetNode.parse({ position: [2, 0, 3], rotation: yaw }) + const ghost = CabinetNode.parse({ position: [0, 0, 0], rotation: yaw }) + const nodes = { [target.id]: target } + const moving = movingAlignmentAnchors(ghost, nodes, 2.04, 3.03, yaw) + const result = resolveAlignment({ + moving, + candidates: collectAlignmentAnchors(nodes, ghost.id), + threshold: 0.08, + }) + + expect(result.snap).not.toBeNull() + expect(2.04 + result.snap!.dx).toBeCloseTo(2) + expect(3.03 + result.snap!.dz).toBeCloseTo(3) + expect(result.guides).toHaveLength(2) + // Preview resolution never moves the existing scene object. + expect(target.position).toEqual([2, 0, 3]) + }) +} + +test('cabinet ghost is free outside the magnetic threshold', () => { + const target = CabinetNode.parse({ position: [2, 0, 3] }) + const ghost = CabinetNode.parse({}) + const nodes = { [target.id]: target } + const result = resolveAlignment({ + moving: movingAlignmentAnchors(ghost, nodes, 10, 10, 0), + candidates: collectAlignmentAnchors(nodes, ghost.id), + threshold: 0.08, + }) + expect(result.snap).toBeNull() +}) diff --git a/packages/nodes/src/cabinet/__tests__/run-ops.test.ts b/packages/nodes/src/cabinet/__tests__/run-ops.test.ts index 895595ab43..8360601ec8 100644 --- a/packages/nodes/src/cabinet/__tests__/run-ops.test.ts +++ b/packages/nodes/src/cabinet/__tests__/run-ops.test.ts @@ -1,11 +1,20 @@ import { describe, expect, test } from 'bun:test' -import { type AnyNode, type AnyNodeId, type SceneApi, WallNode, ZoneNode } from '@pascal-app/core' +import { + type AnyNode, + type AnyNodeId, + LevelNode, + type SceneApi, + WallNode, + ZoneNode, +} from '@pascal-app/core' +import { alignCabinetRun, cabinetWallFillerPlan, fitCabinetWallFillers } from '../run-finishing' import { runLocalToPlan } from '../run-layout' import { addCabinetModuleSide, addCornerRun, backAlignedRunDepthOverrides, backAlignZ, + cabinetModuleCanEqualizeWidth, cabinetModulesForRun, cornerSourceWidthOverridesForDerivedDepth, previewCornerAdditionLayout, @@ -2749,3 +2758,62 @@ describe('addCornerRun', () => { expect(bridgeLeftEdge).toBeCloseTo(wallTopRightEdge) }) }) + +test('wall fillers close small gaps without shifting cabinets and remain idempotent', () => { + const run = CabinetNode.parse({ parentId: 'level_finish', depth: 0.6 }) + const module = CabinetModuleNode.parse({ + parentId: run.id, + width: 0.6, + depth: 0.6, + position: [0, 0.1, 0], + }) + run.children = [module.id] + const wall = WallNode.parse({ + parentId: 'level_finish', + start: [0.5, -1], + end: [0.5, 1], + thickness: 0.2, + }) + const scene = sceneApiFixture([LevelNode.parse({ id: 'level_finish' }), run, module, wall]) + expect(cabinetWallFillerPlan(run, [module], scene.nodes())).toHaveLength(1) + fitCabinetWallFillers(run, scene) + const live = scene.get(run.id)! + const modules = cabinetModulesForRun(live, scene.nodes()) + const filler = modules.find((entry) => entry.moduleKind === 'wall-filler')! + expect(filler.width).toBeCloseTo(0.1) + expect(cabinetModuleCanEqualizeWidth(filler, live)).toBe(false) + expect(filler.position[0]).toBeCloseTo(0.35) + expect(scene.get(module.id)!.position).toEqual(module.position) + fitCabinetWallFillers(live, scene) + expect(cabinetModulesForRun(scene.get(run.id)!, scene.nodes())).toHaveLength(2) +}) + +test('alignment matches base heights and preserves tall appliance stacks', () => { + const run = CabinetNode.parse({ + carcassHeight: 0.72, + depth: 0.6, + frontGap: 0.003, + showPlinth: true, + plinthHeight: 0.1, + }) + const base = CabinetModuleNode.parse({ + parentId: run.id, + carcassHeight: 0.8, + depth: 0.5, + position: [-0.3, 0.2, 0.1], + }) + const tall = CabinetModuleNode.parse({ + parentId: run.id, + cabinetType: 'tall', + carcassHeight: 2.1, + position: [0.3, 0.2, 0], + stack: [{ id: 'fridge', type: 'fridge-single', height: 2.1 }], + }) + run.children = [base.id, tall.id] + const scene = sceneApiFixture([run, base, tall]) + alignCabinetRun(run, scene) + expect(scene.get(base.id)!.carcassHeight).toBe(0.72) + expect(scene.get(base.id)!.position).toEqual([-0.3, 0.1, -0.04999999999999999]) + expect(scene.get(tall.id)!.carcassHeight).toBe(2.1) + expect(scene.get(tall.id)!.stack).toEqual(tall.stack) +}) diff --git a/packages/nodes/src/cabinet/__tests__/run-surface-depth.test.ts b/packages/nodes/src/cabinet/__tests__/run-surface-depth.test.ts index 8543768ca6..2a1d0e1b5f 100644 --- a/packages/nodes/src/cabinet/__tests__/run-surface-depth.test.ts +++ b/packages/nodes/src/cabinet/__tests__/run-surface-depth.test.ts @@ -59,3 +59,42 @@ test('equal-depth adjacent cabinets keep one continuous surface span', () => { expect(getRunSpans([left, right])).toHaveLength(1) }) + +for (const side of ['left', 'right'] as const) { + test(`inside ${side} corner has neither overhang nor finished end`, () => { + const run = CabinetNode.parse({ + metadata: { cabinetCornerDerivedRun: { role: 'base-leg', side } }, + }) + const module = CabinetModuleNode.parse({ parentId: run.id }) + const context: GeometryContext = { + children: [module], + siblings: [], + parent: null, + resolve: () => undefined, + } + const [end] = getRunSpanEnds(run, context, getRunSpans([module])) + expect(side === 'right' ? end!.exposedLeft : end!.exposedRight).toBe(false) + expect(side === 'right' ? end!.leftOverhang : end!.rightOverhang).toBe(0) + expect(side === 'right' ? end!.exposedRight : end!.exposedLeft).toBe(true) + }) +} + +test('wall filler terminates the slab flush without an end panel inside the wall', () => { + const run = CabinetNode.parse({}) + const module = CabinetModuleNode.parse({ parentId: run.id, width: 0.6 }) + const filler = CabinetModuleNode.parse({ + parentId: run.id, + moduleKind: 'wall-filler', + width: 0.1, + position: [0.35, 0, 0], + }) + const context: GeometryContext = { + children: [module, filler], + siblings: [], + parent: null, + resolve: () => undefined, + } + const [end] = getRunSpanEnds(run, context, getRunSpans([module, filler])) + expect(end!.rightOverhang).toBe(0) + expect(end!.exposedRight).toBe(false) +}) diff --git a/packages/nodes/src/cabinet/compartment-card.tsx b/packages/nodes/src/cabinet/compartment-card.tsx index 8843b4f2d4..fcf1f22f31 100644 --- a/packages/nodes/src/cabinet/compartment-card.tsx +++ b/packages/nodes/src/cabinet/compartment-card.tsx @@ -162,7 +162,7 @@ function CompartmentTypeControl({ return (
+ + {action !== 'replace' && ( +
+ {(['left', 'right'] as const).map((side) => ( + + ))} +
+ )} + { + setPresetId(id) + setError(null) + }} + /> + {preset && ( +
+

+ {preset.label} · {format(patch?.width ?? 0)} +

+ {fits && planned ? ( + <> +
+ {[...planned] + .sort((a, b) => a.position[0] - b.position[0]) + .map((entry) => ( +
existing.id === entry.id)?.name ?? 'Cabinet')}: ${format(entry.width)}`} + className={`min-w-0 rounded border ${entry.id === changedId ? 'border-primary bg-primary/30' : 'border-border bg-muted'}`} + /> + ))} +
+

+ {action === 'replace' + ? 'Replaces only the selected item.' + : `Inserts on the ${action} of the selected item.`} +

+ {changes.map((entry) => { + const before = modules.find((existing) => existing.id === entry.id)! + return ( +

+ {before.name || 'Cabinet'}:{' '} + {Math.abs(before.width - entry.width) > 0.0001 + ? `${format(before.width)} → ${format(entry.width)}` + : `moves ${format(Math.abs(before.position[0] - entry.position[0]))}`} +

+ ) + })} + {action === 'replace' && + patch?.cabinetType === 'tall' && + node.children.length > 0 && ( +

+ An upper cabinet attached to this item will be removed to make room. +

+ )} + + + ) : ( +

+ This {format(patch?.width ?? 0)} item cannot fit within the current run and its + wall or corner limits. Move an end cabinet or free space, then try again. +

+ )} +
+ )} + {error && ( +

+ {error} +

+ )} +
+ )} + + ) +} diff --git a/packages/nodes/src/cabinet/kitchen-placement.ts b/packages/nodes/src/cabinet/kitchen-placement.ts new file mode 100644 index 0000000000..6c93366c32 --- /dev/null +++ b/packages/nodes/src/cabinet/kitchen-placement.ts @@ -0,0 +1,17 @@ +import { emitter } from '@pascal-app/core' +import { useEditor } from '@pascal-app/editor' +import { useViewer } from '@pascal-app/viewer' +import useCabinetPlacementType from './placement-type' +import { type CabinetPresetId, cabinetPresetById } from './presets' + +export function beginKitchenPlacement(id: CabinetPresetId) { + emitter.emit('tool:cancel') + const editor = useEditor.getState() + useCabinetPlacementType.getState().setType('cabinet') + editor.setToolDefaults('cabinet', { ...cabinetPresetById(id).createPatch(), kitchenPreset: id }) + editor.setContinuation('cabinet', 'single') + useViewer.getState().setSelection({ selectedIds: [], zoneId: null }) + editor.setPhase('building') + editor.setCatalogCategory(null) + editor.armToolMode({ mode: 'build', tool: 'cabinet' }) +} diff --git a/packages/nodes/src/cabinet/neighbor-placement.ts b/packages/nodes/src/cabinet/neighbor-placement.ts new file mode 100644 index 0000000000..ccb98dd1e4 --- /dev/null +++ b/packages/nodes/src/cabinet/neighbor-placement.ts @@ -0,0 +1,78 @@ +import type { AnyNode, AnyNodeId, CabinetModuleNode, CabinetNode } from '@pascal-app/core' +import { + moduleMaxX, + moduleMinX, + planRunModuleInsertion, + planToRunLocal, + runWallConstraints, + sortRunModules, +} from './run-layout' +import { cabinetModulesForRun, cornerPinnedEndsForRun } from './run-ops' + +/** Attach at a run's exposed ends; interior insertion keeps its existing wall planner. */ +export function resolveCabinetNeighborPlacement({ + nodes, + levelId, + position, + module, + wallTier, + threshold = 0.25, +}: { + nodes: Record + levelId: string + position: [number, number, number] + module: CabinetModuleNode + wallTier: boolean + threshold?: number +}) { + let best: { + distance: number + run: CabinetNode + neighbor: CabinetModuleNode + side: 'left' | 'right' + x: number + } | null = null + for (const candidate of Object.values(nodes)) { + if ( + candidate.type !== 'cabinet' || + candidate.parentId !== levelId || + candidate.visible === false || + (candidate.runTier === 'wall') !== wallTier + ) + continue + const modules = sortRunModules(cabinetModulesForRun(candidate, nodes)) + if (!modules.length) continue + const local = planToRunLocal(candidate, position[0], position[1], position[2]) + const pinned = cornerPinnedEndsForRun(modules) + for (const side of ['left', 'right'] as const) { + if (pinned[side]) continue + const neighbor = side === 'left' ? modules[0]! : modules[modules.length - 1]! + if (neighbor.moduleKind !== 'standard') continue + const x = + side === 'left' + ? moduleMinX(neighbor) - module.width / 2 + : moduleMaxX(neighbor) + module.width / 2 + const distance = Math.hypot(local[0] - x, local[2] - neighbor.position[2]) + if (distance <= threshold && (!best || distance < best.distance)) + best = { distance, run: candidate, neighbor, side, x } + } + } + if (!best) return null + const { run, neighbor, side, x } = best + const modules = cabinetModulesForRun(run, nodes) + const result = planRunModuleInsertion({ + modules, + insertion: { + id: module.id, + width: module.width, + position: [x, neighbor.position[1], neighbor.position[2]], + }, + wallConstraints: runWallConstraints(run, modules, nodes, { widthGrowth: module.width }), + fillerIds: new Set( + modules.filter((entry) => entry.moduleKind === 'corner-filler').map((entry) => entry.id), + ), + preserveEnds: cornerPinnedEndsForRun(modules), + anchorInsertionSide: side === 'left' ? 'right' : 'left', + }) + return { run, side, depth: neighbor.depth, result } +} diff --git a/packages/nodes/src/cabinet/opening-clearance.ts b/packages/nodes/src/cabinet/opening-clearance.ts new file mode 100644 index 0000000000..f548e764fc --- /dev/null +++ b/packages/nodes/src/cabinet/opening-clearance.ts @@ -0,0 +1,209 @@ +import { + type AnyNode, + type AnyNodeId, + type CabinetModuleNode, + floorPlacedCollides, + getFloorPlacedFootprints, + getWallBodyLine, + nodeRegistry, + resolveLevelId, +} from '@pascal-app/core' +import { type Frame, nodeLevelFrame, transformPoint } from '@pascal-app/core/procedural-items' +import { compartmentDoorType, normalizeCabinetStack } from './stack' + +/** Conservative opening envelopes: warnings, not a collision veto. */ +export function cabinetOpeningFootprints( + node: CabinetModuleNode, + position: [number, number, number], + yaw: number, +) { + if (node.moduleKind !== 'standard') return [] + const plinth = node.showPlinth ? node.plinthHeight : 0 + return normalizeCabinetStack(node).flatMap(({ compartment, y0, height }) => { + let reach = 0 + switch (compartment.type) { + case 'door': + reach = + node.width / + (['double', 'glass'].includes(compartmentDoorType(compartment, node.width)) ? 2 : 1) + break + case 'sink': + reach = node.width / 2 + break + case 'drawer': + reach = Math.min(node.depth * 0.9, 0.35) + break + case 'pull-out-pantry': + reach = node.depth * 0.9 + break + case 'fridge-double': + reach = node.width / 2 + break + case 'fridge-single': + case 'fridge-top-freezer': + case 'fridge-bottom-freezer': + case 'microwave': + reach = node.width + break + case 'oven': + case 'dishwasher': + reach = height + break + default: + return [] + } + const z = node.depth / 2 + node.frontThickness + reach / 2 + 0.005 + return [ + { + position: [ + position[0] + Math.sin(yaw) * z, + position[1] + plinth + y0, + position[2] + Math.cos(yaw) * z, + ] as [number, number, number], + dimensions: [Math.max(0.01, node.width - 0.01), height, reach] as [number, number, number], + rotation: [0, yaw, 0] as [number, number, number], + }, + ] + }) +} + +export type OpeningFootprint = ReturnType[number] + +export function openingFootprintsOverlap(a: OpeningFootprint, b: OpeningFootprint) { + if ( + a.position[1] + a.dimensions[1] <= b.position[1] + 0.001 || + b.position[1] + b.dimensions[1] <= a.position[1] + 0.001 + ) + return false + const axes = (yaw: number) => + [ + [Math.cos(yaw), -Math.sin(yaw)], + [Math.sin(yaw), Math.cos(yaw)], + ] as const + const aa = axes(a.rotation[1]), + bb = axes(b.rotation[1]) + const delta = [b.position[0] - a.position[0], b.position[2] - a.position[2]] + return [...aa, ...bb].every((axis) => { + const radius = (fp: OpeningFootprint, basis: ReturnType) => + (Math.abs(axis[0] * basis[0][0] + axis[1] * basis[0][1]) * fp.dimensions[0]) / 2 + + (Math.abs(axis[0] * basis[1][0] + axis[1] * basis[1][1]) * fp.dimensions[2]) / 2 + return ( + Math.abs(delta[0]! * axis[0] + delta[1]! * axis[1]) < radius(a, aa) + radius(b, bb) - 0.001 + ) + }) +} + +/** Something a cabinet's openings can run into, with the ids of it and its ancestors. */ +export type ClearanceObstacle = { + id: string + chain: ReadonlySet + footprints: OpeningFootprint[] +} + +/** + * What openings on a level can run into: its visible straight walls and colliding floor-placed + * objects. One pass over the scene, shared by every module a check reads. + */ +export function cabinetOpeningObstacles( + levelId: string, + nodes: Readonly>, +): ClearanceObstacle[] { + const scene = nodes as Record + const cache = new Map() + const obstacles: ClearanceObstacle[] = [] + for (const candidate of Object.values(scene)) { + const straightWall = candidate.type === 'wall' && !candidate.curveOffset + const capability = straightWall + ? undefined + : nodeRegistry.get(candidate.type)?.capabilities?.floorPlaced + if ( + !straightWall && + !( + capability && + floorPlacedCollides(capability, candidate) && + (!capability.applies || capability.applies(candidate)) + ) + ) + continue + const chain = new Set() + let current: AnyNode | undefined = candidate + let hidden = false + while (current && !chain.has(current.id)) { + if (current.visible === false) { + hidden = true + break + } + chain.add(current.id) + current = current.parentId ? scene[current.parentId as AnyNodeId] : undefined + } + if (hidden || resolveLevelId(candidate, scene) !== levelId) continue + if (candidate.type === 'wall') { + const body = getWallBodyLine({ ...candidate, thickness: candidate.thickness ?? 0.2 }) + const dx = body.end.x - body.start.x, + dz = body.end.y - body.start.y + const level = scene[levelId as AnyNodeId] + obstacles.push({ + id: candidate.id, + chain, + footprints: [ + { + position: [ + (body.start.x + body.end.x) / 2, + nodeLevelFrame(candidate.id, scene, new Set(), { cache }).position[1], + (body.start.y + body.end.y) / 2, + ], + dimensions: [ + Math.hypot(dx, dz), + candidate.height ?? (level?.type === 'level' ? (level.height ?? 3) : 3), + candidate.thickness ?? 0.2, + ], + rotation: [0, -Math.atan2(dz, dx), 0], + }, + ], + }) + continue + } + const pose = nodeLevelFrame(candidate.id, scene, new Set(), { cache }) + const yaw = Math.atan2(pose.axes[2][0], pose.axes[2][2]) + // Composite footprints include the node's pose. Resolve them at its origin before + // composing the hosting frame, so neither translation nor yaw is applied twice. + const local = { + ...candidate, + position: [0, 0, 0], + rotation: typeof ('rotation' in candidate && candidate.rotation) === 'number' ? 0 : [0, 0, 0], + } as AnyNode + obstacles.push({ + id: candidate.id, + chain, + footprints: getFloorPlacedFootprints(capability!, local, { nodes: scene }).map((fp) => ({ + position: transformPoint(pose, fp.position ?? [0, 0, 0]), + dimensions: fp.dimensions, + rotation: [0, yaw + (fp.rotation?.[1] ?? 0), 0] as [number, number, number], + })), + }) + } + return obstacles +} + +export function cabinetOpeningConflicts( + node: CabinetModuleNode, + position: [number, number, number], + yaw: number, + levelId: string, + nodes: Readonly>, + ignoreIds: readonly string[] = [], + obstacles: () => readonly ClearanceObstacle[] = () => cabinetOpeningObstacles(levelId, nodes), +) { + const openings = cabinetOpeningFootprints(node, position, yaw) + if (!openings.length) return [] + const ignored = [...ignoreIds, node.id] + return obstacles() + .filter( + (obstacle) => + !ignored.some((id) => obstacle.chain.has(id)) && + obstacle.footprints.some((footprint) => + openings.some((opening) => openingFootprintsOverlap(opening, footprint)), + ), + ) + .map((obstacle) => obstacle.id) +} diff --git a/packages/nodes/src/cabinet/panel-visibility.ts b/packages/nodes/src/cabinet/panel-visibility.ts index 767e4a1d39..be638acb66 100644 --- a/packages/nodes/src/cabinet/panel-visibility.ts +++ b/packages/nodes/src/cabinet/panel-visibility.ts @@ -17,7 +17,7 @@ const FIXED_WIDTH_APPLIANCE_TYPES: ReadonlySet = new ]) export function cabinetModuleSupportsPresets(module: CabinetModuleNode) { - return module.moduleKind !== 'corner-filler' + return module.moduleKind === 'standard' } export function cabinetModuleUsesFixedApplianceWidth(module: CabinetModuleNode) { diff --git a/packages/nodes/src/cabinet/panel.tsx b/packages/nodes/src/cabinet/panel.tsx index 7032682642..5595bdb05a 100644 --- a/packages/nodes/src/cabinet/panel.tsx +++ b/packages/nodes/src/cabinet/panel.tsx @@ -13,25 +13,30 @@ import { PanelWrapper, SegmentedControl, SliderControl, + usePlacementNotice, } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' import { AlertTriangle, Pause, Play, Plus } from 'lucide-react' import { useCallback, useEffect, useState } from 'react' import { useShallow } from 'zustand/react/shallow' import { CompartmentCard } from './compartment-card' +import { CabinetEssentialControls } from './essential-controls' import { animateCabinetOperationState, isCabinetAnimationRunning, onCabinetAnimationChange, stopCabinetAnimation, } from './interaction' +import { kitchenPresetForModule } from './kitchen-catalog' +import { KitchenCollection } from './kitchen-collection' +import { KitchenModuleActions } from './kitchen-module-actions' import { cabinetModulePanelContext } from './panel-context' import { cabinetModuleSupportsPresets, cabinetModuleSupportsTopFinish, cabinetModuleUsesFixedApplianceWidth, } from './panel-visibility' -import { CABINET_PRESETS, type CabinetPresetId } from './presets' +import { CABINET_PRESETS, type CabinetPresetId, cabinetPresetById } from './presets' import { CABINET_REVEAL_GAPS, type CabinetRevealGapId, @@ -127,13 +132,12 @@ const TOP_FINISH_OPTIONS = [ const EMPTY_MODULES: CabinetModuleNodeType[] = [] const EMPTY_MODULE_IDS: AnyNodeId[] = [] -const PRESET_BUTTON_CLASS = - 'flex h-9 items-center justify-center rounded-md border border-border/40 bg-black/3 dark:bg-[#252527] px-3 py-2 text-center text-xs font-medium text-foreground transition-colors hover:border-border/70 hover:bg-black/6 dark:hover:bg-[#303033]' const REFLOW_REJECTED_MESSAGE = 'No space in this run. No base cabinet can shrink enough to fit this item.' export default function CabinetPanel() { const selectedId = useViewer((s) => s.selection.selectedIds[0]) + const placementNotice = usePlacementNotice(selectedId) const setSelection = useViewer((s) => s.setSelection) const [isAnimating, setIsAnimating] = useState(false) const [reflowNotice, setReflowNotice] = useState<{ message: string } | null>(null) @@ -351,10 +355,10 @@ export default function CabinetPanel() { // parent-frame routing keeps clicks on child modules targeting the run while // it stays the single selected node. const backToRun = useCallback(() => { - if (node?.type === 'cabinet-module' && node.parentId) { - setSelection({ selectedIds: [node.parentId] }) + if (parentRun) { + setSelection({ selectedIds: [parentRun.id] }) } - }, [node, setSelection]) + }, [parentRun, setSelection]) // Animation lives in ./interaction.ts, shared with the registry E-key // action; the panel only mirrors its running state for the Play button. @@ -597,33 +601,65 @@ export default function CabinetPanel() { return } + if (node.type === 'cabinet-module' && node.moduleKind === 'wall-filler') { + return ( + + {placementNotice && ( +

+ {placementNotice.line} +

+ )} + +

+ Solid matching front between the cabinet and wall. Countertop and toe-kick continue + across this filler. +

+ updateNode({ width })} + /> + updateNode({ carcassHeight })} + /> +
+
+ ) + } + return ( - {node.type === 'cabinet-module' && - parentRun?.type === 'cabinet' && - cabinetModuleSupportsPresets(node) && ( - -
- {CABINET_PRESETS.map((preset) => ( - - ))} -
-
- )} - + {placementNotice && ( +

+ {placementNotice.line} +

+ )} {node.type === 'cabinet-module' && !isHoodOnlyNode && (
@@ -693,7 +729,7 @@ export default function CabinetPanel() { value={node.depth} /> - {node.type === 'cabinet-module' && parentRun?.type === 'cabinet' && !isHoodOnlyNode && ( - -
- { - if (value === 'tall') { - switchToTall() - return - } - switchToBase() - }} - options={CABINET_TIER_OPTIONS.map((option) => ({ - value: option.value, - label: option.label, - }))} - value={resolveCabinetType(node, parentRun)} - /> - {resolveCabinetType(node, parentRun) === 'base' && - (hasWallCabinet ? ( - - ) : ( - <> - - - - ))} -
-
- )} - - {canAddTopFinish && ( - -
-
-
- Finish -
- - updateNode({ - topFinish: value as CabinetModuleNodeType['topFinish'], - ...(value !== 'none' && node.topFinish === 'none' - ? { topFinishDepth: node.depth } - : {}), - }) - } - options={TOP_FINISH_OPTIONS.map((option) => ({ - label: option.label, - value: option.value, - }))} - value={node.topFinish ?? 'none'} - /> -
- {node.topFinish !== 'none' && ( - <> - - updateNode({ - topFinishHeight: cabinetCeilingGap( - node, - useScene.getState().nodes as Record, - ), - }) - } - /> - updateNode({ topFinishHeight: value })} - precision={2} - step={0.01} - unit="m" - value={node.topFinishHeight} - /> - updateNode({ topFinishDepth: value })} - precision={2} - step={0.01} - unit="m" - value={node.topFinishDepth} - /> - - )} - {ceilingOverflow > 1e-4 && ( -
- - - Finished height extends {(ceilingOverflow * 1000).toFixed(0)} mm above the - ceiling. - -
- )} -
-
- )} + {planningReport && (planningReport.errors.length > 0 || planningReport.warnings.length > 0) && ( @@ -841,98 +778,6 @@ export default function CabinetPanel() { )} - {!isHoodOnlyNode && ( - -
-
- { - if (isAnimating) stopAnimation() - updateNode({ operationState: value / 100 }) - }} - step={1} - unit="%" - value={Math.round((node.operationState ?? 0) * 100)} - /> -
- -
-
- )} - - - {reflowNotice ? ( -

- {reflowNotice.message} -

- ) : null} -
- {rows.map(({ compartment, index }, displayIndex) => ( - moveCompartment(index, delta)} - onRemove={() => removeAt(index)} - onReplace={(next) => replaceAt(index, next)} - onResizeHeight={(height) => resizeAt(index, height)} - resolvedHeight={ - rowHeights.get(index) ?? node.carcassHeight / Math.max(stack.length, 1) - } - total={rows.length} - width={node.width} - /> - ))} -
-
- } - label="Add compartment" - onClick={addCompartment} - /> -
-
- {!isHoodOnlyNode && ( <> {isFridgeModule && ( @@ -959,7 +804,7 @@ export default function CabinetPanel() {
)} - +
@@ -976,43 +821,6 @@ export default function CabinetPanel() { value={node.frontStyle ?? 'slab'} />
-
-
- Mounting -
- - updateNode({ frontOverlay: value as CabinetNodeType['frontOverlay'] }) - } - options={FRONT_OVERLAY_OPTIONS.map((option) => ({ - value: option.value, - label: option.label, - }))} - value={node.frontOverlay ?? 'full'} - /> -
-
-
- Reveal gap -
- - updateNode({ - frontGap: cabinetRevealGapById(value as CabinetRevealGapId).value, - }) - } - options={CABINET_REVEAL_GAPS.map((gap) => ({ - value: gap.id, - label: gap.label, - }))} - value={ - cabinetRevealGapId(node.frontGap) === 'custom' - ? '3' - : cabinetRevealGapId(node.frontGap) - } - /> -
@@ -1054,6 +862,272 @@ export default function CabinetPanel() { )} + {node.type === 'cabinet-module' && + parentRun?.type === 'cabinet' && + cabinetModuleSupportsPresets(node) && ( + + +

+ Shared countertop, plinth, and finishes +

+ {!parentIsModule && parentRun.runTier !== 'wall' && ( + + )} + {(parentIsModule || parentRun.runTier === 'wall') && ( +
+ Replace with… + +
+ )} +
+ )} + +
+ + Advanced + +

+ Cabinet construction, compartments, and opening preview. +

+ {!isHoodOnlyNode && ( + +
+
+ Mounting +
+ + updateNode({ frontOverlay: value as CabinetNodeType['frontOverlay'] }) + } + options={FRONT_OVERLAY_OPTIONS.map((option) => ({ + value: option.value, + label: option.label, + }))} + value={node.frontOverlay ?? 'full'} + /> +
+
+
+ Reveal gap +
+ + updateNode({ + frontGap: cabinetRevealGapById(value as CabinetRevealGapId).value, + }) + } + options={CABINET_REVEAL_GAPS.map((gap) => ({ + value: gap.id, + label: gap.label, + }))} + value={ + cabinetRevealGapId(node.frontGap) === 'custom' + ? '3' + : cabinetRevealGapId(node.frontGap) + } + /> +
+
+ )} + {node.type === 'cabinet-module' && parentRun?.type === 'cabinet' && !isHoodOnlyNode && ( + +
+ { + if (value === 'tall') { + switchToTall() + return + } + switchToBase() + }} + options={CABINET_TIER_OPTIONS.map((option) => ({ + value: option.value, + label: option.label, + }))} + value={resolveCabinetType(node, parentRun)} + /> + {resolveCabinetType(node, parentRun) === 'base' && + (hasWallCabinet ? ( + + ) : ( + <> + + + + ))} +
+
+ )} + + {canAddTopFinish && ( + +
+
+
+ Finish +
+ + updateNode({ + topFinish: value as CabinetModuleNodeType['topFinish'], + ...(value !== 'none' && node.topFinish === 'none' + ? { topFinishDepth: node.depth } + : {}), + }) + } + options={TOP_FINISH_OPTIONS.map((option) => ({ + label: option.label, + value: option.value, + }))} + value={node.topFinish ?? 'none'} + /> +
+ {node.topFinish !== 'none' && ( + <> + + updateNode({ + topFinishHeight: cabinetCeilingGap( + node, + useScene.getState().nodes as Record, + ), + }) + } + /> + updateNode({ topFinishHeight: value })} + precision={2} + step={0.01} + unit="m" + value={node.topFinishHeight} + /> + updateNode({ topFinishDepth: value })} + precision={2} + step={0.01} + unit="m" + value={node.topFinishDepth} + /> + + )} + {ceilingOverflow > 1e-4 && ( +
+ + + Finished height extends {(ceilingOverflow * 1000).toFixed(0)} mm above the + ceiling. + +
+ )} +
+
+ )} + + {!isHoodOnlyNode && ( + +
+
+ { + if (isAnimating) stopAnimation() + updateNode({ operationState: value / 100 }) + }} + step={1} + unit="%" + value={Math.round((node.operationState ?? 0) * 100)} + /> +
+ +
+
+ )} + + + {reflowNotice ? ( +

+ {reflowNotice.message} +

+ ) : null} +
+ {rows.map(({ compartment, index }, displayIndex) => ( + moveCompartment(index, delta)} + onRemove={() => removeAt(index)} + onReplace={(next) => replaceAt(index, next)} + onResizeHeight={(height) => resizeAt(index, height)} + resolvedHeight={ + rowHeights.get(index) ?? node.carcassHeight / Math.max(stack.length, 1) + } + total={rows.length} + width={node.width} + /> + ))} +
+
+ } + label="Add compartment" + onClick={addCompartment} + /> +
+
+
) } diff --git a/packages/nodes/src/cabinet/placement-notice.ts b/packages/nodes/src/cabinet/placement-notice.ts new file mode 100644 index 0000000000..6bbc2bf50b --- /dev/null +++ b/packages/nodes/src/cabinet/placement-notice.ts @@ -0,0 +1,55 @@ +import { + type AnyNode, + type CabinetModuleNode, + type CabinetNode, + type LiveTransformLike, + type PlacementNotice, + resolveLevelId, +} from '@pascal-app/core' +import { type Frame, nodeLevelFrame } from '@pascal-app/core/procedural-items' +import { + type ClearanceObstacle, + cabinetOpeningConflicts, + cabinetOpeningObstacles, +} from './opening-clearance' + +export function cabinetPlacementNotice( + node: CabinetNode | CabinetModuleNode, + { nodes, live }: { nodes: Readonly>; live?: LiveTransformLike }, +): PlacementNotice | null { + const effective = live ? { ...node, position: live.position, rotation: live.rotation } : node + const scene = live || nodes[node.id] !== node ? { ...nodes, [node.id]: effective } : nodes + const levelId = resolveLevelId(effective, scene) + if (!levelId) return null + const cache = new Map() + const modules: CabinetModuleNode[] = [] + const visit = (entry: CabinetNode | CabinetModuleNode, seen = new Set()) => { + if (seen.has(entry.id)) return + seen.add(entry.id) + if (entry.type === 'cabinet-module') modules.push(entry) + for (const id of entry.children) { + const child = scene[id] + if (child?.type === 'cabinet' || child?.type === 'cabinet-module') visit(child, seen) + } + } + visit(effective) + // Read once, when a module has an opening to check. + let obstacles: ClearanceObstacle[] | undefined + const levelObstacles = () => (obstacles ??= cabinetOpeningObstacles(levelId, scene)) + for (const module of modules) { + const pose = nodeLevelFrame(module.id, scene, new Set(), { cache }) + if ( + cabinetOpeningConflicts( + module, + pose.position, + Math.atan2(pose.axes[2][0], pose.axes[2][2]), + levelId, + scene, + [], + levelObstacles, + ).length + ) + return { line: 'Opening clearance: nearby objects may block a door or drawer' } + } + return null +} diff --git a/packages/nodes/src/cabinet/placement-status.ts b/packages/nodes/src/cabinet/placement-status.ts index cd2db28f7b..c9cc416e6b 100644 --- a/packages/nodes/src/cabinet/placement-status.ts +++ b/packages/nodes/src/cabinet/placement-status.ts @@ -2,12 +2,16 @@ import { create } from 'zustand' type CabinetPlacementStatusState = { blocked: boolean + target: string | null + setTarget(target: string | null): void setBlocked(blocked: boolean): void } const useCabinetPlacementStatus = create((set) => ({ blocked: false, - setBlocked: (blocked) => set({ blocked }), + target: null, + setTarget: (target) => set({ target }), + setBlocked: (blocked) => set({ blocked, target: null }), })) export default useCabinetPlacementStatus diff --git a/packages/nodes/src/cabinet/presets.ts b/packages/nodes/src/cabinet/presets.ts index 3604c8fd22..955c9e3910 100644 --- a/packages/nodes/src/cabinet/presets.ts +++ b/packages/nodes/src/cabinet/presets.ts @@ -23,6 +23,10 @@ export type CabinetPresetId = | 'tall-pantry' | 'oven-tower' | 'fridge-single' + | 'wall-cabinet' + +/** Where a wall cabinet placed on its own hangs: its bottom, above the floor. */ +export const WALL_CABINET_ELEVATION = 1.5 export type CabinetPreset = { id: CabinetPresetId @@ -47,9 +51,25 @@ const runCarcassHeight = (run?: CabinetNode) => run?.carcassHeight ?? CABINET_METRIC_DEFAULTS.carcassHeight export const CABINET_PRESETS: CabinetPreset[] = [ + { + id: 'wall-cabinet', + label: 'Wall cabinet', + createPatch: () => ({ + cabinetType: 'base', + name: 'Wall Cabinet', + width: 0.6, + depth: 0.35, + carcassHeight: 0.762, + showPlinth: false, + plinthHeight: 0, + withCountertop: false, + countertopThickness: 0, + stack: [{ ...newCabinetCompartment('door'), doorType: 'double', shelfCount: 2 }], + }), + }, { id: 'base-door', - label: 'Base', + label: 'Base cabinet', createPatch: (run) => ({ ...baseShared(run), name: 'Base Cabinet', @@ -65,7 +85,7 @@ export const CABINET_PRESETS: CabinetPreset[] = [ }, { id: 'drawer-base', - label: 'Drawer Base', + label: 'Drawer cabinet', createPatch: (run) => ({ ...baseShared(run), name: 'Drawer Base', @@ -91,7 +111,7 @@ export const CABINET_PRESETS: CabinetPreset[] = [ }, { id: 'cooktop-gas', - label: 'Gas Hob', + label: 'Gas cooktop', createPatch: (run) => ({ ...baseShared(run), name: 'Gas Hob Base', @@ -104,7 +124,7 @@ export const CABINET_PRESETS: CabinetPreset[] = [ }, { id: 'cooktop-induction', - label: 'Induction', + label: 'Induction cooktop', createPatch: (run) => ({ ...baseShared(run), name: 'Induction Base', @@ -117,7 +137,7 @@ export const CABINET_PRESETS: CabinetPreset[] = [ }, { id: 'sink-base', - label: 'Sink', + label: 'Sink cabinet', createPatch: (run) => ({ ...baseShared(run), name: 'Sink Base', @@ -177,7 +197,7 @@ export const CABINET_PRESETS: CabinetPreset[] = [ }, { id: 'fridge-single', - label: 'Single Fridge', + label: 'Fridge', createPatch: (run) => ({ cabinetType: 'tall', name: 'Single Door Refrigerator', @@ -199,5 +219,8 @@ export const CABINET_PRESETS: CabinetPreset[] = [ ] export function cabinetPresetById(id: CabinetPresetId): CabinetPreset { - return CABINET_PRESETS.find((preset) => preset.id === id) ?? CABINET_PRESETS[0]! + return ( + CABINET_PRESETS.find((preset) => preset.id === id) ?? + CABINET_PRESETS.find((preset) => preset.id === 'base-door')! + ) } diff --git a/packages/nodes/src/cabinet/run-finishing.ts b/packages/nodes/src/cabinet/run-finishing.ts new file mode 100644 index 0000000000..f3ba6b8f06 --- /dev/null +++ b/packages/nodes/src/cabinet/run-finishing.ts @@ -0,0 +1,121 @@ +import type { AnyNode, AnyNodeId, CabinetModuleNode, CabinetNode, SceneApi } from '@pascal-app/core' +import { applyCabinetModuleInsertion } from './insertion' +import { moduleMaxX, moduleMinX, runWallConstraints, sortRunModules } from './run-layout' +import { + backAlignZ, + cabinetModulesForRun, + cornerPinnedEndsForRun, + resolveCabinetType, + runModuleBaseY, + syncCornerRunsFromRunSources, + wallChildOf, +} from './run-ops' +import { CabinetModuleNode as ModuleSchema } from './schema' +import { minCabinetCarcassHeightForStack } from './stack' + +export function cabinetWallFillerPlan( + run: CabinetNode, + modules: readonly CabinetModuleNode[], + nodes: Record, +) { + const sorted = sortRunModules(modules) + const constraints = runWallConstraints(run, modules, nodes) + const pinned = cornerPinnedEndsForRun(modules) + return (['left', 'right'] as const).flatMap((side) => { + const edge = side === 'left' ? sorted[0] : sorted.at(-1) + const wall = constraints[side] + if ( + pinned[side] || + edge?.moduleKind !== 'standard' || + !wall.constrained || + wall.slack < 0.05 || + wall.slack > 0.15 + ) + return [] + return [{ side, width: wall.slack, edge }] + }) +} + +export function fitCabinetWallFillers(run: CabinetNode, scene: SceneApi) { + const nodes = scene.nodes() + const modules = cabinetModulesForRun(run, nodes) + const plan = cabinetWallFillerPlan(run, modules, nodes as Record) + for (const { side, width, edge } of plan) { + const liveRun = scene.get(run.id)! + const current = cabinetModulesForRun(liveRun, scene.nodes()) + const x = side === 'left' ? moduleMinX(edge) - width / 2 : moduleMaxX(edge) + width / 2 + const filler = ModuleSchema.parse({ + ...edge, + id: undefined, + children: [], + name: 'Wall filler', + moduleKind: 'wall-filler', + width, + stack: [], + handleStyle: 'none', + topFinish: 'none', + metadata: {}, + position: [x, edge.position[1], edge.position[2]], + }) + applyCabinetModuleInsertion({ + run: liveRun, + sceneApi: scene, + module: filler, + plan: { + modules: current.map((module) => ({ + id: module.id, + position: module.position, + width: module.width, + })), + inserted: { position: filler.position, width }, + }, + }) + } + scene.markDirty(run.id) +} + +export function alignCabinetRun(run: CabinetNode, scene: SceneApi) { + const modules = cabinetModulesForRun(run, scene.nodes()) + const hasTall = modules.some((module) => resolveCabinetType(module, run) === 'tall') + const baseHeight = hasTall + ? Math.min( + run.carcassHeight, + ...modules + .filter((module) => resolveCabinetType(module, run) !== 'tall') + .map((module) => module.carcassHeight), + ) + : run.carcassHeight + const wallReference = modules + .map((module) => ({ module, wall: wallChildOf(module, scene.nodes()) })) + .find(({ wall }) => wall) + const wallY = wallReference?.wall + ? wallReference.module.position[1] + wallReference.wall.position[1] + : null + for (const module of modules) { + if (module.moduleKind === 'corner-filler') continue + // Preserve tall appliance envelopes and compartment contents. + const height = + resolveCabinetType(module, run) === 'tall' + ? module.carcassHeight + : Math.max(baseHeight, minCabinetCarcassHeightForStack(module)) + scene.update(module.id, { + position: [module.position[0], runModuleBaseY(run), (module.depth - run.depth) / 2], + carcassHeight: height, + frontGap: run.frontGap, + frontOverlay: run.frontOverlay, + handleStyle: module.moduleKind === 'wall-filler' ? 'none' : run.handleStyle, + handlePosition: run.handlePosition, + }) + const wall = wallChildOf(module, scene.nodes()) + if (wall && wallY !== null) + scene.update(wall.id, { + position: [0, wallY - runModuleBaseY(run), backAlignZ(module.depth, wall.depth)], + frontGap: run.frontGap, + frontOverlay: run.frontOverlay, + handleStyle: run.handleStyle, + handlePosition: run.handlePosition, + }) + } + syncCornerRunsFromRunSources({ sceneApi: scene, run, previousModules: modules }) + scene.markDirty(run.id) +} diff --git a/packages/nodes/src/cabinet/run-layout.ts b/packages/nodes/src/cabinet/run-layout.ts index 20ede731a2..577d7c7282 100644 --- a/packages/nodes/src/cabinet/run-layout.ts +++ b/packages/nodes/src/cabinet/run-layout.ts @@ -508,13 +508,36 @@ export function getRunSpanEnds( if (childBaseLegSides.has('left') && spanIndex === 0) leftOverhang = 0 if (childBaseLegSides.has('right') && spanIndex === spans.length - 1) rightOverhang = 0 + const leftFiller = ctx?.children.find( + (child) => + child.type === 'cabinet-module' && + Math.abs(child.position[0] - child.width / 2 - span.minX) < RUN_ADJACENCY_EPSILON, + ) + const rightFiller = ctx?.children.find( + (child) => + child.type === 'cabinet-module' && + Math.abs(child.position[0] + child.width / 2 - span.maxX) < RUN_ADJACENCY_EPSILON, + ) + if (leftFiller?.type === 'cabinet-module' && leftFiller.moduleKind === 'wall-filler') + leftOverhang = 0 + if (rightFiller?.type === 'cabinet-module' && rightFiller.moduleKind === 'wall-filler') + rightOverhang = 0 const exposedLeft = - spanIndex === 0 && !hasExternalLeftNeighbor && !hasInternalLeftNeighbor && barEdge !== 'left' + !(leftFiller?.type === 'cabinet-module' && leftFiller.moduleKind === 'wall-filler') && + spanIndex === 0 && + !hasExternalLeftNeighbor && + !hasInternalLeftNeighbor && + barEdge !== 'left' && + !(cornerLink?.role === 'base-leg' && cornerLink.side === 'right') && + !childBaseLegSides.has('left') const exposedRight = + !(rightFiller?.type === 'cabinet-module' && rightFiller.moduleKind === 'wall-filler') && spanIndex === spans.length - 1 && !hasExternalRightNeighbor && !hasInternalRightNeighbor && - barEdge !== 'right' + barEdge !== 'right' && + !(cornerLink?.role === 'base-leg' && cornerLink.side === 'left') && + !childBaseLegSides.has('right') return { leftOverhang, rightOverhang, exposedLeft, exposedRight } }) diff --git a/packages/nodes/src/cabinet/run-ops.ts b/packages/nodes/src/cabinet/run-ops.ts index 297c215297..f1e4128fcc 100644 --- a/packages/nodes/src/cabinet/run-ops.ts +++ b/packages/nodes/src/cabinet/run-ops.ts @@ -481,7 +481,7 @@ export function cabinetModuleCanEqualizeWidth( run: CabinetNode, ): boolean { return ( - module.moduleKind !== 'corner-filler' && + module.moduleKind === 'standard' && resolveCabinetType(module, run) === 'base' && stackForCabinet(module).every((compartment) => EQUALIZABLE_CABINET_COMPARTMENTS.has(compartment.type), @@ -615,7 +615,7 @@ export function cabinetRunArrayPlan( const modules = cabinetModulesForRun(run, nodes) const source = modules.find((module) => module.id === options.sourceModuleId) - if (!source || source.moduleKind === 'corner-filler') { + if (source?.moduleKind !== 'standard') { return { ok: false, reason: 'no-source' } } diff --git a/packages/nodes/src/cabinet/run-panel.tsx b/packages/nodes/src/cabinet/run-panel.tsx index 004eedf278..badb797852 100644 --- a/packages/nodes/src/cabinet/run-panel.tsx +++ b/packages/nodes/src/cabinet/run-panel.tsx @@ -7,7 +7,13 @@ import type { CabinetNode as CabinetNodeType, SceneApi, } from '@pascal-app/core' -import { cascadeDirty, createSceneApi, resolveLevelId, useScene } from '@pascal-app/core' +import { + cascadeDirty, + createSceneApi, + resolveLevelId, + runAsSingleSceneHistoryStep, + useScene, +} from '@pascal-app/core' import { ActionButton, PanelSection, @@ -15,11 +21,13 @@ import { SegmentedControl, SliderControl, ToggleControl, + usePlacementNotice, } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' import { Copy, Equal as EqualIcon, Plus, Trash } from 'lucide-react' import { useCallback, useMemo, useState } from 'react' import { useShallow } from 'zustand/react/shallow' +import { finishKitchenRun } from './finish-operation' import { planCabinetHostedEdit } from './hosted-resize' import { metadataForSelectedWidth, @@ -41,6 +49,7 @@ import { cabinetRevealGapById, cabinetRevealGapId, } from './reveals' +import { cabinetWallFillerPlan } from './run-finishing' import { runWallConstraints } from './run-layout' import { addCabinetModuleSide, @@ -184,7 +193,7 @@ function hasLinkedCornerRun(module: CabinetModuleNodeType): boolean { ) } -export function reflowRunModules({ +export function planCabinetPresetReflow({ modules, parentRun, patch, @@ -196,7 +205,7 @@ export function reflowRunModules({ patch: Partial scene: ReturnType selected: CabinetModuleNodeType -}): boolean { +}) { const wallConstraints = runWallConstraints( parentRun, modules, @@ -279,6 +288,23 @@ export function reflowRunModules({ modules.map((module) => [module.id, presetWidthDebt(module, selected.id)]), ), }) + return reflowed +} + +export function reflowRunModules({ + modules, + parentRun, + patch, + scene, + selected, +}: { + modules: CabinetModuleNodeType[] + parentRun: CabinetNodeType + patch: Partial + scene: ReturnType + selected: CabinetModuleNodeType +}): boolean { + const reflowed = planCabinetPresetReflow({ modules, parentRun, patch, scene, selected }) if (reflowed.length === 0) return false const reflowById = new Map(reflowed.map((entry) => [entry.id, entry])) @@ -500,8 +526,8 @@ export function CabinetRunPanel({ const arraySource = useMemo( () => sortedModules.find( - (module) => module.id === arraySourceId && module.moduleKind !== 'corner-filler', - ) ?? sortedModules.find((module) => module.moduleKind !== 'corner-filler'), + (module) => module.id === arraySourceId && module.moduleKind === 'standard', + ) ?? sortedModules.find((module) => module.moduleKind === 'standard'), [arraySourceId, sortedModules], ) const arrayPlan = useMemo( @@ -515,6 +541,35 @@ export function CabinetRunPanel({ [arrayCopyCount, arrayDirection, arraySource?.id, arraySpacing, planningNode, planningNodes], ) + const placementNotice = usePlacementNotice(node.id) + const [finishMessage, setFinishMessage] = useState(null) + const fillerPlan = cabinetWallFillerPlan(planningNode, sortedModules, planningNodes) + + const finishRun = (action: 'align' | 'fill') => { + setFinishMessage(null) + try { + const outcome = finishKitchenRun( + useScene.getState().nodes, + { runId: node.id, action }, + { activeLevelId: null }, + ) + if (outcome.changes) + runAsSingleSceneHistoryStep(useScene, () => + useScene + .getState() + .applyNodeChanges( + outcome.changes as Parameters< + ReturnType['applyNodeChanges'] + >[0], + ), + ) + } catch (error) { + setFinishMessage( + error instanceof Error ? error.message : 'Unable to finish this kitchen run.', + ) + } + } + const updateRun = useCallback( (patch: Partial) => updateCabinetRun({ modules, node, patch }), [modules, node], @@ -606,18 +661,54 @@ export function CabinetRunPanel({ + {placementNotice && ( +

+ {placementNotice.line} +

+ )} + +
+ finishRun('align')} /> + {finishMessage && ( +

+ {finishMessage} +

+ )} +

+ Match base heights, backs, reveals and handles. Align upper cabinets; preserve tall + appliances and custom compartments. +

+ updateRun({ withFinishedEnds: checked })} + /> + finishRun('fill')} + /> +

+ {fillerPlan.length + ? fillerPlan + .map(({ side, width }) => `${side}: ${Math.round(width * 1000)} mm`) + .join(' · ') + : 'Fits 50–150 mm gaps at run ends beside perpendicular walls.'} +

+
+
{sortedModules.map((module, index) => (