From 5eb4d638c56dac6389a313a908124cdae6ceb0c9 Mon Sep 17 00:00:00 2001 From: Wassim SAMAD Date: Tue, 29 Sep 2026 16:57:54 -0400 Subject: [PATCH] feat(structure): room-first structure foundations Rooms (zones) now own their floor, wall and ceiling intent. Floors, walls and ceilings are derived from them by one server-safe reconciler, which the editor, the scene API and the MCP bridge all share. - Room-first zones: rooms own floor, wall and ceiling intent. Adds Divide, Delete room and return-to-room selection. - Derived floor plates: one base plate per connected footprint. Rooms stand on it as platforms or cut it as holes. - Raised and sunken rooms, terraces and mezzanines, with derived doorway steps. - Floor & foundation: each footprint's base plate carries a slab thickness and a foundation height. - Separate floors: a floor picker puts a room on its own base plate. - Floor openings and stair voids are floor-opening nodes (Edit floor / Cut opening). - Paint scopes: wall faces a/b, paint regions and per-doorway step finishes. - Legacy migrations (room zones, plates, openings, datums) load existing projects exactly like main. - Tool FSM: leaving Select ends the selection. - MCP: room, floor, opening and structure tools. Writes to derived nodes are refused. The fixtures derived from production scenes are trimmed to one per legacy case and anonymised. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_013LKpG6PpZe6Jb4dBBAKtBG --- apps/editor/components/build-tab.tsx | 109 +- apps/editor/lib/build-palette.ts | 74 +- apps/editor/public/icons/divide-room.webp | Bin 0 -> 9300 bytes apps/editor/public/icons/measure.webp | Bin 0 -> 8518 bytes apps/editor/public/icons/mezzanine.webp | Bin 0 -> 9712 bytes apps/editor/public/icons/polygon-room.webp | Bin 0 -> 8862 bytes apps/editor/public/icons/resize.webp | Bin 0 -> 9164 bytes apps/editor/public/icons/walls.webp | Bin 0 -> 11620 bytes bun.lock | 7 + packages/core/package.json | 6 + .../structure/apply-zone-transform.ts | 88 + .../commands/structure/create-mezzanine.ts | 73 + .../src/commands/structure/create-zone.ts | 170 ++ .../commands/structure/delete-zone.test.ts | 242 ++ .../src/commands/structure/delete-zone.ts | 425 +++ .../structure/divide-zone-path.test.ts | 434 +++ .../src/commands/structure/divide-zone.ts | 241 ++ .../src/commands/structure/duplicate-zone.ts | 24 + .../structure/floor-foundation-lift.test.ts | 518 ++++ .../structure/floor-grade-round-trip.test.ts | 79 + .../src/commands/structure/floor-opening.ts | 172 ++ .../ground-floor-construction.test.ts | 157 + packages/core/src/commands/structure/index.ts | 52 + .../structure/legacy-floor-reference.test.ts | 299 ++ .../commands/structure/lock-outside-faces.ts | 43 + .../src/commands/structure/merge-zones.ts | 50 + .../commands/structure/mezzanine-content.ts | 134 + .../structure/mezzanine-transform.test.ts | 438 +++ .../structure/plan-mezzanine-stair.ts | 139 + .../structure/plan-wall-deletion.test.ts | 297 ++ .../commands/structure/plan-wall-deletion.ts | 187 ++ .../structure/rebase-floor-reference.ts | 103 + .../commands/structure/resize-mezzanine.ts | 61 + .../src/commands/structure/rotate-zone.ts | 35 + .../set-floor-foundation-height.test.ts | 90 + .../structure/set-floor-foundation.test.ts | 197 ++ .../structure/set-floor-foundation.ts | 205 ++ .../structure/set-room-floor-construction.ts | 92 + .../commands/structure/set-wall-geometry.ts | 85 + .../src/commands/structure/set-zone-edges.ts | 196 ++ .../src/commands/structure/set-zone-intent.ts | 129 + .../core/src/commands/structure/shared.ts | 157 + .../structure/structure-audit.test.ts | 205 ++ .../structure/structure-store.test.ts | 304 ++ .../src/commands/structure/structure.test.ts | 387 +++ .../src/commands/structure/transform-zone.ts | 544 ++++ .../commands/structure/validate-mezzanine.ts | 91 + .../structure/vertical-model-c.test.ts | 440 +++ .../src/commands/structure/zone-crossings.ts | 191 ++ .../core/src/commands/structure/zone-drop.ts | 77 + .../src/commands/structure/zone-insertion.ts | 243 ++ .../structure/zone-legacy-transform.test.ts | 36 + .../structure/zone-transform-content.ts | 139 + .../commands/structure/zone-transform.test.ts | 1536 ++++++++++ .../src/commands/structure/zone-wall-merge.ts | 196 ++ packages/core/src/contracts/assembly.test.ts | 4 +- .../core/src/contracts/reference-inventory.ts | 217 +- packages/core/src/events/bus.ts | 59 +- .../floor-placed-elevation.test.ts | 48 + .../spatial-grid/floor-placed-elevation.ts | 25 +- .../spatial-grid/spatial-grid-manager.ts | 107 +- .../hooks/spatial-grid/spatial-grid-sync.ts | 201 +- .../hooks/spatial-grid/support-host-patch.ts | 11 +- .../hooks/spatial-grid/support-host.test.ts | 8 + .../wall-elevation-parity.test.ts | 37 + packages/core/src/index.ts | 212 +- .../lib/__bench__/structure-preview.bench.ts | 79 + .../lib/__fixtures__/joint-merge-rooms.json | 377 +++ .../core/src/lib/__fixtures__/mezzanine.ts | 52 + .../plate-corpus/frozen-gate/README.md | 19 + .../plate-corpus/frozen-gate/scene-10.json | 1751 +++++++++++ .../plate-corpus/frozen-gate/scene-19.json | 2593 ++++++++++++++++ .../plate-corpus/frozen-gate/scene-21.json | 2365 ++++++++++++++ .../plate-corpus/legacy-load/scene-04.json | 1925 ++++++++++++ .../plate-corpus/legacy-load/scene-13.json | 59 + .../plate-corpus/legacy-load/scene-16.json | 559 ++++ .../plate-corpus/legacy-load/scene-22.json | 628 ++++ .../plate-corpus/migrations/README.md | 29 + .../scene-01-level_eodfbqctw101ntkx.json | 195 ++ .../scene-03-level_jed5kaoexwb8xvuh.json | 284 ++ .../scene-05-level_jkmni52gfrkgddfo.json | 332 ++ .../scene-08-level_4jr4wmtf6uevuduw.json | 458 +++ .../scene-09-level_t3oshtg9z9weuhvz.json | 374 +++ .../scene-11-level_0xnyuk0r705m454c.json | 1653 ++++++++++ .../scene-12-level_v7ocab71p8y3f2x9.json | 382 +++ .../scene-20-level_uqfel9edw0c08f4a.json | 272 ++ .../scene-23-level_588ekegw4cj0g7zn.json | 276 ++ .../scene-25-level_jwi4ovhyra2ayxa5.json | 1310 ++++++++ .../scene-25-level_tf1ug5dswkkzfhqa.json | 1618 ++++++++++ .../scene-27-level_q5k3omsgkch1zjp1.json | 1519 +++++++++ .../review/legacy-terrace-pad.json | 2477 +++++++++++++++ .../plate-corpus/review/scene-06.json | 826 +++++ .../plate-corpus/review/scene-07.json | 1 + .../plate-corpus/review/scene-17.json | 1 + .../plate-corpus/review/scene-24.json | 1 + .../plate-corpus/review/scene-26.json | 1 + .../__fixtures__/plate-corpus/scene-02.json | 138 + .../__fixtures__/plate-corpus/scene-14.json | 155 + .../__fixtures__/plate-corpus/scene-15.json | 136 + .../__fixtures__/plate-corpus/scene-18.json | 650 ++++ .../__fixtures__/plate-corpus/scene-28.json | 219 ++ .../stacked-walls-doubled-span.json | 214 ++ .../__fixtures__/structure-test-06-walls.json | 272 ++ .../core/src/lib/absorb-wall-separators.ts | 74 + .../core/src/lib/canonical-opening-ring.ts | 21 + packages/core/src/lib/ceiling-children.ts | 52 + packages/core/src/lib/ceiling-surface.test.ts | 238 ++ packages/core/src/lib/ceiling-surface.ts | 99 + .../core/src/lib/floor-construction-lift.ts | 65 + .../src/lib/floor-footprint-creator.test.ts | 186 ++ packages/core/src/lib/floor-footprint-key.ts | 11 + .../core/src/lib/floor-footprint-name.test.ts | 52 + packages/core/src/lib/floor-footprint-name.ts | 68 + .../core/src/lib/floor-foundation-datum.ts | 331 ++ .../core/src/lib/floor-foundation-stack.ts | 269 ++ packages/core/src/lib/floor-intent-changes.ts | 531 ++++ packages/core/src/lib/floor-levels.test.ts | 408 +++ .../core/src/lib/floor-opening-footprints.ts | 187 ++ .../core/src/lib/floor-opening-intent.test.ts | 497 +++ packages/core/src/lib/floor-opening-intent.ts | 112 + packages/core/src/lib/floor-plate-id.ts | 31 + packages/core/src/lib/floor-plate-paint.ts | 25 + .../core/src/lib/floor-plate-support.test.ts | 111 + packages/core/src/lib/floor-plates.ts | 919 ++++++ packages/core/src/lib/floor-room-faces.ts | 37 + .../core/src/lib/floor-step-finish.test.ts | 288 ++ packages/core/src/lib/floor-step-finish.ts | 191 ++ .../core/src/lib/level-footprints.test.ts | 620 ++++ packages/core/src/lib/level-footprints.ts | 474 +++ packages/core/src/lib/level-name.test.ts | 24 + packages/core/src/lib/level-name.ts | 14 +- packages/core/src/lib/mezzanine-audit.test.ts | 453 +++ packages/core/src/lib/mezzanine.test.ts | 248 ++ packages/core/src/lib/node-ancestry.ts | 82 + .../core/src/lib/opening-floor-datum.test.ts | 42 + packages/core/src/lib/opening-floor-datum.ts | 231 ++ packages/core/src/lib/own-floor-intent.ts | 255 ++ packages/core/src/lib/own-floor.test.ts | 787 +++++ packages/core/src/lib/plate-corpus.test.ts | 71 + packages/core/src/lib/plate-recovery.test.ts | 83 + packages/core/src/lib/plate-reference.test.ts | 66 + packages/core/src/lib/plate-reference.ts | 130 + .../src/lib/plate-riser-ownership.test.ts | 62 + packages/core/src/lib/plate-step.test.ts | 145 + packages/core/src/lib/plate-surface.test.ts | 323 ++ packages/core/src/lib/plate-surface.ts | 984 ++++++ packages/core/src/lib/polygon-boolean.test.ts | 187 ++ packages/core/src/lib/polygon-boolean.ts | 250 ++ packages/core/src/lib/polygon-label.ts | 95 + .../core/src/lib/room-drawn-floor.test.ts | 199 ++ packages/core/src/lib/room-drawn-floor.ts | 123 + packages/core/src/lib/room-floor-choices.ts | 73 + .../core/src/lib/room-floor-feasibility.ts | 401 +++ packages/core/src/lib/room-floor-plate.ts | 6 + packages/core/src/lib/room-graph.ts | 1294 ++++++++ packages/core/src/lib/room-holes.test.ts | 91 + packages/core/src/lib/room-name.ts | 21 + .../core/src/lib/room-topology-index.test.ts | 218 ++ packages/core/src/lib/room-topology-index.ts | 292 +- .../core/src/lib/room-vertical-placement.ts | 38 + .../core/src/lib/room-zone-adoption.test.ts | 47 + packages/core/src/lib/room-zone-adoption.ts | 208 ++ packages/core/src/lib/slab-polygon.ts | 48 +- packages/core/src/lib/slots.ts | 29 + .../lib/space-detection-invariants.test.ts | 385 +++ .../space-detection-reconciliation.test.ts | 151 +- packages/core/src/lib/space-detection.test.ts | 1369 ++------- packages/core/src/lib/space-detection.ts | 2708 ++--------------- packages/core/src/lib/structure-commit.ts | 84 + packages/core/src/lib/structure-json.test.ts | 341 +++ .../core/src/lib/structure-kernel.test.ts | 1014 ++++++ packages/core/src/lib/structure-kernel.ts | 854 ++++++ .../core/src/lib/structure-preview.test.ts | 123 + .../core/src/lib/structure-reconcile.test.ts | 446 +++ packages/core/src/lib/structure-reconcile.ts | 283 ++ .../core/src/lib/terrain-source-persisted.ts | 79 + packages/core/src/lib/terrain-source.ts | 84 +- .../core/src/lib/terrain-support-query.ts | 219 ++ packages/core/src/lib/terrain-support.ts | 208 +- .../core/src/lib/unit-containment.test.ts | 4 +- packages/core/src/lib/unit-containment.ts | 4 +- packages/core/src/lib/unit-report.test.ts | 11 +- packages/core/src/lib/unit-report.ts | 10 +- .../lib/wall-bound-surface-follower.test.ts | 29 - packages/core/src/lib/zone-quantities.test.ts | 18 +- packages/core/src/lib/zone-quantities.ts | 405 +-- packages/core/src/procedural-items/query.ts | 13 +- .../registry/plugin-v1-conformance.test.ts | 10 +- packages/core/src/registry/registry.ts | 4 +- packages/core/src/registry/scene-api.test.ts | 52 + packages/core/src/registry/scene-api.ts | 34 +- packages/core/src/registry/types.ts | 14 +- .../src/schema/__fixtures__/node-fixtures.ts | 2 + .../core/src/schema/host-children.test.ts | 17 +- packages/core/src/schema/index.ts | 23 +- packages/core/src/schema/node-union.test.ts | 1 + packages/core/src/schema/nodes/ceiling.ts | 8 + packages/core/src/schema/nodes/door.ts | 2 + .../core/src/schema/nodes/floor-opening.ts | 23 + packages/core/src/schema/nodes/level.ts | 4 + .../src/schema/nodes/roof-segment-walls.ts | 3 +- .../core/src/schema/nodes/room-fields.test.ts | 74 + packages/core/src/schema/nodes/separator.ts | 13 + packages/core/src/schema/nodes/slab.ts | 45 +- .../src/schema/nodes/surface-hole-metadata.ts | 3 +- .../src/schema/nodes/surface-paint-region.ts | 15 + packages/core/src/schema/nodes/wall.test.ts | 252 +- packages/core/src/schema/nodes/wall.ts | 319 +- packages/core/src/schema/nodes/window.ts | 2 + packages/core/src/schema/nodes/zone.ts | 50 + packages/core/src/schema/types.ts | 4 + .../core/src/services/alignment-anchors.ts | 20 +- packages/core/src/services/level-height.ts | 13 +- packages/core/src/services/storey.ts | 112 +- packages/core/src/services/surface-hosting.ts | 2 + .../core/src/store/actions/node-actions.ts | 245 +- .../core/src/store/derived-node-guard.test.ts | 506 +++ packages/core/src/store/derived-node-guard.ts | 651 ++++ .../store/derived-writer-allowlist.test.ts | 64 + .../core/src/store/floor-opening-live.test.ts | 283 ++ .../floor-opening-write-conversion.test.ts | 284 ++ packages/core/src/store/history-control.ts | 35 + .../src/store/history-invalidation.test.ts | 57 + .../core/src/store/history-invalidation.ts | 1 + .../store/registered-node-defaults.test.ts | 117 + .../src/store/registered-node-defaults.ts | 29 + .../core/src/store/use-scene-commits.test.ts | 228 +- .../store/use-scene-dirty-tracking.test.ts | 26 + .../src/store/use-scene-floor-top.test.ts | 183 ++ .../store/use-scene-room-invariants.test.ts | 725 +++++ .../store/use-scene-room-migration.test.ts | 213 ++ .../use-scene-temporal-reconciliation.test.ts | 85 +- .../use-scene-vertical-migration.test.ts | 2 +- .../use-scene-wall-slot-migration.test.ts | 13 +- packages/core/src/store/use-scene.ts | 413 +-- .../systems/elevator/elevator-opening-sync.ts | 10 +- .../elevator/elevator-opening-system.test.ts | 23 +- .../elevator/elevator-opening-system.tsx | 18 +- .../src/systems/elevator/elevator-service.ts | 13 +- .../src/systems/owned-floor-openings.test.ts | 435 +++ .../core/src/systems/owned-floor-openings.ts | 387 +++ .../systems/reconcile-owned-floor-openings.ts | 26 + .../slab/__fixtures__/doorway-steps.ts | 83 + .../systems/slab/__fixtures__/floor-step.ts | 82 + .../systems/slab/__fixtures__/raised-room.ts | 56 + .../src/systems/slab/ensure-slab-openings.ts | 44 + .../core/src/systems/slab/floor-step.test.ts | 185 ++ .../src/systems/slab/platform-audit.test.ts | 107 + .../core/src/systems/slab/raised-room.test.ts | 109 + .../core/src/systems/slab/slab-support.ts | 673 +++- .../src/systems/stair/stair-base-elevation.ts | 61 + .../systems/stair/stair-floor-footprints.ts} | 17 +- .../core/src/systems/stair/stair-footprint.ts | 56 + .../stair/stair-opening-movement.test.ts | 141 + .../systems/stair/stair-opening-sync.test.ts | 8 + .../src/systems/stair/stair-opening-sync.ts | 73 +- .../systems/stair/stair-opening-system.tsx | 38 +- .../systems/stair/stair-rise-query.test.ts | 27 + .../src/systems/stair/stair-rise-query.ts | 152 + packages/core/src/systems/stair/stair-rise.ts | 98 +- .../wall/__fixtures__/wall-frame-golden.json | 2402 +++++++++++++++ .../src/systems/wall/wall-assembly.test.ts | 17 +- .../core/src/systems/wall/wall-assembly.ts | 9 +- packages/core/src/systems/wall/wall-curve.ts | 33 +- .../core/src/systems/wall/wall-finish.test.ts | 201 ++ packages/core/src/systems/wall/wall-finish.ts | 387 +++ .../core/src/systems/wall/wall-footprint.ts | 26 +- .../core/src/systems/wall/wall-frame.test.ts | 151 + packages/core/src/systems/wall/wall-frame.ts | 196 ++ .../systems/wall/wall-justification.test.ts | 397 +++ .../core/src/systems/wall/wall-layer-bands.ts | 4 +- .../systems/wall/wall-merge-finish.test.ts | 196 ++ packages/core/src/systems/wall/wall-merge.ts | 239 +- .../core/src/systems/wall/wall-mitering.ts | 104 +- .../core/src/systems/wall/wall-operations.ts | 2 + .../systems/wall/wall-reference-line.test.ts | 185 ++ .../core/src/systems/wall/wall-room-sides.ts | 25 + .../src/systems/wall/wall-step-openings.ts | 46 + .../core/src/systems/wall/wall-top.test.ts | 4 +- packages/core/src/systems/wall/wall-top.ts | 11 +- .../core/src/systems/wall/wall-topology.ts | 9 +- .../project_hrY3qVVq16yo5Out.json | 1684 ++++++++++ .../src/utils/clone-scene-graph-fork.test.ts | 259 ++ packages/core/src/utils/clone-scene-graph.ts | 117 +- .../src/utils/ensure-scene-openings.test.ts | 96 + .../core/src/utils/ensure-scene-openings.ts | 29 + .../exterior-threshold-migration.test.ts | 206 ++ .../src/utils/exterior-threshold-migration.ts | 139 + .../core/src/utils/floor-follow-migration.ts | 37 + .../core/src/utils/floor-opening-migration.ts | 159 + .../src/utils/floor-piece-adoption.test.ts | 204 ++ .../core/src/utils/floor-piece-adoption.ts | 234 ++ .../core/src/utils/floor-plate-corpus.test.ts | 422 +++ .../core/src/utils/floor-plate-load.test.ts | 262 ++ .../src/utils/floor-plate-migration.test.ts | 640 ++++ .../core/src/utils/floor-plate-migration.ts | 1625 ++++++++++ .../core/src/utils/floor-plate-split.test.ts | 88 + .../core/src/utils/floor-review-load.test.ts | 138 + .../core/src/utils/frozen-floor-gate.test.ts | 175 ++ .../src/utils/heal-plan-coordinates.test.ts | 133 + .../core/src/utils/heal-plan-coordinates.ts | 64 + .../core/src/utils/heal-scene-graph.test.ts | 22 + packages/core/src/utils/heal-scene-graph.ts | 57 +- .../core/src/utils/legacy-floor-datum.test.ts | 269 ++ .../src/utils/legacy-material-slots.test.ts | 35 + .../core/src/utils/legacy-material-slots.ts | 150 + .../src/utils/legacy-opening-datums.test.ts | 135 + .../core/src/utils/legacy-opening-datums.ts | 118 + packages/core/src/utils/legacy-wall-datums.ts | 263 ++ packages/core/src/utils/node-defaults.ts | 82 + .../utils/normalize-legacy-structure.test.ts | 146 + .../src/utils/normalize-legacy-structure.ts | 65 + packages/core/src/utils/omit-undefined.ts | 16 + .../owned-floor-opening-migration.test.ts | 76 + .../utils/owned-floor-opening-migration.ts | 314 ++ .../utils/reconcile-structure-on-load.test.ts | 319 ++ .../src/utils/reconcile-structure-on-load.ts | 331 ++ .../src/utils/room-zone-migration.test.ts | 710 +++++ .../core/src/utils/room-zone-migration.ts | 327 ++ packages/core/src/utils/scene-migrations.ts | 32 + packages/core/src/utils/structure-id.ts | 141 + .../src/utils/vertical-scene-migration.ts | 25 +- .../src/utils/wall-assembly-migration.test.ts | 40 +- .../src/utils/wall-face-migration.test.ts | 424 +++ .../core/src/utils/wall-face-migration.ts | 281 ++ .../floorplan-cursor-indicator-overlay.tsx | 12 +- .../floorplan-registry-action-menu.tsx | 3 + .../floorplan-registry-layer.test.ts | 43 +- .../renderers/floorplan-registry-layer.tsx | 464 +-- .../editor/capture-level-picker.tsx | 72 + .../editor/delete-confirmation-dialog.tsx | 304 +- .../components/editor/editor-layout-v2.tsx | 8 +- .../editor/floating-action-menu.tsx | 24 +- .../editor/floor-openings-overlay.tsx | 243 ++ .../editor/floor-region-controls.tsx | 846 +++++ .../floor-region-webgpu-materials.test.ts | 12 + .../editor/floorplan-background-selection.ts | 2 +- .../src/components/editor/floorplan-panel.tsx | 141 +- .../editor/footprint-height-handle.tsx | 204 ++ .../src/components/editor/group-actions.ts | 14 +- .../handles/handle-hit-priority.test.tsx | 63 + .../editor/handles/handle-hit-priority.tsx | 37 + .../editor/handles/use-handle-drag.ts | 467 +-- .../editor/src/components/editor/index.tsx | 162 +- .../components/editor/node-action-menu.tsx | 208 +- .../components/editor/node-arrow-handles.tsx | 8 +- .../src/components/editor/room-controls.tsx | 846 +++++ .../editor/room-floor-highlight.tsx | 128 + .../src/components/editor/room-handles-2d.tsx | 354 +++ .../src/components/editor/room-handles.tsx | 675 ++++ .../src/components/editor/room-highlight.tsx | 168 + .../editor/room-transform-ghost.tsx | 256 ++ .../editor/room-webgpu-materials.test.ts | 27 + .../components/editor/selection-manager.tsx | 418 ++- .../editor/slab-hole-highlights.tsx | 3 + .../editor/snapshot-capture-overlay.tsx | 4 + .../use-floorplan-background-placement.ts | 6 +- .../editor/wall-justification.test.ts | 140 + .../editor/wall-move-side-handles.tsx | 185 +- .../src/components/editor/wall-push-arrow.tsx | 92 + .../components/editor/wall-region-handles.tsx | 509 ++++ .../editor/wall-snap-beacon-layer.tsx | 3 + ...eiling-selection-affordance-system.test.ts | 156 +- .../ceiling-selection-affordance-system.tsx | 40 +- .../systems/zone/zone-label-editor-system.tsx | 8 +- .../tools/item/placement-strategies.ts | 12 +- .../tools/item/use-placement-coordinator.tsx | 47 +- .../tools/paint-region/use-paint-tint.ts | 37 + .../paint-region/wall-paint-region-tool.tsx | 466 +++ .../tools/select/box-select-tool.tsx | 12 +- .../select/plane-box-select-tool.test.tsx | 79 + .../tools/select/plane-box-select-tool.tsx | 57 +- .../tools/select/select-candidates.ts | 26 +- .../components/tools/shared/cursor-sphere.tsx | 10 +- .../src/components/tools/tool-manager.tsx | 24 +- .../tools/wall/wall-drafting.test.ts | 23 +- .../src/components/tools/zone/zone-tool.tsx | 5 +- .../ui/action-menu/action-button.tsx | 3 + .../ui/action-menu/control-modes.tsx | 1 + .../components/ui/build-panel/build-panel.tsx | 235 ++ .../ui/command-palette/editor-commands.tsx | 14 - .../components/ui/command-palette/index.tsx | 23 - .../components/ui/controls/finish-swatch.tsx | 110 + .../ui/controls/material-paint-panel.tsx | 123 +- .../ui/controls/material-picker.tsx | 5 +- .../ui/controls/scene-material-list.tsx | 36 +- .../components/ui/helpers/building-helper.tsx | 5 +- .../ui/helpers/contextual-helper-panel.tsx | 173 +- .../ui/helpers/helper-manager.test.tsx | 69 + .../components/ui/helpers/helper-manager.tsx | 325 +- .../src/components/ui/helpers/item-helper.tsx | 4 + .../ui/helpers/registered-tool-helper.tsx | 4 + .../ui/panels/floor-foundation-panel.tsx | 551 ++++ .../ui/panels/floor-opening-panel.tsx | 143 + .../ui/panels/multi-parametric-inspector.tsx | 54 +- .../src/components/ui/panels/node-display.ts | 4 + .../components/ui/panels/panel-manager.tsx | 43 +- .../components/ui/panels/panel-wrapper.tsx | 88 +- .../ui/panels/room-construction-rows.tsx | 774 +++++ .../ui/panels/room-name-options.test.ts | 55 + .../components/ui/panels/room-name-options.ts | 47 + .../ui/panels/room-openings-field.tsx | 110 + .../src/components/ui/panels/room-panel.tsx | 725 +++++ .../src/components/ui/panels/shape-choice.tsx | 58 + .../components/ui/panels/wall-region-list.tsx | 109 + .../components/ui/primitives/color-dot.tsx | 44 +- .../src/components/ui/right-stack.test.ts | 29 + .../editor/src/components/ui/right-stack.tsx | 145 + .../keyboard-shortcuts-dialog.tsx | 2 +- .../panels/site-panel/ceiling-tree-node.tsx | 5 +- .../ui/sidebar/panels/site-panel/index.tsx | 47 +- .../panels/site-panel/inline-rename-input.tsx | 5 +- .../panels/site-panel/level-tree-node.tsx | 5 +- .../panels/site-panel/slab-tree-node.tsx | 28 +- .../panels/site-panel/unit-tree-node.tsx | 2 +- .../panels/site-panel/zone-tree-node.tsx | 13 +- .../components/viewer/floorplan-preview.tsx | 11 +- .../editor/src/hooks/use-keyboard.test.ts | 47 +- packages/editor/src/hooks/use-keyboard.ts | 70 +- .../editor/src/hooks/use-selected-room.ts | 142 + packages/editor/src/index.tsx | 59 + .../src/lib/ceiling-edit-session.test.ts | 321 ++ .../editor/src/lib/ceiling-edit-session.ts | 206 ++ .../src/lib/ceiling-region-session.test.ts | 179 ++ packages/editor/src/lib/continuation.test.ts | 20 +- packages/editor/src/lib/continuation.ts | 25 +- .../src/lib/editor-level-display.test.ts | 96 + .../editor/src/lib/editor-level-display.ts | 47 + packages/editor/src/lib/floor-edit-session.ts | 153 + .../editor/src/lib/floor-footprints.test.ts | 563 ++++ packages/editor/src/lib/floor-footprints.ts | 395 +++ .../src/lib/floor-foundation-support.test.ts | 283 ++ .../editor/src/lib/floor-opening-draft.ts | 218 ++ .../editor/src/lib/floor-openings.test.ts | 216 ++ .../editor/src/lib/floor-region-geometry.ts | 191 ++ .../src/lib/floor-region-session.test.ts | 485 +++ .../editor/src/lib/floor-region-session.ts | 589 ++++ packages/editor/src/lib/floor-region-snap.ts | 101 + .../editor/src/lib/floor-step-hover.test.ts | 32 + .../lib/floorplan/floorplan-export.test.ts | 12 +- .../src/lib/floorplan/floorplan-export.tsx | 5 +- packages/editor/src/lib/floorplan/geometry.ts | 19 +- packages/editor/src/lib/floorplan/items.ts | 7 +- .../editor/src/lib/floorplan/schedules.ts | 6 +- .../editor/src/lib/gesture-lifecycle.test.ts | 595 ++++ packages/editor/src/lib/gesture-lifecycle.ts | 290 ++ .../src/lib/glb-export-zone-holes.test.ts | 41 + packages/editor/src/lib/glb-export.ts | 1 + packages/editor/src/lib/history.ts | 7 + packages/editor/src/lib/hud-title.ts | 109 + .../editor/src/lib/inspector-expanded.test.ts | 44 + packages/editor/src/lib/inspector-expanded.ts | 36 + packages/editor/src/lib/interaction/scope.ts | 18 + .../src/lib/live-gesture-round-trip.test.ts | 360 +++ .../editor/src/lib/material-catalog-model.ts | 4 +- .../src/lib/material-paint-panel-model.ts | 14 +- .../editor/src/lib/mezzanine-actions.test.ts | 342 +++ .../editor/src/lib/mezzanine-draft.test.ts | 501 +++ packages/editor/src/lib/mezzanine-draft.ts | 278 ++ packages/editor/src/lib/mezzanine-messages.ts | 26 + .../src/lib/mezzanine-selection.test.ts | 207 ++ packages/editor/src/lib/mezzanine-stairs.ts | 46 + .../editor/src/lib/paint-commit-route.test.ts | 37 + packages/editor/src/lib/paint-commit-route.ts | 17 + packages/editor/src/lib/paint-eyedropper.ts | 94 + .../editor/src/lib/paint-pass-through.test.ts | 111 + packages/editor/src/lib/paint-pass-through.ts | 76 + packages/editor/src/lib/paint-region-hover.ts | 25 + packages/editor/src/lib/paint-region-mode.ts | 154 + packages/editor/src/lib/paint-regions.test.ts | 166 + packages/editor/src/lib/paint-regions.ts | 192 ++ packages/editor/src/lib/paint-scope.test.ts | 352 ++- packages/editor/src/lib/paint-scope.ts | 291 +- packages/editor/src/lib/panel-rows.ts | 21 + .../src/lib/plate-paint-affected.test.ts | 300 ++ .../editor/src/lib/plate-paint-affected.ts | 177 ++ .../editor/src/lib/print-shell-compiler.ts | 1 + .../src/lib/room-assembly-overlay.test.ts | 275 ++ .../editor/src/lib/room-assembly-overlay.ts | 266 ++ packages/editor/src/lib/room-built-on.test.ts | 379 +++ packages/editor/src/lib/room-built-on.ts | 138 + .../src/lib/room-construction-commands.ts | 712 +++++ .../editor/src/lib/room-construction.test.ts | 746 +++++ packages/editor/src/lib/room-construction.ts | 385 +++ .../src/lib/room-controls-phase6.test.ts | 630 ++++ .../editor/src/lib/room-divide-session.ts | 523 ++++ packages/editor/src/lib/room-handle-drag.ts | 1068 +++++++ .../editor/src/lib/room-name-catalog.test.ts | 90 + packages/editor/src/lib/room-name-catalog.ts | 168 + .../src/lib/room-push-dimensions.test.ts | 311 ++ .../editor/src/lib/room-push-dimensions.ts | 251 ++ .../editor/src/lib/room-selection-commands.ts | 62 + .../editor/src/lib/room-selection.test.ts | 664 ++++ packages/editor/src/lib/room-selection.ts | 389 +++ .../editor/src/lib/room-structure-commands.ts | 94 + .../editor/src/lib/room-structure.test.ts | 921 ++++++ .../editor/src/lib/room-transform-session.ts | 570 ++++ .../editor/src/lib/room-zone-routing.test.ts | 228 ++ packages/editor/src/lib/room-zone-routing.ts | 138 + packages/editor/src/lib/scene-clipboard.ts | 51 +- .../src/lib/scene-material-refs.test.ts | 79 + .../editor/src/lib/scene-material-refs.ts | 79 + packages/editor/src/lib/scene.test.ts | 58 +- packages/editor/src/lib/scene.ts | 36 +- .../editor/src/lib/session-writes.test.ts | 120 + packages/editor/src/lib/session-writes.ts | 205 ++ packages/editor/src/lib/sidebar-panel.ts | 31 + packages/editor/src/lib/snapping-mode.test.ts | 4 + packages/editor/src/lib/snapping-mode.ts | 9 +- packages/editor/src/lib/terrace-draft.test.ts | 145 + packages/editor/src/lib/terrace-draft.ts | 213 ++ .../editor/src/lib/tool-cursor-icon.test.ts | 16 + packages/editor/src/lib/tool-cursor-icon.ts | 11 + packages/editor/src/lib/typing-target.ts | 9 + packages/editor/src/lib/units.ts | 74 +- .../editor/src/lib/wall-draw-variant.test.ts | 71 + packages/editor/src/lib/wall-draw-variant.ts | 91 + .../src/lib/wall-paint-region-session.ts | 246 ++ .../editor/src/lib/wall-paint-region.test.ts | 373 +++ .../editor/src/lib/wall-polygon-draft.test.ts | 259 ++ packages/editor/src/lib/wall-polygon-draft.ts | 285 ++ packages/editor/src/lib/wall-push.test.ts | 453 +++ packages/editor/src/lib/wall-region-face.ts | 352 +++ .../src/lib/wall-region-handles.test.ts | 304 ++ .../editor/src/lib/wall-region-handles.ts | 368 +++ .../editor/src/lib/wall-region-list.test.ts | 119 + packages/editor/src/lib/wall-region-list.ts | 136 + packages/editor/src/lib/wall-region-snap.ts | 110 + packages/editor/src/lib/zone-content.ts | 5 +- packages/editor/src/lib/zone-name.test.ts | 17 + packages/editor/src/lib/zone-name.ts | 17 + .../src/store/opens-in-select-mode.test.ts | 87 + packages/editor/src/store/paint-mode.test.ts | 189 ++ packages/editor/src/store/tool-mode.test.ts | 122 + .../src/store/use-delete-confirmation.ts | 29 +- packages/editor/src/store/use-editor.tsx | 172 +- .../src/store/use-floorplan-draft-preview.ts | 13 + .../editor/src/store/use-floorplan-marquee.ts | 14 +- .../editor/src/store/use-wall-move-ghosts.ts | 6 +- .../use-wall-region-handles-selection.test.ts | 222 ++ .../use-wall-region-handles-selection.ts | 139 + .../test-utils/immediate-animation-frames.ts | 16 + .../src/test-utils/live-gesture-round-trip.ts | 224 ++ .../src/test-utils/selection-harness.ts | 82 + packages/mcp/README.md | 4 +- packages/mcp/src/bridge/scene-bridge.ts | 239 +- .../mcp/src/operations/scene-operations.ts | 15 + packages/mcp/src/resources/agent-guide.ts | 2 + packages/mcp/src/tools/apply-patch.test.ts | 69 +- .../mcp/src/tools/construction-tools.test.ts | 118 +- packages/mcp/src/tools/construction-tools.ts | 301 +- packages/mcp/src/tools/describe-node.ts | 8 +- .../mcp/src/tools/floor-foundation.test.ts | 277 ++ packages/mcp/src/tools/get-node.ts | 16 +- packages/mcp/src/tools/index.ts | 2 + packages/mcp/src/tools/live-sync.ts | 16 - packages/mcp/src/tools/measure-world.test.ts | 8 + packages/mcp/src/tools/mezzanine.test.ts | 320 ++ packages/mcp/src/tools/own-floor.test.ts | 87 + .../src/tools/read-tool-annotations.test.ts | 15 + packages/mcp/src/tools/room-tools.test.ts | 114 +- packages/mcp/src/tools/room-tools.ts | 161 +- .../mcp/src/tools/scene-query-holes.test.ts | 55 + packages/mcp/src/tools/scene-query.test.ts | 4 +- packages/mcp/src/tools/scene-query.ts | 54 +- .../mcp/src/tools/structure-tools.test.ts | 681 +++++ packages/mcp/src/tools/structure-tools.ts | 458 +++ packages/mcp/src/tools/wall-deletion.test.ts | 203 ++ packages/nodes/package.json | 4 +- packages/nodes/src/cabinet/run-layout.ts | 22 +- packages/nodes/src/cabinet/tool.tsx | 47 +- packages/nodes/src/cabinet/wall-snap.ts | 17 +- .../nodes/src/ceiling/boundary-editor.tsx | 8 +- .../src/ceiling/floorplan-affordances.ts | 1 - packages/nodes/src/ceiling/floorplan-move.ts | 1 - packages/nodes/src/ceiling/hole-editor.tsx | 7 +- packages/nodes/src/ceiling/materials.ts | 9 +- packages/nodes/src/ceiling/paint.test.ts | 154 + packages/nodes/src/ceiling/paint.ts | 166 +- packages/nodes/src/ceiling/panel.tsx | 55 +- packages/nodes/src/ceiling/renderer.tsx | 44 +- packages/nodes/src/chimney/paint.ts | 13 +- .../src/construction-dimension/floorplan.ts | 6 +- packages/nodes/src/door/definition.ts | 2 +- packages/nodes/src/door/door-math.ts | 8 +- packages/nodes/src/door/floorplan.ts | 14 +- packages/nodes/src/door/move-tool.tsx | 60 +- packages/nodes/src/door/preview.tsx | 2 + packages/nodes/src/door/tool.tsx | 1 + packages/nodes/src/dormer/paint.ts | 7 +- packages/nodes/src/eyebrow-vent/paint.ts | 9 +- packages/nodes/src/fence/geometry.ts | 17 +- packages/nodes/src/fence/lift.ts | 11 +- .../nodes/src/floor-opening/definition.ts | 52 + .../nodes/src/floor-opening/floorplan.test.ts | 30 + packages/nodes/src/floor-opening/floorplan.ts | 78 + .../src/floor-opening/triangulation.test.ts | 100 + packages/nodes/src/index.ts | 6 + .../src/item/floorplan-move-history.test.tsx | 6 +- packages/nodes/src/item/floorplan.ts | 7 +- packages/nodes/src/item/paint.ts | 13 +- .../nodes/src/lean-to-extension/layout.ts | 4 +- .../lean-to-extension/placement-validation.ts | 15 +- packages/nodes/src/measurement/definition.ts | 2 +- packages/nodes/src/roof/panel-model.ts | 7 +- .../nodes/src/separator/definition.test.ts | 36 + packages/nodes/src/separator/definition.ts | 40 + packages/nodes/src/separator/renderer.tsx | 61 + .../nodes/src/shared/erase-preview.test.ts | 112 + packages/nodes/src/shared/eyedropper.test.ts | 123 + .../shared/node-batch/source-systems.test.ts | 10 +- .../nodes/src/shared/node-batch/system.tsx | 9 +- .../nodes/src/shared/opening-documentation.ts | 25 +- .../src/shared/opening-guides-runtime.ts | 52 +- .../shared/opening-placement-dimensions.ts | 6 +- .../nodes/src/shared/polygon-centroid-move.ts | 5 +- .../src/shared/polygon-vertex-affordance.ts | 33 +- .../src/shared/quick-measurement.test.ts | 45 +- packages/nodes/src/shared/run-hangers.ts | 10 +- packages/nodes/src/shared/slot-paint.ts | 57 +- packages/nodes/src/shared/surface-paint.ts | 7 +- .../shared/surface-raycast-batching.test.ts | 6 +- .../src/shared/swap-preview-material.test.ts | 21 + .../nodes/src/shared/swap-preview-material.ts | 17 + packages/nodes/src/shared/system-checks.ts | 8 +- .../nodes/src/shared/wall-opening-ceiling.ts | 22 +- .../src/site/recessed-slab-ground-holes.ts | 6 +- packages/nodes/src/site/renderer.tsx | 4 +- packages/nodes/src/site/sunken-room.test.ts | 56 + packages/nodes/src/site/terrain-holes.ts | 102 + packages/nodes/src/site/terrain-mesh.ts | 15 +- packages/nodes/src/site/terrain-renderer.tsx | 16 +- .../src/slab/__fixtures__/ghost-scene.json | 744 +++++ .../slab/__fixtures__/raised-room-scene.json | 398 +++ .../slab/__fixtures__/sunken-pit-scene.json | 1 + .../slab/__tests__/construction-lift.test.ts | 112 + .../slab/__tests__/doorway-step-paint.test.ts | 203 ++ .../nodes/src/slab/__tests__/erase.test.ts | 173 ++ .../__tests__/finish-swatch-parity.test.ts | 61 + .../floor-one-render-regression.test.ts | 107 + .../__tests__/floorplan-ownership.test.ts | 50 + .../nodes/src/slab/__tests__/geometry.test.ts | 27 +- .../src/slab/__tests__/ghost-floor.test.ts | 182 ++ .../src/slab/__tests__/mezzanine.test.ts | 56 + .../slab/__tests__/plate-paint-parity.test.ts | 319 ++ .../src/slab/__tests__/plate-paint.test.ts | 358 +++ .../src/slab/__tests__/plate-render.test.ts | 351 +++ .../src/slab/__tests__/raised-room.test.ts | 64 + .../src/slab/__tests__/step-geometry.test.ts | 1022 +++++++ packages/nodes/src/slab/boundary-editor.tsx | 17 +- packages/nodes/src/slab/definition.ts | 4 + .../nodes/src/slab/dependency-tracker.test.ts | 35 + packages/nodes/src/slab/dependency-tracker.ts | 81 +- packages/nodes/src/slab/elevation-limit.ts | 3 +- .../nodes/src/slab/floorplan-affordances.ts | 1 - packages/nodes/src/slab/floorplan-move.ts | 7 +- packages/nodes/src/slab/floorplan.ts | 16 +- packages/nodes/src/slab/geometry.ts | 385 ++- packages/nodes/src/slab/move-tool.tsx | 10 +- packages/nodes/src/slab/paint.ts | 563 +++- packages/nodes/src/slab/panel.tsx | 72 +- packages/nodes/src/slab/slots.ts | 12 +- packages/nodes/src/slab/surface-split.ts | 474 +++ packages/nodes/src/stair/definition.ts | 2 +- packages/nodes/src/stair/floor-stack.test.ts | 3 +- packages/nodes/src/stair/paint.ts | 15 +- packages/nodes/src/turbine-vent/paint.ts | 7 +- packages/nodes/src/unit/unit-panel.tsx | 11 +- packages/nodes/src/wall/actions.tsx | 14 +- .../nodes/src/wall/construction-dimensions.ts | 13 +- .../nodes/src/wall/contextual-dimensions.ts | 8 +- .../nodes/src/wall/curtain-wall-materials.ts | 12 +- packages/nodes/src/wall/curve-tool.tsx | 3 + packages/nodes/src/wall/definition.test.ts | 27 + packages/nodes/src/wall/definition.ts | 48 +- packages/nodes/src/wall/drawing-mode.ts | 39 - packages/nodes/src/wall/floor-step.test.ts | 186 ++ .../nodes/src/wall/floorplan-move.test.ts | 78 +- packages/nodes/src/wall/floorplan-move.ts | 131 +- packages/nodes/src/wall/floorplan-tool.tsx | 20 +- packages/nodes/src/wall/floorplan.test.ts | 23 +- packages/nodes/src/wall/floorplan.ts | 61 +- packages/nodes/src/wall/justification.test.ts | 469 +++ .../src/wall/live-gesture-round-trip.test.tsx | 218 ++ packages/nodes/src/wall/measurement.test.ts | 9 + packages/nodes/src/wall/measurement.ts | 19 +- .../nodes/src/wall/move-endpoint-tool.tsx | 25 +- packages/nodes/src/wall/move-shared.ts | 10 +- packages/nodes/src/wall/move-tool.test.tsx | 92 +- packages/nodes/src/wall/move-tool.tsx | 118 +- .../nodes/src/wall/multi-reference.test.ts | 54 + packages/nodes/src/wall/paint-plan.test.ts | 204 ++ packages/nodes/src/wall/paint-plan.ts | 215 ++ packages/nodes/src/wall/paint.test.ts | 345 ++- packages/nodes/src/wall/paint.ts | 490 ++- packages/nodes/src/wall/panel-model.test.ts | 19 +- packages/nodes/src/wall/panel-model.ts | 129 +- packages/nodes/src/wall/panel.tsx | 143 +- packages/nodes/src/wall/parametrics.ts | 3 + packages/nodes/src/wall/raised-room.test.ts | 74 + .../src/wall/rectangle-tool-sfx.test.tsx | 135 + packages/nodes/src/wall/rectangle-tool.tsx | 33 +- packages/nodes/src/wall/renderer.tsx | 4 + packages/nodes/src/wall/slots.ts | 91 +- .../nodes/src/wall/split-floorplan-layer.tsx | 13 +- packages/nodes/src/wall/split-return.test.ts | 95 + packages/nodes/src/wall/split-session.ts | 9 + packages/nodes/src/wall/system.tsx | 78 +- packages/nodes/src/wall/tool.tsx | 215 +- .../nodes/src/wall/treatment-level-data.ts | 31 +- packages/nodes/src/wall/treatments.test.ts | 34 +- packages/nodes/src/wall/treatments.tsx | 164 +- .../src/wall/wall-batch-canonical.test.ts | 214 ++ packages/nodes/src/wall/wall-batch-system.tsx | 40 +- packages/nodes/src/wall/wall-batch.ts | 13 +- packages/nodes/src/window/definition.ts | 2 +- packages/nodes/src/window/floorplan.ts | 13 +- packages/nodes/src/window/move-tool.tsx | 62 +- packages/nodes/src/window/preview.tsx | 2 + packages/nodes/src/window/tool.tsx | 19 +- packages/nodes/src/window/window-math.ts | 8 +- .../nodes/src/zone/contextual-dimensions.ts | 42 +- packages/nodes/src/zone/definition.ts | 10 +- packages/nodes/src/zone/floorplan.test.ts | 111 +- packages/nodes/src/zone/floorplan.ts | 141 +- packages/nodes/src/zone/quantities-panel.tsx | 20 +- packages/nodes/src/zone/quick-measurement.ts | 19 +- packages/nodes/src/zone/renderer.test.tsx | 94 + packages/nodes/src/zone/renderer.tsx | 339 +-- .../nodes/src/zone/room-clear-dimensions.ts | 6 +- packages/nodes/src/zone/room-documentation.ts | 13 +- .../src/components/viewer/glb-interactive.tsx | 24 +- .../src/components/viewer/glb-scene.tsx | 104 +- .../viewer/registered-systems.test.tsx | 101 + .../components/viewer/registered-systems.tsx | 31 +- packages/viewer/src/index.ts | 15 +- .../viewer/src/lib/pointer-events.test.ts | 25 +- packages/viewer/src/lib/pointer-events.ts | 21 +- .../src/lib/terrain-perimeter-fill.test.ts | 31 + .../viewer/src/lib/terrain-perimeter-fill.ts | 37 +- packages/viewer/src/lib/zone-geometry.test.ts | 41 + packages/viewer/src/lib/zone-geometry.ts | 61 + packages/viewer/src/store/use-viewer.ts | 7 + .../systems/ceiling/ceiling-system.test.ts | 127 + .../src/systems/ceiling/ceiling-system.tsx | 92 +- .../systems/door/door-floor-alignment.test.ts | 27 + .../viewer/src/systems/door/door-system.tsx | 12 +- .../systems/item-light/item-light-system.tsx | 13 +- .../viewer/src/systems/item/item-system.tsx | 14 +- .../src/systems/level/level-system.test.ts | 34 + .../viewer/src/systems/level/level-system.tsx | 10 +- .../src/systems/level/level-utils.test.ts | 15 + .../viewer/src/systems/level/level-utils.ts | 22 +- .../src/systems/level/shadow-only-levels.ts | 9 + .../viewer/src/systems/slab/slab-system.tsx | 34 +- .../__fixtures__/wawa-house-openings.json | 562 ++++ .../systems/wall/wall-cutout-cache.test.ts | 30 +- .../src/systems/wall/wall-cutout-cache.ts | 84 +- .../viewer/src/systems/wall/wall-cutout.tsx | 4 +- .../src/systems/wall/wall-finish-data.ts | 37 + .../systems/wall/wall-finish-geometry.test.ts | 300 ++ .../wall/wall-finish-plain-golden.json | 305 ++ .../systems/wall/wall-floor-step-golden.json | 26 + .../src/systems/wall/wall-floor-step.test.ts | 367 +++ .../systems/wall/wall-justification.test.ts | 160 + .../viewer/src/systems/wall/wall-materials.ts | 316 +- .../systems/wall/wall-opening-cutout.test.ts | 169 +- .../src/systems/wall/wall-platform.test.ts | 238 ++ .../wall/wall-progressive-budget.test.ts | 49 +- .../systems/wall/wall-room-corpus-golden.json | 29 + .../src/systems/wall/wall-room-corpus.test.ts | 106 + .../wall/wall-support-extension.test.ts | 6 +- .../viewer/src/systems/wall/wall-system.tsx | 632 +++- .../wall/wall-underpinning-openings.test.ts | 30 +- .../src/systems/window/window-system.tsx | 10 +- plugin-evals/README.md | 2 +- plugin-evals/publishing-cases.json | 10 +- plugin-evals/release-notes.md | 2 +- .../tool-annotation-justifications.json | 186 +- scripts/openai-tool-annotation-policy.test.ts | 2 +- scripts/openai-tool-annotation-policy.ts | 14 + scripts/validate-skills.ts | 4 +- wiki/architecture/selection-managers.md | 24 +- wiki/architecture/space-detection.md | 81 + wiki/architecture/systems.md | 13 +- wiki/architecture/tools.md | 4 +- wiki/architecture/vertical-model.md | 172 +- wiki/architecture/wall-frame.md | 38 + 788 files changed, 129411 insertions(+), 10049 deletions(-) create mode 100644 apps/editor/public/icons/divide-room.webp create mode 100644 apps/editor/public/icons/measure.webp create mode 100644 apps/editor/public/icons/mezzanine.webp create mode 100644 apps/editor/public/icons/polygon-room.webp create mode 100644 apps/editor/public/icons/resize.webp create mode 100644 apps/editor/public/icons/walls.webp create mode 100644 packages/core/src/commands/structure/apply-zone-transform.ts create mode 100644 packages/core/src/commands/structure/create-mezzanine.ts create mode 100644 packages/core/src/commands/structure/create-zone.ts create mode 100644 packages/core/src/commands/structure/delete-zone.test.ts create mode 100644 packages/core/src/commands/structure/delete-zone.ts create mode 100644 packages/core/src/commands/structure/divide-zone-path.test.ts create mode 100644 packages/core/src/commands/structure/divide-zone.ts create mode 100644 packages/core/src/commands/structure/duplicate-zone.ts create mode 100644 packages/core/src/commands/structure/floor-foundation-lift.test.ts create mode 100644 packages/core/src/commands/structure/floor-grade-round-trip.test.ts create mode 100644 packages/core/src/commands/structure/floor-opening.ts create mode 100644 packages/core/src/commands/structure/ground-floor-construction.test.ts create mode 100644 packages/core/src/commands/structure/index.ts create mode 100644 packages/core/src/commands/structure/legacy-floor-reference.test.ts create mode 100644 packages/core/src/commands/structure/lock-outside-faces.ts create mode 100644 packages/core/src/commands/structure/merge-zones.ts create mode 100644 packages/core/src/commands/structure/mezzanine-content.ts create mode 100644 packages/core/src/commands/structure/mezzanine-transform.test.ts create mode 100644 packages/core/src/commands/structure/plan-mezzanine-stair.ts create mode 100644 packages/core/src/commands/structure/plan-wall-deletion.test.ts create mode 100644 packages/core/src/commands/structure/plan-wall-deletion.ts create mode 100644 packages/core/src/commands/structure/rebase-floor-reference.ts create mode 100644 packages/core/src/commands/structure/resize-mezzanine.ts create mode 100644 packages/core/src/commands/structure/rotate-zone.ts create mode 100644 packages/core/src/commands/structure/set-floor-foundation-height.test.ts create mode 100644 packages/core/src/commands/structure/set-floor-foundation.test.ts create mode 100644 packages/core/src/commands/structure/set-floor-foundation.ts create mode 100644 packages/core/src/commands/structure/set-room-floor-construction.ts create mode 100644 packages/core/src/commands/structure/set-wall-geometry.ts create mode 100644 packages/core/src/commands/structure/set-zone-edges.ts create mode 100644 packages/core/src/commands/structure/set-zone-intent.ts create mode 100644 packages/core/src/commands/structure/shared.ts create mode 100644 packages/core/src/commands/structure/structure-audit.test.ts create mode 100644 packages/core/src/commands/structure/structure-store.test.ts create mode 100644 packages/core/src/commands/structure/structure.test.ts create mode 100644 packages/core/src/commands/structure/transform-zone.ts create mode 100644 packages/core/src/commands/structure/validate-mezzanine.ts create mode 100644 packages/core/src/commands/structure/vertical-model-c.test.ts create mode 100644 packages/core/src/commands/structure/zone-crossings.ts create mode 100644 packages/core/src/commands/structure/zone-drop.ts create mode 100644 packages/core/src/commands/structure/zone-insertion.ts create mode 100644 packages/core/src/commands/structure/zone-legacy-transform.test.ts create mode 100644 packages/core/src/commands/structure/zone-transform-content.ts create mode 100644 packages/core/src/commands/structure/zone-transform.test.ts create mode 100644 packages/core/src/commands/structure/zone-wall-merge.ts create mode 100644 packages/core/src/hooks/spatial-grid/wall-elevation-parity.test.ts create mode 100644 packages/core/src/lib/__bench__/structure-preview.bench.ts create mode 100644 packages/core/src/lib/__fixtures__/joint-merge-rooms.json create mode 100644 packages/core/src/lib/__fixtures__/mezzanine.ts create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/README.md create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-10.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-19.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-21.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-04.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-13.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-16.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-22.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/README.md create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-01-level_eodfbqctw101ntkx.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-03-level_jed5kaoexwb8xvuh.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-05-level_jkmni52gfrkgddfo.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-08-level_4jr4wmtf6uevuduw.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-09-level_t3oshtg9z9weuhvz.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-11-level_0xnyuk0r705m454c.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-12-level_v7ocab71p8y3f2x9.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-20-level_uqfel9edw0c08f4a.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-23-level_588ekegw4cj0g7zn.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_jwi4ovhyra2ayxa5.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_tf1ug5dswkkzfhqa.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-27-level_q5k3omsgkch1zjp1.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/review/legacy-terrace-pad.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/review/scene-06.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/review/scene-07.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/review/scene-17.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/review/scene-24.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/review/scene-26.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/scene-02.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/scene-14.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/scene-15.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/scene-18.json create mode 100644 packages/core/src/lib/__fixtures__/plate-corpus/scene-28.json create mode 100644 packages/core/src/lib/__fixtures__/stacked-walls-doubled-span.json create mode 100644 packages/core/src/lib/__fixtures__/structure-test-06-walls.json create mode 100644 packages/core/src/lib/absorb-wall-separators.ts create mode 100644 packages/core/src/lib/canonical-opening-ring.ts create mode 100644 packages/core/src/lib/ceiling-children.ts create mode 100644 packages/core/src/lib/ceiling-surface.test.ts create mode 100644 packages/core/src/lib/ceiling-surface.ts create mode 100644 packages/core/src/lib/floor-construction-lift.ts create mode 100644 packages/core/src/lib/floor-footprint-creator.test.ts create mode 100644 packages/core/src/lib/floor-footprint-key.ts create mode 100644 packages/core/src/lib/floor-footprint-name.test.ts create mode 100644 packages/core/src/lib/floor-footprint-name.ts create mode 100644 packages/core/src/lib/floor-foundation-datum.ts create mode 100644 packages/core/src/lib/floor-foundation-stack.ts create mode 100644 packages/core/src/lib/floor-intent-changes.ts create mode 100644 packages/core/src/lib/floor-levels.test.ts create mode 100644 packages/core/src/lib/floor-opening-footprints.ts create mode 100644 packages/core/src/lib/floor-opening-intent.test.ts create mode 100644 packages/core/src/lib/floor-opening-intent.ts create mode 100644 packages/core/src/lib/floor-plate-id.ts create mode 100644 packages/core/src/lib/floor-plate-paint.ts create mode 100644 packages/core/src/lib/floor-plate-support.test.ts create mode 100644 packages/core/src/lib/floor-plates.ts create mode 100644 packages/core/src/lib/floor-room-faces.ts create mode 100644 packages/core/src/lib/floor-step-finish.test.ts create mode 100644 packages/core/src/lib/floor-step-finish.ts create mode 100644 packages/core/src/lib/level-footprints.test.ts create mode 100644 packages/core/src/lib/level-footprints.ts create mode 100644 packages/core/src/lib/level-name.test.ts create mode 100644 packages/core/src/lib/mezzanine-audit.test.ts create mode 100644 packages/core/src/lib/mezzanine.test.ts create mode 100644 packages/core/src/lib/node-ancestry.ts create mode 100644 packages/core/src/lib/opening-floor-datum.test.ts create mode 100644 packages/core/src/lib/opening-floor-datum.ts create mode 100644 packages/core/src/lib/own-floor-intent.ts create mode 100644 packages/core/src/lib/own-floor.test.ts create mode 100644 packages/core/src/lib/plate-corpus.test.ts create mode 100644 packages/core/src/lib/plate-recovery.test.ts create mode 100644 packages/core/src/lib/plate-reference.test.ts create mode 100644 packages/core/src/lib/plate-reference.ts create mode 100644 packages/core/src/lib/plate-riser-ownership.test.ts create mode 100644 packages/core/src/lib/plate-step.test.ts create mode 100644 packages/core/src/lib/plate-surface.test.ts create mode 100644 packages/core/src/lib/plate-surface.ts create mode 100644 packages/core/src/lib/polygon-boolean.test.ts create mode 100644 packages/core/src/lib/polygon-boolean.ts create mode 100644 packages/core/src/lib/polygon-label.ts create mode 100644 packages/core/src/lib/room-drawn-floor.test.ts create mode 100644 packages/core/src/lib/room-drawn-floor.ts create mode 100644 packages/core/src/lib/room-floor-choices.ts create mode 100644 packages/core/src/lib/room-floor-feasibility.ts create mode 100644 packages/core/src/lib/room-floor-plate.ts create mode 100644 packages/core/src/lib/room-graph.ts create mode 100644 packages/core/src/lib/room-holes.test.ts create mode 100644 packages/core/src/lib/room-name.ts create mode 100644 packages/core/src/lib/room-topology-index.test.ts create mode 100644 packages/core/src/lib/room-vertical-placement.ts create mode 100644 packages/core/src/lib/room-zone-adoption.test.ts create mode 100644 packages/core/src/lib/room-zone-adoption.ts create mode 100644 packages/core/src/lib/space-detection-invariants.test.ts create mode 100644 packages/core/src/lib/structure-commit.ts create mode 100644 packages/core/src/lib/structure-json.test.ts create mode 100644 packages/core/src/lib/structure-kernel.test.ts create mode 100644 packages/core/src/lib/structure-kernel.ts create mode 100644 packages/core/src/lib/structure-preview.test.ts create mode 100644 packages/core/src/lib/structure-reconcile.test.ts create mode 100644 packages/core/src/lib/structure-reconcile.ts create mode 100644 packages/core/src/lib/terrain-source-persisted.ts create mode 100644 packages/core/src/lib/terrain-support-query.ts delete mode 100644 packages/core/src/lib/wall-bound-surface-follower.test.ts create mode 100644 packages/core/src/schema/nodes/floor-opening.ts create mode 100644 packages/core/src/schema/nodes/room-fields.test.ts create mode 100644 packages/core/src/schema/nodes/separator.ts create mode 100644 packages/core/src/schema/nodes/surface-paint-region.ts create mode 100644 packages/core/src/store/derived-node-guard.test.ts create mode 100644 packages/core/src/store/derived-node-guard.ts create mode 100644 packages/core/src/store/derived-writer-allowlist.test.ts create mode 100644 packages/core/src/store/floor-opening-live.test.ts create mode 100644 packages/core/src/store/floor-opening-write-conversion.test.ts create mode 100644 packages/core/src/store/registered-node-defaults.test.ts create mode 100644 packages/core/src/store/registered-node-defaults.ts create mode 100644 packages/core/src/store/use-scene-floor-top.test.ts create mode 100644 packages/core/src/store/use-scene-room-invariants.test.ts create mode 100644 packages/core/src/store/use-scene-room-migration.test.ts create mode 100644 packages/core/src/systems/owned-floor-openings.test.ts create mode 100644 packages/core/src/systems/owned-floor-openings.ts create mode 100644 packages/core/src/systems/reconcile-owned-floor-openings.ts create mode 100644 packages/core/src/systems/slab/__fixtures__/doorway-steps.ts create mode 100644 packages/core/src/systems/slab/__fixtures__/floor-step.ts create mode 100644 packages/core/src/systems/slab/__fixtures__/raised-room.ts create mode 100644 packages/core/src/systems/slab/ensure-slab-openings.ts create mode 100644 packages/core/src/systems/slab/floor-step.test.ts create mode 100644 packages/core/src/systems/slab/platform-audit.test.ts create mode 100644 packages/core/src/systems/slab/raised-room.test.ts create mode 100644 packages/core/src/systems/stair/stair-base-elevation.ts rename packages/{nodes/src/stair/floor-stack.ts => core/src/systems/stair/stair-floor-footprints.ts} (93%) create mode 100644 packages/core/src/systems/stair/stair-opening-movement.test.ts create mode 100644 packages/core/src/systems/stair/stair-rise-query.test.ts create mode 100644 packages/core/src/systems/stair/stair-rise-query.ts create mode 100644 packages/core/src/systems/wall/__fixtures__/wall-frame-golden.json create mode 100644 packages/core/src/systems/wall/wall-finish.test.ts create mode 100644 packages/core/src/systems/wall/wall-finish.ts create mode 100644 packages/core/src/systems/wall/wall-frame.test.ts create mode 100644 packages/core/src/systems/wall/wall-frame.ts create mode 100644 packages/core/src/systems/wall/wall-justification.test.ts create mode 100644 packages/core/src/systems/wall/wall-merge-finish.test.ts create mode 100644 packages/core/src/systems/wall/wall-reference-line.test.ts create mode 100644 packages/core/src/systems/wall/wall-room-sides.ts create mode 100644 packages/core/src/systems/wall/wall-step-openings.ts create mode 100644 packages/core/src/utils/__fixtures__/project_hrY3qVVq16yo5Out.json create mode 100644 packages/core/src/utils/clone-scene-graph-fork.test.ts create mode 100644 packages/core/src/utils/ensure-scene-openings.test.ts create mode 100644 packages/core/src/utils/ensure-scene-openings.ts create mode 100644 packages/core/src/utils/exterior-threshold-migration.test.ts create mode 100644 packages/core/src/utils/exterior-threshold-migration.ts create mode 100644 packages/core/src/utils/floor-follow-migration.ts create mode 100644 packages/core/src/utils/floor-opening-migration.ts create mode 100644 packages/core/src/utils/floor-piece-adoption.test.ts create mode 100644 packages/core/src/utils/floor-piece-adoption.ts create mode 100644 packages/core/src/utils/floor-plate-corpus.test.ts create mode 100644 packages/core/src/utils/floor-plate-load.test.ts create mode 100644 packages/core/src/utils/floor-plate-migration.test.ts create mode 100644 packages/core/src/utils/floor-plate-migration.ts create mode 100644 packages/core/src/utils/floor-plate-split.test.ts create mode 100644 packages/core/src/utils/floor-review-load.test.ts create mode 100644 packages/core/src/utils/frozen-floor-gate.test.ts create mode 100644 packages/core/src/utils/heal-plan-coordinates.test.ts create mode 100644 packages/core/src/utils/heal-plan-coordinates.ts create mode 100644 packages/core/src/utils/legacy-floor-datum.test.ts create mode 100644 packages/core/src/utils/legacy-material-slots.test.ts create mode 100644 packages/core/src/utils/legacy-material-slots.ts create mode 100644 packages/core/src/utils/legacy-opening-datums.test.ts create mode 100644 packages/core/src/utils/legacy-opening-datums.ts create mode 100644 packages/core/src/utils/legacy-wall-datums.ts create mode 100644 packages/core/src/utils/node-defaults.ts create mode 100644 packages/core/src/utils/normalize-legacy-structure.test.ts create mode 100644 packages/core/src/utils/normalize-legacy-structure.ts create mode 100644 packages/core/src/utils/omit-undefined.ts create mode 100644 packages/core/src/utils/owned-floor-opening-migration.test.ts create mode 100644 packages/core/src/utils/owned-floor-opening-migration.ts create mode 100644 packages/core/src/utils/reconcile-structure-on-load.test.ts create mode 100644 packages/core/src/utils/reconcile-structure-on-load.ts create mode 100644 packages/core/src/utils/room-zone-migration.test.ts create mode 100644 packages/core/src/utils/room-zone-migration.ts create mode 100644 packages/core/src/utils/structure-id.ts create mode 100644 packages/core/src/utils/wall-face-migration.test.ts create mode 100644 packages/core/src/utils/wall-face-migration.ts create mode 100644 packages/editor/src/components/editor/capture-level-picker.tsx create mode 100644 packages/editor/src/components/editor/floor-openings-overlay.tsx create mode 100644 packages/editor/src/components/editor/floor-region-controls.tsx create mode 100644 packages/editor/src/components/editor/floor-region-webgpu-materials.test.ts create mode 100644 packages/editor/src/components/editor/footprint-height-handle.tsx create mode 100644 packages/editor/src/components/editor/handles/handle-hit-priority.test.tsx create mode 100644 packages/editor/src/components/editor/handles/handle-hit-priority.tsx create mode 100644 packages/editor/src/components/editor/room-controls.tsx create mode 100644 packages/editor/src/components/editor/room-floor-highlight.tsx create mode 100644 packages/editor/src/components/editor/room-handles-2d.tsx create mode 100644 packages/editor/src/components/editor/room-handles.tsx create mode 100644 packages/editor/src/components/editor/room-highlight.tsx create mode 100644 packages/editor/src/components/editor/room-transform-ghost.tsx create mode 100644 packages/editor/src/components/editor/room-webgpu-materials.test.ts create mode 100644 packages/editor/src/components/editor/wall-justification.test.ts create mode 100644 packages/editor/src/components/editor/wall-push-arrow.tsx create mode 100644 packages/editor/src/components/editor/wall-region-handles.tsx create mode 100644 packages/editor/src/components/tools/paint-region/use-paint-tint.ts create mode 100644 packages/editor/src/components/tools/paint-region/wall-paint-region-tool.tsx create mode 100644 packages/editor/src/components/tools/select/plane-box-select-tool.test.tsx create mode 100644 packages/editor/src/components/ui/build-panel/build-panel.tsx create mode 100644 packages/editor/src/components/ui/controls/finish-swatch.tsx create mode 100644 packages/editor/src/components/ui/helpers/helper-manager.test.tsx create mode 100644 packages/editor/src/components/ui/panels/floor-foundation-panel.tsx create mode 100644 packages/editor/src/components/ui/panels/floor-opening-panel.tsx create mode 100644 packages/editor/src/components/ui/panels/room-construction-rows.tsx create mode 100644 packages/editor/src/components/ui/panels/room-name-options.test.ts create mode 100644 packages/editor/src/components/ui/panels/room-name-options.ts create mode 100644 packages/editor/src/components/ui/panels/room-openings-field.tsx create mode 100644 packages/editor/src/components/ui/panels/room-panel.tsx create mode 100644 packages/editor/src/components/ui/panels/shape-choice.tsx create mode 100644 packages/editor/src/components/ui/panels/wall-region-list.tsx create mode 100644 packages/editor/src/components/ui/right-stack.test.ts create mode 100644 packages/editor/src/components/ui/right-stack.tsx create mode 100644 packages/editor/src/hooks/use-selected-room.ts create mode 100644 packages/editor/src/lib/ceiling-edit-session.test.ts create mode 100644 packages/editor/src/lib/ceiling-edit-session.ts create mode 100644 packages/editor/src/lib/ceiling-region-session.test.ts create mode 100644 packages/editor/src/lib/editor-level-display.test.ts create mode 100644 packages/editor/src/lib/editor-level-display.ts create mode 100644 packages/editor/src/lib/floor-edit-session.ts create mode 100644 packages/editor/src/lib/floor-footprints.test.ts create mode 100644 packages/editor/src/lib/floor-footprints.ts create mode 100644 packages/editor/src/lib/floor-foundation-support.test.ts create mode 100644 packages/editor/src/lib/floor-opening-draft.ts create mode 100644 packages/editor/src/lib/floor-openings.test.ts create mode 100644 packages/editor/src/lib/floor-region-geometry.ts create mode 100644 packages/editor/src/lib/floor-region-session.test.ts create mode 100644 packages/editor/src/lib/floor-region-session.ts create mode 100644 packages/editor/src/lib/floor-region-snap.ts create mode 100644 packages/editor/src/lib/floor-step-hover.test.ts create mode 100644 packages/editor/src/lib/gesture-lifecycle.test.ts create mode 100644 packages/editor/src/lib/gesture-lifecycle.ts create mode 100644 packages/editor/src/lib/glb-export-zone-holes.test.ts create mode 100644 packages/editor/src/lib/hud-title.ts create mode 100644 packages/editor/src/lib/inspector-expanded.test.ts create mode 100644 packages/editor/src/lib/inspector-expanded.ts create mode 100644 packages/editor/src/lib/live-gesture-round-trip.test.ts create mode 100644 packages/editor/src/lib/mezzanine-actions.test.ts create mode 100644 packages/editor/src/lib/mezzanine-draft.test.ts create mode 100644 packages/editor/src/lib/mezzanine-draft.ts create mode 100644 packages/editor/src/lib/mezzanine-messages.ts create mode 100644 packages/editor/src/lib/mezzanine-selection.test.ts create mode 100644 packages/editor/src/lib/mezzanine-stairs.ts create mode 100644 packages/editor/src/lib/paint-commit-route.test.ts create mode 100644 packages/editor/src/lib/paint-commit-route.ts create mode 100644 packages/editor/src/lib/paint-eyedropper.ts create mode 100644 packages/editor/src/lib/paint-pass-through.test.ts create mode 100644 packages/editor/src/lib/paint-pass-through.ts create mode 100644 packages/editor/src/lib/paint-region-hover.ts create mode 100644 packages/editor/src/lib/paint-region-mode.ts create mode 100644 packages/editor/src/lib/paint-regions.test.ts create mode 100644 packages/editor/src/lib/paint-regions.ts create mode 100644 packages/editor/src/lib/plate-paint-affected.test.ts create mode 100644 packages/editor/src/lib/plate-paint-affected.ts create mode 100644 packages/editor/src/lib/room-assembly-overlay.test.ts create mode 100644 packages/editor/src/lib/room-assembly-overlay.ts create mode 100644 packages/editor/src/lib/room-built-on.test.ts create mode 100644 packages/editor/src/lib/room-built-on.ts create mode 100644 packages/editor/src/lib/room-construction-commands.ts create mode 100644 packages/editor/src/lib/room-construction.test.ts create mode 100644 packages/editor/src/lib/room-construction.ts create mode 100644 packages/editor/src/lib/room-controls-phase6.test.ts create mode 100644 packages/editor/src/lib/room-divide-session.ts create mode 100644 packages/editor/src/lib/room-handle-drag.ts create mode 100644 packages/editor/src/lib/room-name-catalog.test.ts create mode 100644 packages/editor/src/lib/room-name-catalog.ts create mode 100644 packages/editor/src/lib/room-push-dimensions.test.ts create mode 100644 packages/editor/src/lib/room-push-dimensions.ts create mode 100644 packages/editor/src/lib/room-selection-commands.ts create mode 100644 packages/editor/src/lib/room-selection.test.ts create mode 100644 packages/editor/src/lib/room-selection.ts create mode 100644 packages/editor/src/lib/room-structure-commands.ts create mode 100644 packages/editor/src/lib/room-structure.test.ts create mode 100644 packages/editor/src/lib/room-transform-session.ts create mode 100644 packages/editor/src/lib/room-zone-routing.test.ts create mode 100644 packages/editor/src/lib/room-zone-routing.ts create mode 100644 packages/editor/src/lib/scene-material-refs.test.ts create mode 100644 packages/editor/src/lib/scene-material-refs.ts create mode 100644 packages/editor/src/lib/session-writes.test.ts create mode 100644 packages/editor/src/lib/session-writes.ts create mode 100644 packages/editor/src/lib/sidebar-panel.ts create mode 100644 packages/editor/src/lib/terrace-draft.test.ts create mode 100644 packages/editor/src/lib/terrace-draft.ts create mode 100644 packages/editor/src/lib/tool-cursor-icon.test.ts create mode 100644 packages/editor/src/lib/tool-cursor-icon.ts create mode 100644 packages/editor/src/lib/typing-target.ts create mode 100644 packages/editor/src/lib/wall-draw-variant.test.ts create mode 100644 packages/editor/src/lib/wall-draw-variant.ts create mode 100644 packages/editor/src/lib/wall-paint-region-session.ts create mode 100644 packages/editor/src/lib/wall-paint-region.test.ts create mode 100644 packages/editor/src/lib/wall-polygon-draft.test.ts create mode 100644 packages/editor/src/lib/wall-polygon-draft.ts create mode 100644 packages/editor/src/lib/wall-push.test.ts create mode 100644 packages/editor/src/lib/wall-region-face.ts create mode 100644 packages/editor/src/lib/wall-region-handles.test.ts create mode 100644 packages/editor/src/lib/wall-region-handles.ts create mode 100644 packages/editor/src/lib/wall-region-list.test.ts create mode 100644 packages/editor/src/lib/wall-region-list.ts create mode 100644 packages/editor/src/lib/wall-region-snap.ts create mode 100644 packages/editor/src/lib/zone-name.test.ts create mode 100644 packages/editor/src/lib/zone-name.ts create mode 100644 packages/editor/src/store/opens-in-select-mode.test.ts create mode 100644 packages/editor/src/store/paint-mode.test.ts create mode 100644 packages/editor/src/store/use-wall-region-handles-selection.test.ts create mode 100644 packages/editor/src/store/use-wall-region-handles-selection.ts create mode 100644 packages/editor/src/test-utils/immediate-animation-frames.ts create mode 100644 packages/editor/src/test-utils/live-gesture-round-trip.ts create mode 100644 packages/editor/src/test-utils/selection-harness.ts create mode 100644 packages/mcp/src/tools/floor-foundation.test.ts create mode 100644 packages/mcp/src/tools/mezzanine.test.ts create mode 100644 packages/mcp/src/tools/own-floor.test.ts create mode 100644 packages/mcp/src/tools/scene-query-holes.test.ts create mode 100644 packages/mcp/src/tools/structure-tools.test.ts create mode 100644 packages/mcp/src/tools/structure-tools.ts create mode 100644 packages/mcp/src/tools/wall-deletion.test.ts create mode 100644 packages/nodes/src/ceiling/paint.test.ts create mode 100644 packages/nodes/src/floor-opening/definition.ts create mode 100644 packages/nodes/src/floor-opening/floorplan.test.ts create mode 100644 packages/nodes/src/floor-opening/floorplan.ts create mode 100644 packages/nodes/src/floor-opening/triangulation.test.ts create mode 100644 packages/nodes/src/separator/definition.test.ts create mode 100644 packages/nodes/src/separator/definition.ts create mode 100644 packages/nodes/src/separator/renderer.tsx create mode 100644 packages/nodes/src/shared/erase-preview.test.ts create mode 100644 packages/nodes/src/shared/eyedropper.test.ts create mode 100644 packages/nodes/src/shared/swap-preview-material.test.ts create mode 100644 packages/nodes/src/shared/swap-preview-material.ts create mode 100644 packages/nodes/src/site/sunken-room.test.ts create mode 100644 packages/nodes/src/site/terrain-holes.ts create mode 100644 packages/nodes/src/slab/__fixtures__/ghost-scene.json create mode 100644 packages/nodes/src/slab/__fixtures__/raised-room-scene.json create mode 100644 packages/nodes/src/slab/__fixtures__/sunken-pit-scene.json create mode 100644 packages/nodes/src/slab/__tests__/construction-lift.test.ts create mode 100644 packages/nodes/src/slab/__tests__/doorway-step-paint.test.ts create mode 100644 packages/nodes/src/slab/__tests__/erase.test.ts create mode 100644 packages/nodes/src/slab/__tests__/finish-swatch-parity.test.ts create mode 100644 packages/nodes/src/slab/__tests__/floor-one-render-regression.test.ts create mode 100644 packages/nodes/src/slab/__tests__/floorplan-ownership.test.ts create mode 100644 packages/nodes/src/slab/__tests__/ghost-floor.test.ts create mode 100644 packages/nodes/src/slab/__tests__/mezzanine.test.ts create mode 100644 packages/nodes/src/slab/__tests__/plate-paint-parity.test.ts create mode 100644 packages/nodes/src/slab/__tests__/plate-paint.test.ts create mode 100644 packages/nodes/src/slab/__tests__/plate-render.test.ts create mode 100644 packages/nodes/src/slab/__tests__/raised-room.test.ts create mode 100644 packages/nodes/src/slab/__tests__/step-geometry.test.ts create mode 100644 packages/nodes/src/slab/surface-split.ts delete mode 100644 packages/nodes/src/wall/drawing-mode.ts create mode 100644 packages/nodes/src/wall/floor-step.test.ts create mode 100644 packages/nodes/src/wall/justification.test.ts create mode 100644 packages/nodes/src/wall/live-gesture-round-trip.test.tsx create mode 100644 packages/nodes/src/wall/multi-reference.test.ts create mode 100644 packages/nodes/src/wall/paint-plan.test.ts create mode 100644 packages/nodes/src/wall/paint-plan.ts create mode 100644 packages/nodes/src/wall/raised-room.test.ts create mode 100644 packages/nodes/src/wall/rectangle-tool-sfx.test.tsx create mode 100644 packages/nodes/src/wall/split-return.test.ts create mode 100644 packages/nodes/src/wall/wall-batch-canonical.test.ts create mode 100644 packages/nodes/src/zone/renderer.test.tsx create mode 100644 packages/viewer/src/components/viewer/registered-systems.test.tsx create mode 100644 packages/viewer/src/lib/terrain-perimeter-fill.test.ts create mode 100644 packages/viewer/src/lib/zone-geometry.test.ts create mode 100644 packages/viewer/src/lib/zone-geometry.ts create mode 100644 packages/viewer/src/systems/ceiling/ceiling-system.test.ts create mode 100644 packages/viewer/src/systems/level/shadow-only-levels.ts create mode 100644 packages/viewer/src/systems/wall/__fixtures__/wawa-house-openings.json create mode 100644 packages/viewer/src/systems/wall/wall-finish-data.ts create mode 100644 packages/viewer/src/systems/wall/wall-finish-geometry.test.ts create mode 100644 packages/viewer/src/systems/wall/wall-finish-plain-golden.json create mode 100644 packages/viewer/src/systems/wall/wall-floor-step-golden.json create mode 100644 packages/viewer/src/systems/wall/wall-floor-step.test.ts create mode 100644 packages/viewer/src/systems/wall/wall-justification.test.ts create mode 100644 packages/viewer/src/systems/wall/wall-platform.test.ts create mode 100644 packages/viewer/src/systems/wall/wall-room-corpus-golden.json create mode 100644 packages/viewer/src/systems/wall/wall-room-corpus.test.ts create mode 100644 wiki/architecture/wall-frame.md diff --git a/apps/editor/components/build-tab.tsx b/apps/editor/components/build-tab.tsx index 12e9cffaea..79cf7402af 100644 --- a/apps/editor/components/build-tab.tsx +++ b/apps/editor/components/build-tab.tsx @@ -2,12 +2,21 @@ import { RoofType as RoofTypeSchema, useRegistryVersion } from '@pascal-app/core' import { + BuildPanelAdvancedSection, + BuildPanelRoomsSection, + BuildPanelSection, + BuildToolGrid, + BuildToolTile, MaterialPaintPanel, + selectWallDrawVariant, + startTerraceDraft, TerrainSculptPanel, ToolOptionsPanel, triggerSFX, useEditor, useFloorplanMode, + useTerraceDraft, + useWallDrawVariant, } from '@pascal-app/editor' import { useLiquidLineToolOptions } from '@pascal-app/nodes' import Image from 'next/image' @@ -49,8 +58,10 @@ export function BuildTab() { const [mepOpen, setMepOpen] = useState(false) const activeTool = useEditor((s) => s.tool) const mode = useEditor((s) => s.mode) + const isTerraceActive = useTerraceDraft((s) => !!s.host) const roofDefaults = useEditor((s) => s.toolDefaults.roof) const floorplanMode = useFloorplanMode((s) => s.mode) + const wallVariant = useWallDrawVariant() const follow = useLiquidLineToolOptions((s) => s.follow) const toggleFollow = useLiquidLineToolOptions((s) => s.toggleFollow) useRegistryVersion() @@ -93,6 +104,7 @@ export function BuildTab() { if (type.mode) return mode === type.mode if (type.id === 'mep') return isMepActive if (type.id === 'kitchen') return isKitchenActive + if (type.id === 'terrace') return isTerraceActive if (type.id === 'roof') return mode === 'build' && (activeTool === 'roof' || isRoofFeatureActive) return mode === 'build' && activeTool === type.kind @@ -113,6 +125,8 @@ export function BuildTab() { ed.setTool(null) } else if (type.id === 'kitchen') { activateModularCabinetTool() + } else if (type.id === 'terrace') { + startTerraceDraft() } else if (type.kind) { activateBuildTool(type.kind) } @@ -133,60 +147,63 @@ export function BuildTab() { if (firstType) handleTypeClick(firstType) }, [buildTypes, handleTypeClick]) + const renderTile = (type: BuildType) => ( + { + triggerSFX('sfx:menu-click') + handleTypeClick(type) + }} + onMouseEnter={() => triggerSFX('sfx:menu-hover')} + title={type.label} + /> + ) + const typesIn = (section: NonNullable) => + buildTypes.filter((type) => type.section === section) + const advancedTypes = typesIn('advanced') + 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)} + + - {buildTypes.map((type) => { - const active = isTypeActive(type) - return ( - - - - - - {type.label} - - - ) - })} -
- + {advancedTypes.map(renderTile)} + +
{mode === 'material-paint' ? ( -
+
) : mode === 'terrain-sculpt' ? ( -
+
) : mode === 'build' && (activeTool === 'roof' || isRoofFeatureActive) ? ( -
+
Roof type
@@ -281,7 +298,7 @@ export function BuildTab() { ) : null}
) : isKitchenActive ? ( -
+
Kitchen
) : isMepActive ? ( -
+
MEP
(left.paletteOrder ?? 0) - (right.paletteOrder ?? 0)) diff --git a/apps/editor/public/icons/divide-room.webp b/apps/editor/public/icons/divide-room.webp new file mode 100644 index 0000000000000000000000000000000000000000..21dedbadbe0ca740346b1296d42def58e6aec1b1 GIT binary patch literal 9300 zcmcJzRZtuZ&@DK)2Y1)tZh_$L4DK$$Ex2oNcL_lUcXx*X!QI{62b=x=TDf%}_HDPT z`=R@xt?G1DA2m5?X+;_UKwC;&RZEp$2N?hWVEkwIQ2(Q1imI{+XaE4_P0)Mq1NSE+ zPa@Jjk`{NhEK*8t7+$Vk%_Y}=L?9-uH5NzkrxT&QmCFz7=gqi&1_{s?Nx-xkUqs}icHcdG`LHD9AdNjw^f&Ja55yNTx(ovUJyyzcWX`=jK z7A5wM6E}2YA>S7;i4jN*tSH=Q!5*SdslNk+Bs@+Z)49Ciomq{`Bz%*8QN!vwB<=R| zQPK7IUh7m~u_N?5(m?lEJm;hFjacTNTMn}okDU$s2<~%SjajN{A;OV0*;Dg^NPeXW z3z~F`ks*4+E50}c;nT(AJZ<1Xa;q;1Ict$9@}0n?HW}9H^Q_a$c6sS1c5MkT7x}Bd zbiP$8e9@L*p3);v$v1{B7i!H}zp=&&=}!($ei`T9w+-J#xUPgG#=GpxBIzP}`A4|x zo8g2C2OBzCFncgCAfe@~YU?KWD*r;L)l;ADc`!^M?45}-d&}${yLDZ-mZ`Ng+shy2 zMP;$~nSRY+_h6>Msp}a*ri4cdNsq|Bf{dDpQhwWXEcrQLIcpHNCDzMm8~Oy-K!xpL zK{}p$+iP3p(K3q;_OTS6I)@9ZsKcrLgsjcW?^*$_d?QW7nHR)@G1a^{ck+4rxs*`B ztIy7cY^t7(f?92saI z(I;|noLdC%%eYTldS}Og_IpL)hLV-&v_ljWq_vQffj_CzlP>weX8bJK9$9cTGWcGL@ z_gJKgar~f#+tt|Cd%6s^=u=Mnc=a{I6^nLz#-!=61*j|icfjI0A%1*-d#l0`+;Lk$ z_v82L{Ay$1w?Nyn)cYGK>2ekYU{MeVacu6P4_u^~!$l)#5}5=p3yfn-E(z$V-&#sw ztj1&hmkyt^O=R4zcBz-x_i(e=cnvAy){gL(k8O#=fB{6RIRv~;mF#!Q&nYE$ru(|+ zzDVycb9hOwCG-F@Lk^o48vf$L$=eotxpdvDMi+l(p3}(^n9R<-Jehxsd+XlYQ(7F{ zFCqG10V*r7bi%+gt5#rxq~ue)dYQ$g z){PxpKP7_JDJ746vJ@AMjjTcupY;}1?H0;^IMQiOTfFC#~ZE z4}7CG`w&P)c7A%KS*T0y;3zDCghv566U0J1c9(_9GbJTlbmT|4@`5qMJiTL_|2gWKKqr`XIz#%| zLKks!+B%R*^+IQ3B#2NkD+wWc5Z0gDof7CMf zw1)l7mCgTDVd_WzV=+TFfE=o5(x4lJ+kwPSNRPAKbqO|cH*wW>Hi;$eKbt8IOgX8_ zvKYXwJn5+zkwVh6SKZ?y0yybmGu4}KG7irIPiKsx>*Fd zD`qqPi^2fbNpvgPc~O}oag2|?_G!?_y;7{-g=bvmOwIjCD*|*CSYmoXvQfq%!&uZ0 zUm*6O)U{9L0G!pKneIZVY_4Ywz~oMmOA}N+T8gKujKFE0fxqW{GBF%v%ZqSH{pd|& z5H~puWl^Mro;cGiV0^F?KSJk}8pENV&ED5_Z{EW65lSJILZV<=$r^x-^{JH5IGqS% zUNUD^3!=A)->)2U6AUv_wp^A(MkQr1LB_=p_(WE(rW^{?DJxWi2cY?-MGlYSz!s49 zBNxI2#5jG=<@XG=$TiVV9lOnpW_xeXYtilQ?mTlHF-D zg)jJMSNyMW0V68cS>D7;#K#^>jVu(*2GwZ|hle9CW-q#3xB|n|5RpPGFR_zQs?wL> zbQKR|<0f}#9Skgfs}b4ySsPz0ERo?p0m>#medxmKx{#UMJylu^s1@x+*i z9d-?fq%4V1WvNhv^n3J0;aRYP5WQXwEvEh zQkIag5Y}W{{gK>UaXT)QuWY$7hcRbAQZUAEE6-Nra6xd(dap-B@245}E|A9m&*<3_ zztv8R=A~>hno$-^N@pr@dXtZR_0_%D>$5SDEFYG=P?E?yaa zHryRmr!3%(6t?R)I{5ej2TpCGZh5$2(<&IdOOYoG$;8@wM(qpGf?Ols^{WXoFlSeAdP_p}*hWLhcUl zzL099_v~%Q=BfEi)ak*n>4mlhOik6kH9en+or7o+(3?WC0)g#KCY0IhG21XmvZ}VYEQ{*B<-Cv zve{LW7Buak&>m@%*nEEM`f*Dmk+SJ2h}-W@M;ymDeerH*QTo|-(*ksl+S^&?$UP6h z5YQljLwCe1Bpt*I!zpsY%-6kYV<$mlL8C0DWeq7xeqdp4IZM!UQeqKaq%R;X-_$DwI-!b@Sb+5dTleV0UkzYtHrdCgRe#iJPG^GG}+>aphTo@M*i0H`dQ!>g-tF? z7m7c!OcK)akQ);CP3qs`W<4;+i$0#|>s+{7*KFoQz2tZzcIV<<%0#lk)M@j)b7K4@ zQW2NAA1q5`QJS49JxAACn!^z2q=v?=b21%guJ{&k7@U7o*f0NTy{j>sPA7a!JL)ME zC_Edx_#=lFdZEE7DN|GJdHRX+I=SWI!?7Dk8$V*L&9BU>Rmz^`7xVxA_uS_b+)x1i z`_w4X@c@9jTtFTa;{((Kl&~p#x=b-O6=iV~ePj?SlC|Tz^EU)G{`x%^{7*Kf-U$EE ztai$k{e|nZZIfP-K;0e-k^Df=N85AZBh*L2!q-L7t1olhvwC_DLsT?E{??yFmnzoeqS@psY3 zd=Pvc9zV7NqPi$VDqd#1L3Ic>+oypKkP+Vsi1{1#iO5~;lL)xG50Vn71F8NbUdvxX zxWca+JzHshLmc`P<7gpU^;Yc73grB>e4hYk+_N1SPyT=5GS$1zuPY3P-W&YevVPns z{a;y`YNskJ6p`=B}v_SgLT5>kAbu@;lRZq@>RwP(a61l{G{$+l% z&;46<)~p2i-SB_=Zs@q6Rql$K>MTB8LHXuK0xkXu;y7DM6it9~D~9&0Es{M@CxNod zXu}{lj$Rd^$XqP|d8=^4D)l7{ZM!7Q-TZ~#vX9AEtXY6Jh29Wj@o$kn^K9+5+x591&?Sf-sdo_>ss)|LDY`l+TKl)AZP4n&vbxN9{zpw9MdshO(k0cj zOa|&kP^_@H-(*JR8)}`q2ko-dyL5FCt`Fz3tT`500N$GH<38z#z_M0Cl@j1uCui(4 z0&ccP(^BbvEzVznc8Hg(rNv9@}Q<;@f z42Rlo`2d^P^fDuL0-Wv{c|UPy?_wS2p#*Ah3b45ITZLmVt}2a#9a-_UJp4aF8anu? z`~M4O|8Mwb^Z`C0PE-GJQ~#R~i_k*`1@LC=WH}-|7c3!GexHj7V~yiP)1MrkWthrS z-5mBNGsbV22L*3P{NV5$FUy5}fuA5|ZBRaOHDVJyMt{FUT-v#H7of}kfub5+FFy^t z4^?VDXl?vlCciWB4cutNZ8_5~3We)%}7Nj1upP%1Sofrig z@!;J=HP>73GdD&GsCN|hO)2yns5Z+SvpPw6OCg2$jm^Z-UPnONSML7n%s)ov-5Jl3 zN)_3iEAFNKilO_N+;eAJrL6nTURWQG_m?~&)~)km*%)E<%`*Jg-qMzix3yj&H+OB> zJ#4f?v=G}=W#Rrdp3f*RgNc~+Ls5IaXsZ=mVB3j+aY!=mYCt5fTf-xt4^kMIPFgI; z<%OoxMK|l(t#&4opFotaQ$}3C$YDrj*QSld8>N_s>&F!Ordpw(8{b6&o+O4gS^H2d#-Q!nX}cVG7sh(P27EA&hho9ebwe|=w5p4 zr=bP%5j8jd%8Zdtrj|{jql^6sQI~{;9n*bZK0v1=GsPK@pDXy5SF~WOot%+m%vp`K zKYb(W-e2DDZeN_&pC5b%I3y!Zkie1Rwd?|yhzaP={}{|fsuz0sg4qYC z1JXOHq-G8y+*1gx+0)-~J#6si``XneNF_P0gmoIf>W-^voykwd{yMrz_3R2sQv)Pe z8RJ^Q#b2S-n)FppgeHGUug~Sw*(G1b3(-e+gY~_JhPCOMl)md^(}Hr|Rc1iD+P68% z+p)Pfa&>d#*Ay-XO|m9(O22X+c;DO{eo8Ewa=WU~O{L6Ns>gBRBa+~b?7G?q^aV8H zEQQd{8>@uY?4=B+>C&qpAkLW;ezR#t5d#${)o>*JdG%mUZ~w*Ua!&Hp!SD^*Br8Ko z*kI=m<*R=_`3j95AC=e|<3-{(T%Gh^of?68-@}-J>?*N@UtxxT(pJFF4;J@)QP9z_ zR1ka492^zc^;=&_c<+h$8lE=VBvI_ug8WdOuu4ZA_C$+HU3!cTc0zIdf`l61&>c4<4gl}1UTt*V&( zKz*$jkEgVFHsQ~NBGwm-a93Qi`44g01yQ?Yd6gbA+A zdL7=kQlK#8goyYRzpaApV@jg`LZ=y*?YS)GmKGL@8w#TPb{m*Nja99W3St~4>$YDx zdsL#iuSH;c!}8(CIbTYS2pVE)GSQT1yeYUHo|k8fhT- zFCr&1)L5quqW<)v0e7YFoL_J$VdpPD|w2v8x2RS1yg|Fn!% z9I)>-TKe7o{Z^duW!Z*OO=AG`tmMljl^})msq5~uSc2!UzmEK(w20RrWcqgx4Nc!e zM-W5dJVu6zJd*jlTP_Z&#IPBj)!e4ZlE$>kjI* zPS>QX?a?xumDhC&^S&nXk`OmF$Jfz`I@Gh0P8S@~WIx1o-wveGE2^VPR_K1vVQ_p; zXUHZgM9_*v`Df^2V?>U}{LbCRx^M3t;H|jEUXq1LevFIs$=@o*iORT2ZZ5M|!ava> z@X?Fe-9Rz-k#8@Pj-&Ucb6W*ne##wNNgq+AtYXVcsuxV8rw8IIc~%eTG>jkA^WhX& zyqQLDs7m5mJCD`n>Net)eZ9f_n(3VtYm|om`SgQINwJZ*+W0hf_29D?0h?kXnR3TJL)~#xTVz^d@@T>k-XSkNiP+zssLzuK! z(CK!agAeG>nVUg1R?*4BqUzY?IDDTfDIwIT#B-dxGEV4o>vtKr8#vzG(JLCYPJ!)z zz3nKx8vaE>EFlxba9^-Qw+!<3R(Z86-?1NG;2O9t)RX^eS#MkmuYXm0ks%5O5*I^2 zo&*|uNOt$|`wOh4w;Mk7#A#lHH2Dk-poV)LDUwCD^gsjBn5r%zYPj*If<@{K zDmuXht=Pf5Wg!kJ3WkmN-IgD5gqSe}?WU}pwE%BTWHLAck-@bBDkz&?`(EQdL{SR` zjSp=Y*03OEBzG+>3ODn#3S?Ua@|D%CY-cW>h`pICalcdYmlx#-lxyoFQEWgwV6483 zX4ESf^{4fT>DF#KT32zDtlVJJLY7T+t?_{mfpe;eus(6dSU6{UY<^jEslZ(jtqGp; z{c~xo?Bg4yI)Xr(B*|pKg6&H$GMw+x7*fR(9NmV? z!yFQAVnbkCAugX}1Yq1oa=H$Da^}(HJA}VUuqk9GMLeSyN%p5eO&AaKC;1(#wyjT% z9WJ|^2%xvSH^}7BBiOl5+Z?o03Wmi?rEZW8;`es{8)QN@Or%e{0o?V{XQ?=vC>iqteiC*E* zpRH9!it~S;>eJFUBy>o#vGyDvM|f4x1Tq#fcXw*c$>!0F8g^9Zl_Y9;tfr&BCJNGZ z+&Civiz&_~Mji)O_#a*LpZM+xW{*)FS873a)82RuYcF(c&OZUL?1q#8M(dzB9NFpX zerdt=&2Kw$BRJk|sTx9jNB35NnzrQ#V7cg`dn8D`!|Lz~ONc+$IKmL(F!{ME2yQelmL%j?R z?@^_=zWQA>H;PBZRP%X+7Dglbbkjb^HCMP8zCuOmA=DimR@C^l@9iajf-zTZXITq8 zBTW3GuP%R6uNdRGLzvh1$1H)Y%1puD@p8OFzZoSRe-Y4pxi4g&;8Ft8$>;Jfz|io; zV0X()c+}4mXNowEQpK62_f?4oC=n!mL2*aYV_mdyy!z+DSl68fCo>qXRuEqmBK#FD zf&(arg(7eMo1t}-`$sS`>F9y=y*3?l!EnQZZ)e^IR)(F@Kjk0^Z^*Ve1tg50uNL|h z!~LH!iwuR-V@GcqU-BTyS=$S$)?NV9)G(JWOsIyoWV2zFZj1h?IG=(7I(5AsAg{Nr zJB?4M^%(moRYC$QvS07!Myn4YIpfK2m2in#K{B=D31{eDDwyPFMjX#H^OQL4V#GF{mG(>YBVr6_DJn{ z`%JF-5Z&e4OijM_WI(iG^^sL~m0Mh%qxDn|Ka4&6JWVm4Ak|1WqS{fRj^t5g72`QK zTeEPF>0K8qqDM^WAPssG2fQ2&wJR^Skgs=~Uy6P)#j6FxZ`l_d&JOQjmnU!;`H;QG z1{3r>6U^QMZ1hmX#tkkG>fdhvV)@0SX%ZqC2*q8#LQ&qX{+2xS-6MGf6Mf|ic#B2) zBckFUOwEUKDhF8Q3&8Hm?4mwP4ublc`tOXhF{>m-L-5L-vqX0;GYP%21A~ZbRmAyT z>kBsX8EWUSo>nZ>tt$`LbQ8#U#qn8?Z#{K33*7PQv2qFGp5=!xAgeL6Q%Btmr29)L z2dsVl9f?V?q6NAoyctvw&6}(CH>>(URFr|ov0Zw(>$N=R1|_cpo6ginv+M9h>eEga z621s3|3|}d{rsM5CGUq7rox;$DHM%+i5cm{j7JMx^UQrRjxqIr4&KGXJUsXfehIm| z4YLe6xKDBG*m{SWv6Y38jUuoVF;a81u^-u4U!UgU0}R~1BZ4b0ns;X1nDidI-oAve z$J{%CbCfGLd%E%)%{8o+&(>roVWtJPmM!fBSlFo>!+7>9-DDf0tBXLC+|MAvt$-Ew zQ%T-{zq`e%t|<07W=)@vP~(4ETa^~Y6?GmZpZvLnmao^M&pb%I@g+6u)w2KqjDhJh zt3M2^AJf8lwRsYq$1OLRPSd|%_cA2W#7JO@P4O4MlZams-dn3e+E}h-jv4%!^Twx9 zuwC$r$Z|GpN8K(0K!Mj`*~d%d)5h&~O|=1U;XH)Q5c%2m#i#?i^|vGESw`4hnCZA! zL8~VFb*Ov|{Fr(6zTAx=1iFm_7Ed`xALZU=IkYt;OCU z+mOtSfoe%N7xvvdLmS?QoILZk8jR$`^6b{63hk*y7qExB9vQ_c0+!LP|dW4Ckau3Bz@{n;t@tS(d$Yk zG1;|{-j{?=AuohOtU!N+;RCC9>g<=Z$ic_6ek>o!4Hxr9Ink&E0wRR)9x{HHdG~Rg zR&E$UaYH=oP%5Cb_-z}Cl0FgF{VA>7ly8MTiWv4wly*9$s5Zy(Y(B30#GR-!o?Bm{ zkaO8)eI?LnPy5Yb$*(Iwe_qIBe1R{EKX6eST9S;#5F#{AoBozsuJHoQ+>&&^>jjH3 zOkeFjY{Xa5PK}VFsiQTYw_XQ;3{e%m6VuZ3w=qOhzh}7a%)i3TyJrX?fA%^vH~G*9 zwRjVc7mi*i8Z3;QeZ$#wv9Aj-O9bf~A=ItDd%>qJ?z$@taV9k%^qa<6bDO%8UwE|@ zHz@jmjNkcLJOt9ga=?`Kb#U~E4Kebd{Pa;(AQIin@OEa34v|U7&MisMPJi+Q#x*CK z>))UjQk8JkqA@j@_XPX&tDm+24&QC44t~sJlur^vGNr^EZr3$VYL09mVvZt^FPi>| z&yo9$m(_TtN)XXrbdiWmkVQKW=G^OLC8iCmjlG}egulyZK>)*6cZ!^kr-X={L2;te zjDQoz>xD=s1tnPcRy!YV-sM_j^!)|`3IFAi;texzmdNH!2@mL3urBy5VWz5uH_{E? zj_I*{863UKd`>7tOI98KXkp1QOUc4;mR#sUbuiS~NHCZ?UaQ7v;BrHrgJdEuRe}&T-OLXsD3e0qnp_d^)wM0icV8=lP0jP8@K{xAYLQz-`;t^44JGW5A{X?+eQ44V^z z%!7N(-fW)SJ&w5nRO`$Qj_gU+JY**nM*!N3S>rIKa|g7;0Sxa$P9*h$8Q{!IJG7l= z2;er1+Sx_bhv(_;nkJvo-nn(p!N|5V6e}0$4x%1pp+pF z+)#A{MkDnp|d6$F9FGp6H4iRkxT0z4bd|W zPoJbu>vw8dOO+&wlzR$f=4Z-0s&@&&VP`k=V322`8LL-!U?24h#7LQt*_rhdmS`9i*sk%af3X&9*vw4OMn6Qc?tT&vehYQBP z8u7KYB?(%ccqy}BoPOw6Fl>4w&FZhmC=CUBKsUDEv5eNs0*JBuo(2(R$%kiN-39xP zzv85u(gwD2AWB2InMN;W1n2O45*jXkfYH5CPS%-D;n--w^8<=3w%FQeH~!%pLUiF8 z*K(WMio>vszd3n4SA*{xybl^Djnlj@Cu<`?ZEp=?Izp&9`5=TsC421XUO%CbD`GS? zZ0}7a`tG-SX#|N6S4IN3*e85uiS~ZQ70@?8<2`A1}GjqmvYCCmUkwuD7hJlX>y3HUB#ToRF&=MUe%1X@vAP_Ix z1S;4F^FQcIl3RrSQBp(+=q6w5iBCvg6qmJOSm|*>BsWt(K`26e@hWe^ja?u98-rwx z2Lx9oDdMl!6=Op~nZ0^0@iUn;zM!0(C;$!UFuxpPmUaLF;D}S~RSOfAU6akGlCPqi zi@hev6B$PDDm8^97_nU($%&$KO72)#$SBTp7rlFo%;p6ei?c%oU8~9HEQkdBkC(D+-YdyTiKl)w!S{NB1ecQ5tI9X`mzTnj#{qu zwQbx~Ce7O9i1TPySH_Ht&RK+@^JV&<9(=Uj=>rzi9hy($+u{8-eAGR9Yz=4Bf31cn zVw2Ot9(qtBx{Y*Jg(n}eR9bZdU6x%XLG@xXhk|b?eEZRRhg&GtjI<6nBqxU=XH9-9 z$@Wc;OnR`21q?dEc<};VsuPlSW~${%bOqyyejOGq{*@oojlg1w`uP1l zQt1J!N!{{xa-VW0P4my^Fn@Ly2?2H6XV}bNd>)QSRf<9qYHo}d3yhigQLx0nSP?^U z*j|}Y6A+XNE`dgt7Ep28uIx^28dE&-;_EcI8E^ht>!`qQadg`6Rut7-87k^A&q zLPwP~*AVAE(MvnyI0TJnk;*PR=CSPW+I5jh6=Ck)*E~3cFRZf!h&H>I;(#A4W)#Q|*;B^iHVVHPomIWY#}?Y?20Fdao0d3WbqxlqKJN`u#)#41Mc?%T|W&)_Ncp`*j%R zxce4$uHPn#7y(Qf`{!om?E%(eu;&%!nCNHCF$TBoAHX7wr2&u6C4vkoe%*q@R+4S0 z2acb$&7r+)zpr4jzZ6T63_iL;P~cB5W4U2yV_JKEW1 zTVau#Gtgp%<(ELDqHeN>rGtyi2b+Loa=x)rnv3*Cg);`;xlYI88v<$U>2njDYJIjf$1Wb)lkTAE|i1BZAVB_Enc~my80yzPZ}tTo;x` zvX+CpEzl+-`BL=?Cy~z;>!Ob1`f)b@4~O(4WV|lwu^febePkb1`|n$#3nt#xr#xci z!8i||dNWy<8X|;gmxTrURi1hu*&Q)6c@gI2PiXD-<(jW%D^&a^x%f{yGB%dwrcddc zTI9dB`2uyw_{NN7f;(=}JuV8d6!4?I4!Nm+qdA+pFb`_fV3K{bP41@Q)SY1U?KHfP_M6@AHWw7IR5DJdhks6di1*H4}@{O!eFo!_!;<$f`n~pDzl)Z z=lWmLbu#-7J)TdFTjq)Bzty0fPa_Z8rr0~Mc_|Bt1=z$(>GjP+&y$lW_3uwhFMM4t zuTxJ{f$c$1oQFbd?qQMv5(^Boc%I1rucP^iCEYhI6yCG)W3rTP2Dk*+4IZt+R?IQ} zA(;*7e;grpev;dZ_=OfC!qDE5lXs>PfQ~Uu)6oHZbDMWC+_Cu(d1ZcDiV&QP2PdtJ z3TTg%{6Gn(;#FjhjHqAf6drWGMZA$=q|Y88U?QD~?v{l2%UCtWg_E%$JKF-EZA0_X zs!I2sG@e>Fe#XR@Fda_PWSpn#&H_=L}WB59l;MdjKrHY-SdR2>H`9gD+ z508UfuaiC8YXJ&c138#TKgB*ygClw`YTg?3ESPJZTq}==cYe;B)w|1a=KYd&()nxN zw`QU2_Fu*=j}pW%?(hZDa_}m5mj?^X5ELrU>8*(p(&wCbEF2+DM7#;WeB;WcazNNw zp5C#HEAP()evDxPg?o90njd^K&tiCEhxV&KjKD>d!bO&=3TxI zRgEifH!HeD6A<@Ls)020f+})Xwj$H?FLz3ZqA^@<6NR^%$&Z|h+0ZS?@K^_B_IB0d zH)WLQ?@=26LuxcS=p7~4kD9p=emh&H+U-6BI~LIauKc{7f$_O~D zhp89`+cN&4Ti99gnP6gj4F{>S;=iH#|I^q%iD3c&USTs)e}7K?J5Z+|ly_c<(_;3N ze)oXMCrY9i=Bm|)8i)F)0HkAz3IlWAWb}T{@`Fc`b{@Q{R@voZwAZ=|mhsAtNG^k6ycGP)?FGu4U5~V#?F@kw2_9v(zrj~ z$jWvENxUF@?H5B!Du1Szyb8CUM5V4Tl!J>He`V7`rMi!`C!F7Q;Z32>@!_TMsa$~~ zGXH7q!aeBR68@6n^jSph{G!pJ&&Bd!-%xa{&m7+-U?d$AXMD^e+)huf+XIhi*xc_6io;CHe1Y zo}iTXF%I@>?dx<6Uwie<9Dr z7{OSutp9yb(7r(_eOOF7+SUBAjl4a57Y^AA7n|yc)YW~+>kC;hHyS^BK7en(H#b8L zArq}TI5oSF8c6-wV5QvPi#Ygr!rylPVlf&@+}?_k%=+|Emn*(t|E( z^O$SALe_XmHCv}!sikm6UXwR@~ zK@h(g?DhU>3NqQ-(dr27rr7EfpVrwgsDLj;rWv7d`r&y%PCB`0ja3iTP3s%asvG>n z_rXb<{3+nh@4+C);2KCPG4;c+*FjK7Czx-3qW|;z5QINgy_Xr~^PxCJ!$+SQ-lf>P zUoIGZ9lXV#;P|~N0G=(dBCz}}UvRl`i|oBnZ@c2qS?Fgi!-l8N%Ik~G-V?mOmDw%F zdvu2*lo(INsLoHb)$Oz}D)J%Cwn^14Fm|FRcb>Fp;^%{+$JIw&r`4qlLewFKyk;06pqSoxWd5QNa2|{27Z6xX{ zAL;ZWmMD{WQn0i!qYubYIGM2iji-;6bXinnGvl(5@BQnHKxtuGI-y@I!o?TpXp-If zqyjQKh>kgCRAUy9O$ORW3Xu0Gxwc0d7g1prhu2O`Ax3Cp_;WK?+mhQ)4&^T4e>y(L zt36YB`KZepqGwJ1Y|Rx?XmTYViNB0X-pC+vE@104@ix!wGH3jH=U6}RjSDNNAShbK zJ=u-?)cdk_ZYp3X<=c03@QdgE;0`;d&5b%IWee61*|br!;*$OG$tchZUQ_`m;LAQ2 z6-Pv+-}zIG$CR11)uz(7we!esa$*{pm3WxWfx9hR?P=ykNeJ=jej@mWd1xV?25*XQ zvB4^o(+QHMbe^d~ZUjpi@kSFPfi(EhKTo{z6`8#BiV-f&oSCU=>KL`p!lxNCJ9#%t zX6CWok%S2VcK;#aSXt_L`mIg9h9c$%MYYlizMbAYctpj`6Qhg`&F0XmIib)oErQ;cN)^rDqSY}`^Z+x$% zO;wS^sbTuv`?a$WIpJG(=$Lx0oZ5mGwVqDrF4-R28+1^Xd&B~hv1|E0E|`!6hn%i7MaTvfV*JsBraU&-*A#U-V#OLCl6ygk~0X%BMZi z@>uF$z9iibw=N)TDceEQY*AVRN<^Dc_pYPw*MR)sO0I|u#$1GF9R#9q2+L&x(0}a9 z1Stu$pZV-LZL<;u8#9YA9ka)O3rgKJ4cc$kH*koj{)~62&8{X6RJzp@kDDBo_gbJP za&?9$PzZMsu~|#Bi7}?*#MuL6KN_dv>9s09gNXS#LWvvLVn^SDbXs+t2BoDO49V7V zN^T0F*gv-5b^5H*XBuS0)bFO>AJ)Eqxs{1#m+I2z0TVc2G!rnp{{HItV9L!__hV2o z<7+eQ018|hu>M1(R+}}SbUeXb)K3+Bor1;>E5V^!d03#T#$#m8iIC>-V>4uJTG7VGt3fyU&H4q&d22F*}gU zLGU8mmMyOb2EM3D`CCA5u445B!mDt~- zyZV}h1wEqz*Fah?JH6Zp}jIIRNSDGx4a*^al4++U6iWPm%G@r{#_=TbClQ?PS z7USms!BaFwoBfADyvk=QsAR}bkNitp;X#qQWY2P_>>~q%@emDSW=Z9zWKhl4f^ID* z{cG7ijH)QbVcnK@=qb?TZPaKxeK6sKpw_t+fq;;1McZ2pmY(C}$YkppjR#kTwwPSx za;2z*5}LWso)b;n^}&U9Z<3#SE@3C^2anki&xYQjrDf0nL>|_sWQ&!fC$QU< zoxpI$`E>TFauIDVV|pr<=&(*$U0`s81?)Q)PQd9S-ss?xsZPdKE8TAVOMI1TGZN1Z z^R?|@xl=x5cYT;kjerIYx$w;5<~s$beu-&LcoAmIyG^)6Hjhf zCO`l+|IUZ3(W-GN z5ft^tMJdCkn)`TxZq00KpVIkIoUGx1&n?I2+z7>w=APtC*dj=^UlIZ@CFzP#7>m1k zmNLIc>>rl$dRul4Ov!BS{cU#M^0Gu^IX%pBT7I}Dq;E+2&eb5?u=<<6uXWk*pp9+R#Kb+-5Dj#S`rN7Kk&CtLK7W^*fy3us|6@wRmHob-nLl-MQKyzu`t@M1y;r zivtq}OtIDDFPT2+!w(8?1*ffh-o4IzN0`W*5{Z!5D>5nS?pZ>fY$2Le_Z7Z)HCe5m%; zQ5V%ThL2@pzxaf~MDd#m-|P}MZB!bGvq@&Rmil8mC@=3C zMwW&);=HSRW-1!U`|+ZX8J78)QVS!hz|dvx=ncj$&)Z*0UU8}}Yf{gD00;&I5G??9 zq4OipB61he2|zPD>Oz7~gng*G7E-j)+s%qh{|w;j3d)+CUiJh*K69V1qQ^>+%~U(K zGR|}2&}9bGB37Vy$gd?duDIUqF5zokJQMfRV|@Hx?|d+9;r&s^lRJ)u@_5so)!~-h3^IdnA4e(N7jK3@ z+`_l=I><}RjDoPrTCgd}>X1;C=o2DXabMxlZWqfk44~X{ssn9HpI02=Q9B6mN5=OM zy5~_=EgV4`xp;I1<9HRUroa9ENnQVAp4qM6wz}T+wNx7Z2|LHv*RN^?Kyzeu;`c%c zdDwKkhP9q~P>GHY!p&?H4|kt@G94;C^LpVwzv_)4MSPk+KDE8Re;G4MwF&eHL__&|3Eue9sXQAtb=>UbSKwpcb#wJ~v@C z($1~as~-Lou^i|1Gv9L7p~;k3aVGv^ymp2_g}3DiI`*R}2RtzazpNIV6#+u;;ddq0fx#66 zy{rc2v`>;1>XOoUnM=)ysYfSHuiM*$Oute});{cwE5hoF$sT@OSUsUFe%DBcy>xXuZ~SZXft}qSH_RV7AEw%!D0<*Tv@e^6eKL1eTw6TZO2GjYj<+d6y`E{dc!|Z8~c4{}IAECh80WE4Kk&LoCJN&ec+J3w@ zbEG3wr<2Ytnzu9jYu*a|v9tvE8P%sjYa^Si0Y}zm;Ak>JUl?`x(;x<+9<1gO0JyXB zyNUU((~Q7cOC~T(iRk{Ql?+B!PU&21PBcVKnp5c#X}if=e#N{;L-lFvt`%FS-^7~1};WJ$6E~hBg2)G)%lnoRzn7!4sC%qiZb&%Kq=ff z#D{!9ocd%&qMw=48j(m&p)hc6Fs50NDGbSqfi1ybjHt4eg^L_DDO=D*gN>=p`FLGU zD5Ik#8Gs$MMcvpJ&EyN#F2&u8l^*WyR^WgF#oeJ$tQ2?m!`+?YQrxY$6gaH7A9An%yf68_ zm%O~>?d)cg&Cc%Z{$_rejFzID+z}%Hpf4+>p{F7A2^|0c;QkvoaR2F&DjEv-7ytks z;V;K^q3bvMGShEzLx?V!ZdJ{`FT4~V`XBThBeI;(`8p4&kd%|YETMN=qacF)J2sv- z&bAKExhQ=5u$fAyKgJW_#Zf9IW%aF3&IU-}5PCaf0;;^S9oIR|ibnGdJx7t4%^@Z` zyx-~5CiV;2e_MJLw%Zsl6NR}6v9{?Aa)o_lP2MYf$0C$=kYDJYCb!mPH6kizU1QKo zj@L-D?zE2VVqkwRlCA?EKMQ+zJ@`EHf5-(j3R+GHhS*TDd& z7L5M#390TEo~IC=>*goaf-ZgO^iU<6uSFH}C(7k9*M_h5yPDGeTK-F@P>;9Dw;Ag9 zgrWplR)nFK>R36{nq{eXXt(ME6I!Q9uThDrkNgd)oL96C{f`%V=_Hv|I}HeP&!$p zjpKMBk;oU}yjm2i-QPQ^K1YPj+ot+;tRcrXLGfRdd=K#Kgeh|tV|Ua~K55P@wc2Ev zrCiY;q%66%h`wbc$X`;ouvZ)?VezX>GCsyOI&BQ60?YmSP#>dtonA3DDU>+>`c=~R zYwL8;8?qAn)PE1B(fJGIZr36ZPqo5*k;-gy+*304zndNF0W?Viy{5Qo3B%+zjQ=9R zEz5e|4cnA>eb%>aMG5j)m7i03?X%WL0R&%`)S8T>imkXN@8huqNhvY#YHkMCv%aW%$e!|Mw4N-`v|Fw;}=kHDFa1`!`MZ$l`(!jkJ!# z-LRv%+mR@DR+_!_jQEo8Nn2suo4`S0IR=N|p`?C5a8fn2$7dx$wiJ8r+TS!pXUSTR zAl-3Rq=sFx@B~=%V?xfRnxAG`?kVaO)H(o8{z<@4@fRfk(n!vBgJ$lK5}2Ph;k5z- zk%XWUFyb}Rl7pw{71SI4)U`WAhFwo1jrttPNWlEsAH+^CF^~ z%i6a)#H{(L6BAFG7AKyzSI2fXqBd$_rB7WMxT>gVpzkCtf%L-VHU!ZDDKR>q294N^ zgFN-wHG=)QFv5GQGC{%dF?`XM$)qY%AHpc%U(INPwA>VL!2ua#tP(>H)AXY<2rC9} z=b4c_^&2+xDdAt$?I3P=xbfT^0MrzY#ha(^AnZY-;mltlHWfL`DIAL1lt7WPAQ}YE z+L(mr1Ro2URJ^{58G-BJM>8iNGdyabsSKWgGsrK(4%ftg`uD{NM!M!nECIUjn>A%B~?+)%NB;EIyM;$jA zO-GT)o0Ie-K=>UTZn9X0qg62=tPa!;(x(6ulT8ELIc0#)Tj&{MqH{zbQ;yR0+95d#`qjJ6QuHQ_td<_hKJS9)wa8`Ga zxe@G_#Uun`CZ1x5)C+taMKR`ME0g35<{L_!*Z@W)M(?Ley=~lKx*6=dwaUdlHIt>f zvC5AA8g1DpGIUoYGI5UXB3ZP+e%eyoj$vELdft+^(t+#9QMRSy*?&qlu;;R#vP?)X zNq9h#N}r#Nfx5BA=6Ff_B8^^Tq9;B#La1r4tG^T8_+vn*mqGZxJ+enyCk8h?5=J}E zX3o>#DT+$m>r;2T(WOmB>Q=d1Sh)JWCAhWp&`6-jPdFI8EHOF($9&(ip>q-TTraS| zxo^3-P8W>+ekN0(2p-aLrPirVB-I1{-3AF8jZMg=xqwY29;$OC98OLrT1U(z1ga!Z zWNIpR`%gVMatEG+pE44*%Ns5-N`8I7hYCE$tus9KyWhVnJ4@aQHyoL1ya=-AA8y&F zlJ;L7s6&qmknIpH7ibkhA0Ov_!q_WsnGIb+sChxh1>_jVmJ{GFKoS9PE52+ET02ndFsP$vTPjdCKQ*CF2QgH!-`k{LVdZy*JB3=GoM4;O7^a1}yLpIHip`eL81<(f(tYMGhftdg0!}GivSf)f1i@=QZ>pgRi z3g8aNCiW-P0bn`0bR>3GuU#NuKIIGI8kt3sN1I-(rC99|Y^NGDjizU!T>Y$1h`@tC z9S+ZeT0n5V@Ux1jQy~F<+Ay}fWxd&v<6ltI+w)+yD+@>QNo3+94?7hFW#6u<$`RB^ zSmjH^J}2x@Id%vRpF|)6G@65V(hfH3q7bCbGubq7V_qV5u)nz)c{L*vw0mK2Vs{iw zpUBNvN7go8>^Bcy;v3m?jQYUZS}YFJBna zMO^#sM>Lonil;1y>TnJI@?kJ8=KChxL z{{9E!+3g7c6j@2QM)h=}+Gi(KD?HYHFkA({W*ZV|BUrb6t!S6yfBpjI-YD zDj_X&Y<@Z+O^z?9N7g*uci#2)vQUD-BnN6bT;`ZV8NdwsIsIwgqS*bZ_P7MVNanFr zOLt$&7_aUbmITVBwA`VCz)_CZu!PWTGbL@cKh7Ip`+T4my=73prbk7$w}_3-UgnqB zY_q)aJ+xjKwI?wtcIU8)qtOGf(A}{(YK_myO=T@8AnF{_8sJfAtM!2^Pw&SE?P++f(Fco*#d6kNc+ zT$!ex{9mrz4akLKyM?=j6EovUkuRoaC@4-HlSsfsvv%6`atcxpYdFdYT-csuA7gAg zad`O~epGjJQIB%mcI^Cln|HfItnMwT_ct^G27-NDE_z*mo2dt%QJ0yXn+~Ad)jgYb zQp1TiQp2EqK;OsR#{+2O?e{6z-00S=b@U97Dg3eO#qUA{;kxs{t@`% zTTpK@%;8l3+2C*VGaqc$mFGcP=K3tnCeOHWieRGEpwQQAf?u6$)hhB}onua<(=v-W z-J$9Ky~R<&+|Q{Zf+HQju=41CoWxh%j|O>yl3iF={CZxDn)~uwbq#I>d=Qi8Gd7BB zlJsBK;=`k+@78dYRK*N`EDm_%pb6}%UfOaG!(g&9sp#V>f(hnG{Dd_7py!Ez2vkI8 z|6^4;)n`4gE|(V=%GZ8*Fh(`}@ZQ1Si?|{iAMTAvEmi^oszate?ZNrjy z&}Ad8^oG>0pwQP%wOHJ$rBaGS>82Ez49PaPEhEl2{n>bpOc5zK5t?umKpV&FdzOt-p3VG8BmE$M5a3gUb3@e}cUUVHU z^v0=Xuk)g?u}_*wTgu+`a#oR1Zav<|^BOQSV;CPGvEfBZc@$XFUt@F0p^taju}K)- z4PhnhIpqD*I9qhVUh)wQ@Gff^G8x&Uxn!#x;0}CqM1eI_^};3U#yON$(R`XPP%m%U zAadpn9P;=Fl{gPs8O5xDiQK8=(zfbG)8(eUJ1`2R+C?+D;tk%K4xYtF1g+scpDsfP zJo8LY2jV}tjWSJ~Hc4=!asnzUmnhc`Yk!rRl&O?_K^(LCU_{q5g6VGSO(P`AZflHv z-`Z{;Tx!vl5dD;b{O=#)(PWnW&6wS>$e9iexso!ljc#=RwwZm*pv7aC(K}RW?uG=9 z7@15Q+h5OsIu5dbAtYHYeReDC8YaSt4Af`5{kub1#(H{JWLZPDMP$Y)-MqQCF?7h} zG)HARFXJFf@ zBv2;5{d6S;d+OG|lsKXDw>pXPoxZfRA}fUiHc7Z~A0}y$S{}6Nt_+@#WsGqCEm;Lc z{_`}W^a%{H9n!67&T8Rf`76$RKWLc9T%^Vq!Fqj$#R`mZaiOinwD^Od^^e#mhKU?q zK*W9?r=rg`3B|mPwB0WM;#y3Pqb(X_Yp?Se;E% z&)6_~;a$y)7v`n>#Xq++fNF&-v-2Mi+JNOZF@@T=j7TlyfB-YcubT-=AC`k4{M6#U znM_B5LOtU_^k_8ZS`;E39&A{PeFa#*zl{bcto|^CeV+Q?{1IhlpB?MmG|il?nyg-2 zkjE&X7}Jhx)L)7q7t1*pPeY@Cq`mHEPvRmx<#2c;kk&nX&Wq=Dlm7v@&{Z;oRxbN%!0k1w%32HTgp{HS^USoSEj_kzJe9-aDwwn{Ygdc zBTQUHcCf3ziwn*mbC-6sCc839AflX#eai6+<%(BD;fodx=6kYXjs7{j2*=Q3Z@1yw zkJ$d?*E9kmK^W@1?Gq@>_wR6lM|{{s+hyTu%1<0N2Jvd{f|5?*PcI`J?3kf}6o-+F zb%#V-WTd9`-Lff8ttXWM&9w4*hFN7)#(%XR%FHtEvgNFezSV(QeGo68hE!)+f+a=x9 zNJp_t(0BBRZ}hCcQn_8;=dX7;6ELMd>4k*6-FsuOS`Oh+#0>)6DRW-86yXgi(+W@a zvtv+^i2X&CJX>~0l0$V-#ZNMKu^WyX}N@CKlHkQpvqM-EE z5{887Vie^0jjD#J#mG3O=botLO!vwt%Ca_>cVR4BIVsc6h5n@k&r@?JJJvM9+f)BS z3)RJCkSPjlVK2O=XC`nd-Z}OGkCutpDxcP1HUXl1N3Bns8x;z5?8yqwg%kyc>_PKAfb6!rvUz0i=o@DjELPzs!w;&(~?FPSa|?6g%-G_dz+|8_pqNE z!P}0Ct3t?yyB-j9K^*LszLh+uO{`Q2`a({n98fk=MA-SFHtKSYtk8qBgIg7tezW=y?TV*30a|O2 zZIS4E)*Qq~!jW)qV`tbvDE8oAMFP9(6w*9ODZ5>fzEcG>3>4p09sRTt5?Q>eQJhlh z?_B&9ACS+vK!R4}%j^lDw}!elNFD7dCH}y&`K=|z4Cefn2k8E2YWpa} z{la!MtoF~uQPnn8`*FPf7@Q$obQ`=?u>(*8P3#w0gL%b$!c+tZaBVqZ?+b${+WFta zejibJ2U1iOmz?3`^t6%vNv6Bjg8gn$(~7GmHx*ew!wq5j*z%&_b0B<&$zy3wuBHnE z`YUUkL=ez6o()X`xt|EW?c@zy%UQPc!nYIt91tv_vZz%Dc&o(9ssF^O=@>T6u_2{jqMKMA_s53%uu42g2Ri$^O zhfz}>4n5K+aww+ra(=(BNL+R*Yab##vDfZk-`4<%R!vVgkC^ru=UbS)c662t*`IIE zRJ7QO{O3P))%)l7nV;<{?u}OwZ#+G$dKUH?Us=n>JoZ;+?cpI9>t7({-39LDOo|Xe z(a(4{&@8Kce|oBT)zpg2&Ea9kkru~19u{AZluhlS&s`60s<)$p4XtfPa8e-%woO~B z^&OW0WiGx53=YZ=Rit(i$8tm50;`_#4qnE9;ZnvB8rIEhMZFg8hxg}=tSe}B_1Xgb zZ^I(Fx)*3yp3BWIh2M(DS2BEq0Rp~F*+H?QM!Tx2NX-2nZ3omyzZQp!G{FXN&Nkgj zWBs2dZp=IUVX`8!hc#pTBHdyR9;N9cG(n(l*fk@?`(i6AgMkW1&Jx2`tWDm&6mK~i z)CN_uI@8_lcO7TYXlp%^odnfhp_D=F$~R_(Mfpa0IX`&EIN0o+vUCy&B(8 zI&bc?sRmzo=}~tX-1vU<}3_QV2Dsk|4QI4BbZG zRKhMQNM4CK+sH!arR|=<*NrC^Z!V*|)CPMZ;xXH3^ z%x3T|hAkyzNuN%fOZKa5>eEF-AHir8>bUc4n zu;8TnjhIpD)r|8QgiC?V)b`jihfrHfzfTS-nIkor(RMvxfr(L+{<_pB-oLlL!5MJg z43foikkP^W$k=oNEZkJk>=Cu*6SY%_m=W=s`-TwgJ5Pa`f>pFDGS55H#scfORatfk zflGVlvVTs>F2;4bH7>2!V823O3(*Xw!+2Aq<82ESdqaP*uIGcRTZp&oIHXCiXhi^Yb-ARH22=ZYeSo$|_BV zqh4uu{Pwn*bQaE8>^E-LYsq>dC}ChLT<)?IHDX?Qd(uoz*W0AK1?B~87x8bAR&#hE z6zkKJ6^Klxk0?2ypY%BdMcXoX84e}yN{e~hh2x#?k9V&f3wAeZBXh zZ2Fg7t7~7GECV?{N@lChdFAuLUec)Z827!Nu{x5Z9kE^RvnRPZww2zkG}&iYp7zf^ zoiEFMzmPZ&REUYpMy=6ky|*e6a?|_>7tzWYRJkOQhqUVu zo8Nt_YOfe$DP44iq$Jf+a`v;?`Ap=$D~ZkVUSZ6rLxbvRFYZlV5;Xy%Lr!7(a4Sx*$)#XG4(eK;;=ij4-qFM-j^w*)YFK+vT4gyABMo8 zMyx)P)d&1u+@kJnMb4hM(s@YVEW{>4T{jS}LEhcngl@RKS6|;@MMnabQD^&5%g6`Z zUV|<#v1A1ipdEJy_*an-Ua8Ui6d-d~tDW1GRu1YI$%5!gxNDW7JxyC#PX_yQ*^(kU zs~&1nv^qQ4)#;{oZbmuabD4OYELfELr!vFhkGq19{i!pN!*#2Exgx!uN8^cvC@2eHBSyW~1 zL9;C$9BsH2dp&G{*`C%lV;i>BA9AF5!{_oa$*A;PKM|8(B-d(*054O}SVP)xGbs*M zinM8e2b+@IRD!qmp}*eR?*5tsorWoQ`(>6W*|&u0ec(VI#7AzwN0@~UHOe3u?Yf$- z>@gWLGVz?8DuvD4+TF_Yb&Or~+Jbrmv{JslscZ2rXkuPtP}2&5rW1zjV5vvmx^B=V z+1V||@NT`fl04|$PEF}j_3qBQnbyg;#q314G`%hYf{ENPeslYZ$xa!=+Vw5qAa=Vu zljWW1OjpbN_K^;_fq1V(sx3i5hI!!6?YX4Mve?}pG%UrIq|@?2w=s=SPTwQk=x4R# z1*Ms5OwLaTsD)1i6L)9oqBj&Pcpyp9@Q^Q3%W-wE*BZkeadFp7>B-T%j3Lvn=UUXB zp=R<4hiZ5I19*Hf1J*Ephz)5JwdugmsQ#iJWgoI$D7uB%*`E;q_6M?6t^=#zchky1 z<$1*PYA)jjKd#F@Lzb-1Gm7a~%fq%g;OgCYS1(idy$)DS*&9ckV zMqRn&E!v$BHRrq$wj7bma z2(O(`N&a#~kC370aZSoAT+^(a{vFM~^Cf=kneo}65nQSD{#U3f4hR?e)iJ-T7rPLJ zRdDebON^1mZ+#muRr^JLULq)6$m{DSdlg@RM%?=f#fn^MYgTaxe^$~@l9St-?R8=5 zk0tO4#2`61nR;?b!}^&$wIbcY=oIw*x-%n*WJZpVhG%6k)M+>J%RE$?j^ya-cGxVz z+KFtfntb)ON_Jt%;QO2Hv=QgT&GAg&r^-x{7g$NVD51W4=om9Qkcz5BYFVa*!)OUy zbK#bg;-ZaBMu$i*pzTn&$D{;Af2un68zlFDT~~5H)|MzbLHNBb8Uy7eN?&=T3*@MB z(}{7{6*xLH z^aMy}7RU{uBwXT3=l}6Bk0O@gocKHxmXeB^I?;_~D+MBGjvS zoAXJW*4owV~!x|p9{wHI|yPK7Be7^b7Yvj zz(N3+w7Yp#M=b%R^_w~nxTEz896DQ z5hBu{2pYni*k7|L2W^aAx$@RP%K;4a{%2~x6{Ex)9>DeOxtVsVKxH&MR}VmxH|F&& zZFA*v=iSdbTiqZ2AxV%#fmFL1(D{xP3jo0B^&BEls(8|?JlV`ktW6TKo~#MSU`Ewt z0hEnw9z$tcI(Uw8Q;}-SIbZ$7fR+MH0KZFl*4{3tLvV{5r-fiQ+Lcd&)6R{8oCfz{ zmv0ZKTKqG>F0cD~;W~lvyIT>O=6ugWjCr1`Vp#=b?fy#&;MUb8g=pJ$OhfT7C0%G14o8_citQyMW0nM$Aqex36v%SHc5#-Ayk> z61z54pcPB@R`WtG^3>|QWb1nte-nw*xa#f>oLXeymfO4LtuJ| zWF4G`+^@8Vp5nl;t}*nt7O#^GB$|JPKg=uYmU?Af>wmd*w*_;VD%WI-P=u0;GJjy- z1vPL&M wHjY^iL})g5P(=%sk3NQcM;Uwq*RR{#J2 literal 0 HcmV?d00001 diff --git a/apps/editor/public/icons/polygon-room.webp b/apps/editor/public/icons/polygon-room.webp new file mode 100644 index 0000000000000000000000000000000000000000..7d51fdcd8376ff0ba262f441ff7a6ac721a106e9 GIT binary patch literal 8862 zcmb_=Wl$VYvn3YX-5GRncS3NN;4Z-l?(P=cf`-8fFt`LKxVvi@9D=*cY_@9atM`7q zt=g)+)winq$GzQs>YN|l8Va(q88k33x-yb#I%X-k z%aGS@-ljJw#Z)w|I(~RcbgxG?rzdutVjXThZU+ZqPNaGG1v~!+5m{JoX&iNm^{@w* z-rSK>v_=Cqet54|m^l~Ykc4vk4^BmTJuQZbNg7tpM}$-_x!iwKRaM5-l|!?BUA z^kzex{wu2CU~;JI>+t{JBosy*q>1T182tqHKcBd$E8Z=GMB(RedY`hd z&NGOVmg)3^`21cFewLgDM2~;tI_X}ye-6){!_zVhG>_nMbx{(r{wgf?$G|X|A-L;r z`63?3^+_#v%sMK-IlW{gpF@i$cMlOOc*L1EH1Ew2bq+s;|GC7pA`@pa(Tn%vj~sxU z@ZVA{YtOdXS06cxbf7j@_<~5~o-oa9E*JuD*hvzLMI7iJuWu;L*)HT`ccJ5)N`7Qu z_r%qQBM>Auuhzyei+i*Lwx+1JQ{Wj9f<_j54jx@A7JgbxN|2WYHhAzXHnuQxVSh?0CM`_Tw!m*_*92Qb_AC;|X`H%{XK@nnKW6uyCtYPr_$G`hNH$ zuU)R5pd7d^RQzX)%Y(5frUt(0M0YHoqup%3Tx-~Tz~-BQ{ket;fUjtf(=e?54i@jZ z`eX!cup(WOtu8=NnWEB}*P-1T+FW#sAk^3OGyGV%xr594O_Xh2n`I!nr6fsVpckBh zDcPM5trOskJMRNWaCGKzz=-ra-MNsvziXB>&L4{AcO(YAFnP<^-hyKQ6$ulWRCPh zXvSG4F`+Yh#-Nx{r*iohTC0H1fTy$VW`jjkuEEXH>LT4sRjU?1%-?EhHN<)aH73nl z@r*Xli3|AFMNWg!6%R*d@#sndJhX?Hi>=0P5p`&FL#?Fp9b8Tx{GVKPQ^~g#p>vV0 zUvN5uf=rvpbeBCeBq=Fk^ggVjyO~|ThPKbK4larLm1xi6<)!zv;cQ~!Z7A0(+(2_l-ZlhHd5C4+lqfw&@Jtk=xxqT_4 z>NAgB=i1Fyewlg=`4ly0;xs$5IKrR{XP(-tRJk!YcH2=>^ zH1(gIfp{nu*5yr0#d=J?E}k1+s{-@d1zoK-8wW{ZVSi$Dn2faMQo0F*Doy768I2_= znOq8_{^_+o*>@M0->sb?vp>Rbm}X*N?U)2VmcI@GkEk0>C^^>EkRxlZy9>-U1!8>m z)7VETnbhaPu4#S{_z}$DFBaUyyKd#X+0;T0(C3v7I5!yfr$0bQ-6^LvTtz*tc!&*l zQ1lkSqGg8I!uji{`Ex^+)o^KX4pr_;T9%b(-G~Fm9OWR(mGbp&eP~`juepupiPh(lZTjm#v-!gOY`B#BItwZ z`ZS)5cv`zefm?(=^ZUz^ApEt~Z3VXB3EWJJIO*hjM_8dyh4!DN_%`u-8&Phu6D$8#v|#Z$6c zW#Pd5*Ck?vrCVU5EOo*Cv$k5aBqpq#Y6lah5S(qCSEDZ79NZyMj2BnozaOrwGzo^cRO{$oJoNDd`5mVy9bRpNc+t))Lib1L@n5AzSyq3u3d0E#u5mf+>{Wh_0X9Gr=OCL3 z%m(*1n!e20{N=5mFyp^^+D>@!{=r%$VuOr>&gqraq$4$Y%!69Lj*i>d#U;Z<)l04N z{70*ix)zD;`0g`m&~CiF0F`UFy?_D{aX*iL55OXX_Qz20Ns3U!SJEDUz4WlYJI4Ge zLb#DwsV^G(`HvnR&|)8K9u;wZElhY*bd<_LUoW4u7^uVr#2sZtoWlkz2(f%}f*XfV zeRKE_8Qw7@)L-w&f=rIvVjE>{s2LH$IZ6_HLZ?QTcLFkNm0@O0eR0|%QqN&x^a=#GI9ZEh#7J5WqYRM?k71Ecv~^#G>3 zE4R|qXt0J3TVPn3nklk;2fnx1BmYEr!J1f`!Y&(%nGR!J1=JB8GQ5Ts?Bp^W1b=Td z%$ULHdvGCvKGlP?AJUwh&!5;B<+zNUjf+OQ7{<2(y>U)bk~ObXJAx(NLt@m+@@d!$ zm^ufu6aI40u`^>HiG_kHY0Lqfam*64vkS zWbDW8zU&cG=@8#9q`j_9Bf>@D4~{u=Ke{0Z!<|#w`oF9ZKfyByU4Vx)E#fkO=tD)$ zfA8dD)-USK0_3|~t%Pt!*ILV77`}^{78!Pv7A7XYIY zMHS8?1FeS3q&!iXkm}B8{}fq^vfgL3W4h;R6~kSYj?9<0OzS)+)AZ=4VdC+U&lNJ~lmkVy=B!8*e1~jbWAjlKvcJ%Aw~@on&-$ql9pQyyK&ld_D)x*I8_p ztH%c}vVbapU$}Q$4xRU17bM3hPn>;PB!h5^XNu%;%$rMEMDc!!{3w?@L#V(qz*Wv; zaA$M%E9*<@y*w5p-iG!?OA_12Z0a0QO!*ejCW2=rmsJG>SQVy*gMU~V9_dkpqWuegVJid(Kdkzb5Se}X2%`j=aoH=l@qep z;IefE;s0dY^u4Yp4GR3Y-3e|oYCcCNej{^~O7)82=}C7sin(H>cUJ1JUy@opx~En+ zf+HJ(X4D46-^strtVCN53QZMw1sQf40W1<(Sdr?na76^e*M!|K6Px;ni6;;@`#>cr zJjupB1fHp>00H8jBeK@-bF%&I?IP@AsBF%S<>`L&Bx^XKaxJus4-t_?G{K0~S z28ikXkgl%t_(OUqLt_`|JLcei^q?oO_5*=Hq7=P-ovVd65liu{=jLC~>jeRwm>UY0 z?})me#AJOJ%=aOJnHA+2?KIh#bCnl=?T3`GE4$NT1cgpng(uH0YI&NW_&~RWKaBLX zeiy4J-g}IY`GbzX-*)$U7voqj#^gK!~UI;srV^@hR^0cDj zd30@y^pY9PJANZ7b|3uKyPisS$EtYiVE;+LSI&epR_{&9U?S$4VrvYmqZD5RnqoVP zBb#u-uw64|yqUl*OULc=GA0jJz#B=&3R-z9qn1;8$Vrn2tK-T4c(LvG?sva#HCH&w zG+P*Pnv3%Wwc;ih*MS!#dGeFJtiEp;V&1aUT&A8_RYt;(5kS_a_qzQi*KRw|6($o> zf3F)nJ8#s3NNp9<7PcALpxGO2z@+6vyuu8sM5y5V?qkxf*#F?PV!*=uo1Os51plU| z?=ZQr%(t+&u%FC0Gv!KXX$onyh_^z}QEZ%EHT7-8v1Sl`khVVTrCIHXRymtZU~HP| z9vDjNP(ssBgKuq4GJ80Vr*ng=q1^ei(B1d`msvjx=!avx7lIR0DB4QPOYQ5$7pz57 zmF^9(u!}!Qf4W2R4}!OYpZsC`U_9}zyszMIGsicV^CkSQALI(cZC^&9ep9p4V(ZVa zdQZ_1gIdI-R;bNA%)7{2@cVRwz{BSA>+c}#_stcwC+EAQ7n4@XS}_mN*lt~ERqBm+ z{}GQ~N~sRwhvcKMkKeqwE~w`bd@)ZgAX25s*Ay$mo!^vk_C)HFd@-|VN4za4uPHd? zlFx@k_k_PB{XaeDER7jt1btFX-aM5x`!9JlXDO{$E|1fCqRC-H;XC`zrtZk_BuYVN zSLemkn$r0yVin{Ei0S{yC)+goLMAGjP*c~zUTgq#X@AwT2+Zt16RP~PWpf>*e*i6v z|6Gk;E3>EA`+wSU4oXR2?Kr{hJLW~Q;pf$nJy_zLwijGU0)A)Wa_s`c5-)r3uc3ER zF~7;nr}AtCqgum$e{@_-^89$$NaGvauj?XUA16oi?4UfowRO|=(1GU}@szQ7(lKsB zd6Zx}9q1c~>g}S=d(vr;wkEtqF_?I6vpZ4a2JBN^RT(xnf za{u9K&XHgmogxUZp%*aGI6S1*Z=h8S1V74KF<*an<&!!DZf{ucSSgX|J7_eI^0l-%ldXemz&Cm`+VCA96=JN**%bf&uz@`wI_{n|Lp6T)|cQyY< z*o5(Y1Tk7{cvMH#*w)_tImKVe^t__ym%5RJEH@SBUq|L(Cn8iKWS$lq{`smz#G&DK zc#j&MuVOumE{vGtaIMtfDhUA*fXU zMJ}H44^{vFh4g>ZAz=^9JG2n<--_qI9X4U!TS3Zet9mj2d}vOl&~dk;$@hHThw>Iv z>wW~3;7*$EnEZi(o?Be&3m@eTZK_j+7^e4z#~2OCbKeHzWBSf0O4BV$iGp%nAb*Fx z@tMX_r=GFi;I+R_L};w6E{-@1O0fIo(-bMd5f6hB^3%SvOeppvQAqQfSkYS3sbgTU z@+2NHmyele%S?)@n&soTlxaKL!S8PU*zx?WYGNPdzT=?AbLO7~uLJr@*eZm#;BAa< zI&PaOudh;9<%X-8t7EhR!l9xN_y-#?lV%ArNz?Fpr|dli2SP&nWGREV)}rWeMyo#) zl1SyyH2!xEd#E z2D@Blbm}}|%A%y#roUoS9|#>f#*?RM4PgWY|CW{Hw+<8EeCaJ5f0z%i2u`0hY0>qX zN_e6(_e12|wG#aTeLI>r(mZjP-Cg|b0YV=1G`6&fL3A?HKS(=62V+y}J&pj^dJK`{ zw`R+&;WOJOi}L3GmUq3_CP6+5de9z@t|B`ng56deNlQZyGsAr;G;648Bb^XHtB>)L zmo2_VJ=vYu-BXD68K$W7(;>DUnXJ(io6TOyv&F7$0`VvPN+>Ot1O#_?wkK^<1lN|9 zyiuZQ6O4Rzfen5P#O}q%(SA*B?oQ&?Lw?#9 z*6WK>$9L%$!5mrAQLg<|Xk0sskW7xu=5>&*mHP=ATP)3!_00;wh(6a}4Cl;8L0HG% z_C86Fyx=&UZoaUaahm+$9gLz;D7ot%qQIlkSrNfc68YIqF9~IW>c@>H-waYi$6sRg zxY7(gkcwq3rsD^YDl0^aV^1cV%K7pGzQA~<7s9&H$xm`t&3Hr;SV(8M*v9rjr-QhE zDzfr-bk-dKQIMqb=)7c>g|V^MfPH*cm+pq6KOBwcG3^Iud{#5mRj1gNV z?aa(}rZvFaYw^boPLAizhu@uL<9iEhUEhfMD*cMiqnb`qEwh)Xun{cm-9z!)QHA;z z?(15#)L}DMGp?I`hW~yC{=5s@&6%|Km2AT&{F>JuVm7?S=J~YM3ftq0r$25UP<)#4 z0Y7g%0ZsH<+hQvQtle&mCqk67zCL#$!S5hGz*jEGFnQdXEF}ltdX2FX&*kqGms2U| z1){NKDfmvh6`RsNrUL%m91cYWQdU-rc#L|C^k#>7mSHHgYS~{$ZOErQ zL8Ji*V+ z#!j6Jp;T13l8+I!y6Ht3YW_mEuEX&zBo>F?;E~j#b2%~!49$oK!N1ms<+U8ns_o}c zJ9+HgOSMnig*al85{rSZA}w#$FQ=|R;6Qj z%V8c!qpHR$6>fPA?Gy4<9?RG@-$~U0m-|OzdvxLPS#cL6y;X*6D&y}Va687toU39F zUI!%=gLOQCcI^@KvEW-jxg?plZ6eUMEU~H8X~1SkR>6x~TLUF^hxY`&UPxEcLu*u8 zmAvmE4x>&;oS*hiq%!VTn3YOa+Q7==X^|)2iy`rog>O|uS-SPy9C_easd@5#n~lp+ zJhpGyK|ijH(_mP|vs<)0=XMg~7Xtw}$ZlqxvXtp${-GBP*d#x{b_tE=Giyh|r}35V zmh?=jG!1I>JvdM8bcw9ibHFBC%1dn*@V8<4EDMQ_{ve8nV3`|y8@(YaKGdrsu?DKT z_rvxckegF=XpiK9rWtlKSh+lvz|e_G5zPbmF$aSM))h#crX{d9w{X;_;o^%l9@;z& zl{SBQb%5w^32{GvHS9r;R5~=iJs+aVGL*iEr5vB7Cma+cb)D6SW>4#Z?C8KF*KX9) za=5b5jX317A1QH^j$=f*{aDYu-K3~mA>WsG!L>2CS9czz3m=s~bZKxh>43{j!5gM^ z%2H@$9E{)_S&d|??3t>;jY*gZKqrG#uifr<`6>Tp-vFhtUpgUgvZAXAOOxKyt1dxPv>ugVabo>dG+0U?6ur) zmLX!;q92bOYrVN)E%0Klf|awlxgS`f=0SPTbpSNOw7p-eUyi2@N_duyCbj3D-JblQ zxuRVg+1Xxj!MT>xTaVpyrx&u}1@u(4$mC0gd45Q+BnNXtffY`b z$gUU%9;v#(jVNK>byY@Ow2?#9^|_LhYM*7)D=RO0$?0E?N3NncDeIWRC@~)6z$0#Q z*UL%lB2Eu>X-aGTXIVaS!?Y+uzx<2x1J#)WW}NIh2=u@4IX`9}Qm7gjz*2SZmQE~< zz%_o_S(kk%SeqHOq1XP3**U6_ScAdd=&x;QvpjixG>$sR6}ihnLL5DewdBo38cvbxQt2SZ?fad!dIp)I zsKg;!T`Vzu>+g0a%ufzbqSlj}kf#S0J@j%C8IuF=gd9~!>W8)o3eX0E{_Y{FD&P4d zCMNMAV=~JYD(}PDJ{_MEtncdR&4(Wrj(tQ3; z_<+gGz$kzf8iieXJ0g*0HQ2+$4f2)uxGw-b&T>N|UeAG;au%~gIushZ#+QC!k6(fU z4lDL4n=8m0m6Ulq^e-K=UT|EY9y+0koJeLoncW{25#EWG zUz38LE}>9SGpF)X9?D#wvs22%xuh)GrZf#+xa?kCYvmkJL*n5EjKif4y=3D8J{1T0 zg~OLuOq)P}XxI6w)U`NX7ghTHA8|VteNjx_Tb*C4+PAn9fr$28eT+=`?d0&07?I`8 z_J|kciYPU|%a!s~i0hZturo6hvXDN*eS+AepB*X(7QtRG8LqnAX~}on=+1l^Sui~2 z+71@|x^#f#1Hu9g=+YVj2$9Qk@6@-xJbs%8whYlz+MW~R;51sP7CqUo)|Z_mJQ z5-&-A!^NU=lI!IFjIPU^SPpi6DBf|ERrV+LL|n{M8$#S1q+i0MHW5;ct6MrD665Q$ zd>H5`*%JHhcFsglh40fNRl<=#6S-G0AF!Lmz98s#M40Eo6a6y?VjqH`*Y5Pk#;4rb z9Ag+hMU$M)R4z4JfAmR}8Vp5l;WWO?1_A==cYBDKV;-+ub||FQK+ za4kV{lR(cxM9-9~X>6NtTwso*_ov?>NT|0wn zPpffFN3~bxX-SyVg15?CucA=oE$i?4yCXp>~wU3_a$R(r4ckTM9USg@6r48v^!Aui<71NU_af-gVmv<2cVmagPrTIZ_ zWuqb!E3a8=ay{}Pj*wzypDX_~b zR{Sf5>(5<&v@CwHYaCz{g(j~>VgB1cF+MBQL9w&-%0ct8H6W za6?~&b`e6r2P;&15xvA+I4I4(zcVPoSb;{lRXkIGani#u)=BP|+(t z-T8RldwtH}GFeBK-NpoO`%e&JHXV79Pf>ywUvVaz+s1>QzEA{$ x9fgGQ>Ya(Av7Zk@@m!92@YR%`1p_yC4WVgB(9t@d)%Nyak(vLtjQCIRzW`RSFYf>V literal 0 HcmV?d00001 diff --git a/apps/editor/public/icons/resize.webp b/apps/editor/public/icons/resize.webp new file mode 100644 index 0000000000000000000000000000000000000000..acdcdeca8a4cac967be72a6d73e56d8e5609e98a GIT binary patch literal 9164 zcmbuERZtvIv*!m1?(Q-$xVyW%TW|>O5+FE(hv4oK+@0VqL4!L9PSC-9ZoaL%x3+4Z zw)RNX>6g=Wy8HL=@1vzCCpSz30O-p~Y3OMP7@zjaS_EFZgDlOoVCJnzj0!?`S}Eow440|I}Gg zN@XdX^3p1I!iGjqBWT7Gg;R5~ri)@w3O*&&L)_YfxoE2X7{a1&-^ zkYIESx}L={jK|v3J-uCqef6$K8-u()A8EP-q_QG>C`I8E!+pTKCZLAou@|rpA8*s} zY??2)BEQAEH6=x4$4vBQo#2=++KT{*HlzG4$J7ZZ#&rN{-m;?>`*3>0L zv@m24y9y@K4cp1to1JO0Mh@>7Wdnx|4p(#^B5gU{gm%n8o)JV74Ch7F?}-G;pV%mK z*@p$rqQ|sY*pesWLT+ zo9e0bis}uH{=?PFj86=?nJ!PA%iV1X^O8c6jbyEYRKy4*F+Th{klHQrep>qV<7`HxRFZ(!Yk_Fr_g6z@39`v-7k0Sa=1Yd$2z6`dkij$uPNRq51K$bU^ z<393L2fX*`At9W}jB|E%#B!@UCERH$5%6QI8*86@K+By1hC2kOwl$iy3Z%s-BbG|k zv=Q8odw2Bke8;YO(wz#fCTJgg(vkOeLMf%~aS8v(k}I64Op3hp)HT>vdByUsX6wCT zjTG}^vU6ej2mYa%1Kfu%m#2HlFjO$Js5e&14AjiqkjS^A=ns#sieLEjON|kuqmX>7 z2uI^Jl#F=;2bS$$xi0G$>jcBRe;S?n2NfcD>6aqMd|USJQ+2Jx+_RD;=?$*9$Zt}W zz={6WD5j+NmlKkp?J;A+rLE0bt;`qjsJLRZ}30uFr7V zH#Bgym)#n)Z(eyG5+VX{ggt(OisI@9k>;(%iEF{{im1X zGL*(-1IZ)nFH0k&#NUB@{9xuJ*FLQ%+{rHeT|hRq&&x)2NQ?Y8rPM`V3M=i|@?Jve zS5m|5mQRAv;KFQ#@CTh4LL9x*bksQR8JcNgleIB$mAw?*5Xost>h~UAV4cgpU|G3O z1hiGrPFkSAPB4{ixRSCMZfQ5;)fMqeh zR?v^14?XVb3p*RV7MQ4@k6|eeg@)8CML-a1kO!}CsY7plT9gTWOE#t}>q{f_ej}$0 zHsHAaXd#2Zvz=2 zpb=aRl>}g&8;@U<25a0}p4RAr`>lC*yaswVvy;Xp<=im#E&!_CtG<(luGyfq8?wc< z(@jrY#dk4FgLgk0(91^JbajY>;#>SKl!9g=GC_;y@X>f-3?xm2Nq~cL>mRP&z7PMi zBTbHB{O##4InDfWzBEIB0lr_28DGnI;icm=9D)5A zEvzEza}e7!j||Yn9!qLs-Z8l-iJ6gV*J&4K6kD+wcNkneVXmrjjSiE<{$oUQ!XB%A zpKsJ{f|;u67-I}n11rb412@AY13M z9M?!$UbEcpY=Ra}qjWp{0@_yOe5iRLNt@KxS|4amqui01Ba_f+D!>sCvzEH3Bvp0y zb}JTZ{W%Y!wMan&^El715t+_87&OA&zF>%dmt)i!T%5O%1udq#!7CYc7W?Pbn2}&u z4~WV;!=YUnhEy)13&SU(n*$g{m|gSkG%R_IL*0iDBTWLX;T|T|)PL=0!f~(_0v)40 zFZ@%qs2E9x$j)Jb6MrKMvSX1_#gp@*hqSPOZxpyWPe4kBS#JeSD}?^yNAtA=aeSglVvGEf%4Ai~zoAWHqQn%$?*!q|hs8?HrV+bXYU^5${s9f)0^kHunU0w}>sM<%ACTb|vj0&-%Rn zjf_8!m3{FfS8?kAv!rfq{6ryJu@vCFcc0gM=o^a^kC zy!jiYk_)?Eo5kh6p65oHDd5-4)?ur&7TN{ZF?OC56*F7yGc=vDMzG!=FY8^wj|*Yb%Ygpy&E6m+*~DX@XCg40pN zXe&6nxZB%f34V!MTo8+|#fgIyX*Ei|%f^a`FjR1T_ABWecuN`9bthLJWSQww&ijcF zus4_j&i#lc&u5S!H;e$y04IJLLk#~tHY#o)89ihJ2UVoK$+MVBP3oh0H*3R^0xd-C z2XIGb0`^4QIMsQ36fTZvq}=9(mW=l`RK%O!5$hSiiR}@!T}af)_DVt5?lTSU$@g1o z2kDw-O>g{W4cNHLCRxS#GLFf?Vpw=A2KsAcyhXx_OwOMqB}2(SSC)xW(>|H=W5!<8 z)^iDlmBp|PEXML_%3VHS-VAb`=M8!Hv;I8p^ncLP{f7#A$Int2Q}T_ibua$~XR159 zdaSMGe{rkGt^=K?`AfApxUy-h9wi&@u*+n4BarA1~^Ihr(Ed-(<{Sp1yn$H?Ab1v%af@pI+>(qO|_8ppB@aJeDa>foj7$do7D+^v%`nJfH{@f-4%1jsnkxmxY z;AAwPWMeNjfF+HUBy-WvH@N#=GD*fBCis3({CpTc&Lrl!+PK*202S^@tk+qq*>3c3 z$Z1H+J_4I(2Hge;5bnggJp#}g_hWPPijlZAQ0jMM8%~apLYjUZYUqg2WU|gs^;B@J z84}fGCZ<{m2HPbtgCgZ;zj=@R;X0`YT&s^jyTR+mc}eAc_Op%xexp`8o1GfIH}_Fg6+Ep&97z&Jwm=Y9S1D0fn2LZnBHo(>nj7ng$+w6 zN>l6((Kqp|l-MrS?Qox9>t4E_}*f9 zQCq1#BfzmbbY8bC;7FEm@HU%@e!U*+H7?2ir7$|#9zOgtN;@E*bUm(gYH(DNn$sPc zXyrPJJMKh=g>x=jt4ex49Sv(pDe|wNG%fhJn|ii41FtYphko8P>rfWat(H zLeqX##98|RLL~MUafmZ6TGOl6RtvuSGNvXwM&Gl4O{DLOm9-ByE-F@h%d+e@449ZDM&0;Q zW%6g4vo}X!Y=&Tz*y>Ma`DW=Nr>3IdBAX&ZmnpA4uXY;TISd;=L)t}eE`g&B9d7&m zD=%BqwffyMTN6JReU4le4yKXRSu|M*sg-jGeU3M+TueZ_OH@{g=!xe4R$~9e8MG_{ z0QjdGslxC90Jls)9t_hh%q@(V1xLF4cMyoW1TVUy5DnSZ<&RrmSc9SKi<$|W=QX0d z67fZjU~h7t{0nSQa!`l&>5cOX<;$mwi4*Y`{tEq@**nvg;2Y6zeco>&;zofy;!Z(m zQ0G3!cbMSxU>7Ll4CeUX{7X63H+Z>Jpt&;`Tyt=GAJY>b#MNgB zB|k%a4Svyoo7IfF403#@UqyZ5zgJgGFb@J3R8zi$mnUBI&b`#Ph@GBecD_jezZ;Jc zC84t-yW63#VInb%rN%Bbfkh8ws!e_vF*&XTBi`7yVzEd<(j>a0f5+A-z3-!#Irga{ zE)#}o+{a9Or6MRh*$D<4MrX3*U7H-bZV634&fLQG?feE_|R* z$mh_4t2j%Ggj>aTJo-lE7hD8c7n~39emH7gpH7uR65~2@pLRujim#aW&T$4D{4!(-3t>Pi*ca zR?Z>N(*ebnDE7ww;lO@=7mKK3brJ6xtEP|Z4SQX8IOJXN(~^_tDMKJC@Jo1namVBP zf8wVi_7rm`4yVW+f^EE;rg8}1c!W=LP$3%!p1{dhMfQ>5(~~M`H_K69h$gwSJOw4^ zF(`D)C()j7Bm*}hKRvF4@}aOtz+KBly8tSFU!TllJXxRPbljN$any7yM-6i%jV&k= zo=+RkOi@FnOlSR-e`7);NAy-);Gj~5TwE1IX2YgvC?xbOaKz#4uu>Vd@*=kWGA9d# zHlF+aUoFK6lectI)WQglM6%`n4q%?Uo-j~UEvp>Fng*k$)S-E%(!PN|e(bq?OYa@6?PNbJ=uU7sw>Mbk zU%c!BSN<1W|LyDl(*OY8p=$8|x?uk^5EHIoYl&H%1@|M)c3Bbw$B*5Z#m8wa?LLZ> z;gsUuAzQTvV+l?!vJ4!h2#vPMR0b<>004700l0GJFve$^&F;tDt5VWLmhyJMv5KLV z$IRdPx6LLFs`e71^b}&Q!h0yq#s|R>BF2PM@LmeydGI-}{J`=0XS66~o4v3J*SaM! zeGExQKimZ22t8LwW2UCs(#cdKm5~^^u4GgB%-gHl(kNg&xw{{8${uBZ44{+C?oWy& z-6kEt>bOU0#|=wHSu?hL<8S(w&46^oO_op1K6WQ$*zdn|z5_j=5PuJwKyhelbd4IN zC>Ck{mZJ;+FhK|X2P5Ek>QeNL)su{?Mv9&`>YPX!NtDd(r2$KQ$Odqo*VNbPxwz^&1tls}tmI|uk@GB;0ot@CCK@T%8)z=>1oHJ7Y3Tv<> zJA*CWw+)0(p%(celny<@_jy;6EAnX792<=8F$(U(0#pwOWa@TO1bS8yPZqo|fL*Jn zZR;Ivvyl&O9k|H- zwl=SMXIH_PK7?Dz1do%?p|0BIp+`5>{3uH9)57)mh>x>0izbjhVt5c_^7#r+_db-# z)m3liH2+E`{Z9+4=$3*JL))*tG|s)hds{kh3tsYCPUnn#Py1tKrL;31Hn6(N1w=z}ah5hL@(WMJl2ynME$f9GqiB|Y?9zvEfg30b)quGdB;(|p6?)iEoaQ}KM$-(v# z9i!)MX7-BNA$eSkY~=c+4hcKMw(@U%6Z%oGq113y_>(C`TTvOk7HZ+^x_mVT_ z(RZ~-+?A}yYZHqDbWj|;R!xwZ0DKkf*m&0WAq0{kPfH_F!TGgDu7UNgo_Nu{M{I$2XUtJ&d(mNI@u!h!g(XP zkAEF5j*Gia!}9~S(a7xO%aK@>A*wvqyj8lE86|uHl!rIf6F=UaT!lZmDq9Hd6rUl+ zby_H{zpNo^lDsDhakh%&{XGk(@i-naCz#1LUPVfEcwmLYLW`I=F4jS&ru$8=FxTR? ztuk?mcYN(=nM9CqQ4fXYguu(EtZg`yjS$^GOFT)#q*Gsv79O!>8(JCFSFEQ?@Aj55 zb?}s8^`!|0ka*(xLMY7WVOwp|)U~Q;W+EmhX-zU+&92U&+CQs;>GMeON6Bepm+d{g z2+tPKK9a?<2al)NYosPD;q6V)p5pZE7pgKJxn{0TftxcjoQ2H)a_DqsI)dqJJc(8= zJFrySt#s?~z6S(yqYtrPtNql(cOWXl_d0U=G#V5@792S;EWU@qD@un`)@#lej4GlC z-;?Lmt_m)$X_jQ&j=|1J+JG6peizm(5crJVf^B0~+_c)b9!5P_!|LtP^P?%rRc83~ zPjn+ua(8{p2YY^0pX$uQ9*hvgp~*<&eYr9>Jn5leQAUJ>j`pJ<%B?u7)?INLRZGZO z3qb<00(`c$aSSN_1CJx1` zCx?OgHQzcq7R*2C_>Sj*wSXDK2TQ8{9_#ogb-Je1D+fPRj_-J{H3?j?UT9l!wwSjlepvU0rE8_6@_xc2M7yN3Mwi=yWTRh<2 z#(b*TORi{8httjzTlfp8dqJ{`jy;88CNm~2 zE_bWZ7wpe&$G|9q_s3;|JDITE`U89&K0yo+=SNzj3U`K7J31=yovz5dxk> zU5ifvTw7E@n?Ja+uct7+((o1oln1BSoPA4oI#@B;|gJRd6fvKqF>dHhP^QsV6V99$W>?Xvkmmfi$@_*Vyw2>}f zm3v_}vJ0+~jDk8-^1bO-P=$@uDM8tK3H**@Tb>%BD3h#yb zmw`%rfp~T+`NR4oBH5W0<)T_L*7~>dMQC&I>qWZ1V*4ZFN_*t!B9< zD^~l5x;r*GN7toeXqN@E&JYd&d^DYSNdW2+u47^&5?nPk5h|TsB^C$4i7t|8G&fKD zwpjO_aS_MlpQ!J8ejTC!Lt{BMo>t#j2B&)zSXkwhlll5xggAv$-;1dCQv6Itw)^3x zQGuMleX@~H5d|Eo#w0zWKNHUg1VNHH-YG!Mg3yhGejAC!^zfIrrNiPOUba3EZr;>U8q^UH_UQs{ z+s}w|i$E{f^^UY))AMvGUK9o76c7fww_?H^*?FaBpg4qAce6j_KtPU^V49PXpp=eu zoZugddy=R^y1he?sw>^_thPur3|RL2K8tpaBskE7M5hvA2Wz@J&SzQz>?0ejdh6AO zN8_)`hV8)ALgUS}yFsf0QH31y^|v#;{Zz2y*3n-+yb|=Z%SV*|H2Yip*Up_38?c$E zk#MkayLq)ALfu-hgoLP~j?lq7gIk^$zp6-zJXJ_t#oFFx^g=o$0W0XGckun!>b@_h zcG6HjTe{31)>4)iE!`an>m)E#XoR*`YBiX z0-aL9RqXYYKaR^sa-j1+6p)VKdLRsl3G>-{a4FUFWAE<)zJAtv!mv#+*zw zyMPi&?HH{S?4W1ax_S}HG%3YfdF4LObonPdkhU#IVTNQ=Cw_I&d-knmpxE5f_(-|4 z?JMhewS&b^vr;m&tQ&x*PsP1tyVuBvg#J78wnGm?eR1Z^S501n3Mq%fm3rM*;;Pjqki{3^QZwb2Rh@8lif@Wp3N|` zkI#P6W)}bIcwXjWgm_&fk$a7P$tc!1=>SpjBxJ32>T^Bv9^=M24Nc;Ha{W!w4WMXa zuqN>HP%^wc{4p9aq)YOCkYD6>ArU(jOQ?^CHYX<1ej@#WX^u028=+{VjQ(RaB*1Vp zR!zg!9p5RC#S>eP{}(upY= z5=BG9r4gDJGQL+^TjHyzyh;8h+}-*gh5J*PA16I?j9vRrwjB!Ln5=Q&(A9MP<|P8+ zd8t;mj1WmCU2&X*P!apD&FIf(O6$ zPwIEJn>DZR-?V>uWC+@=8664GQy{#>XSq~2>gMvx`QfZyV9k6+>ESBwsI2-DNduqM z#rrefhvQN=19f916&Q58oZ<55rw48syn!i(wPBC<0hf5X1YwffGV=K{-&zxYut%WJ z+xQNU_{L0q#w=>#{V2}Fvx}uYeRkb&QZv7O2C-Us?4RirU0r)cW6*Xrqmw_8pX(oy zlI9;ll-_?+L`5MkC+oMWkOa3Ld{B@00`+-ZIxmzgYZF|xr0Tj9@rL@}HOY`NhB zVfF<1q55b)0#x0w0Z68WdB6~b*Y_;}lqqX!6VzAF1b{rfvedKQtgdm7TTf)oXeBCn zBSK^|3^Hs-$pt|X@v;m?D)@5#1*Uz|W}{@R;mT?wJX+6}W(Aq@V3{lamY&d?V3nY% z%-Pe+5s#tk_c0~6_zBZD4q*=d>~MIo!G}{J*CJTR2nm(bC3adGZ!H4I*DQ%Jd}ok@LK$dz zab0k2@viF#s?rny0QYf*zelfog@?jkxLt$Y0#UW9kkBl7K&GS?UMr)rnK>Uj* z2ECh)$Bsd;AsgZQksGgfz#Zm(qKFSw_x1Emqh4df(30kfn!jnkC4;*<^|#wDHSvBJrT M1^-WH;{Q1O7oUT@0RR91 literal 0 HcmV?d00001 diff --git a/apps/editor/public/icons/walls.webp b/apps/editor/public/icons/walls.webp new file mode 100644 index 0000000000000000000000000000000000000000..b5fac998bf020363da294d709954d3c0fdd237e4 GIT binary patch literal 11620 zcmb_>WmH>1xAwucc=19AL5f?8L+}JBR@{pehZahK;#FJ{v`|WM_u}p;?k+73#ofR3 z{nlOg{<;5dRx&wj&zZgF+0V0QP9{2VWo1)d05DLJ*V5M#Gb986fDHXP#`yP^Q`dr- zKLh~sgD-dY_Z&0#3$9X03d#K=WR%Bvp@>Z}PW5(#K%B;nTaPOGE>16`3pHwr{*{|fkG&0S*243uJoy{H}`lW4L2JnN~ zfsQ-ov-`69FSoLP?_b=LUI$L!|HpLyot>P0z(impm>hs5SSzm7E7%R4GcHV=4Z{FP zAHP+1iOkZ`EUM&`G#V3HF%CW$|D9(tr$3aYC%laj!&3~CxvqpP=^*|(<=$Pcj|~8@ ziU@Go->eM3T!hPc!0pw_IR=2L2+ecak6mqugP71ny9U0cKo3QRe4gSr9@Itb7A`PX z4bkHSLDay1+7=$7lGQ5Aq`hAC-Mj=qMt3nux0>+gT!hVadmFD>ZUg{DWRnEj1;(xV z@}u6a<8rfCx%C@aW)O^89Ngk9Ap4W=d)!GP9K&bdM1zN?krXaf^4?r zMO>RXeS*{w#o_mNHY@YW0K_PV%v!egg^z%0#je_yr$djh(9kKY+RfoiMF^XQ^M-GQ zc98(If|!Nf3x1TIU}GZfD`|{|Z&N3ivBnK&Izia%+!!!0Ghv_y5>a@Ns=2$w*<8;z zM`|u=qD=%8nqDUEyZ@$kH1T%Vy zt4rUs-0BJgF+2}Kt~{F(oT?x*d(u~X;k>LEK{j;I2%iS4x&*a~M?(RZzcQ_XAe%N7 ztM#;kHDiAGTdDh9Uw#cX0D;34T=#|72Zj!N-|0IPfld<7dPv!g3Yvn>f|Lk4 zux3Do>mV&Ubs^;EEe5etAJq`M&DJI~B3J;bJv`~eLGOr+A6{L`c)fGv;E5h<+!;{{ z5hqne&)Ki}?MrC@q4Y3Rg~Y_&9IXjE5@#a`3;<58g-v~DDQ=-!v9NSIiTpP?OECSc zruh1UIfRXc%-!7)9BqSw=@;w&Zu)Vd-rfh^)%$Uw)f5s!u&)Q%Fo0KIYwj-zwGg1a z$##BR&_iA7BU~&bP9~rKb2rVB^Hz^-!vbF6e|k|;osSKzsAYNiw^(%$g>W_qysWi; z%Zg5u6-?^TB`!6S4fS@Z#$@9OTEZEhI@?zgQY+D>{ogKqIa635qbxG-v#d;yI>?-; zhF7smK03oV1lm)tC*55WZ5rOKe@{tcA_X8sWLB#=GJTik6}yE?ZYDyZ=zK7C);^lz z*$9MJbIS(SzoSQs>9w5tZh@+X0=(MO(aS^)3r#-+CUq6bmYWHgIlK{dmqG{wig`S8pfm|F2^=gk|tf|ut=n@bMB*%?O;^t;^Y)vEos zQU;E{Vgy0PB9h9E>(|~S*fi{4^z7J)0s!g+%)XCYtxB+&+h{SA&7}ii><>eG(9(a0 z7Vx{4dvtA$05G9=7|&H3g3=64!cBn(S~H+zdFr*`*8ZbW_*2u-iPC|I>X+BiMUn|};rZE-2bDR&(r)mzz zq!4bYUTx13#zALc1QCvWKmdJZ6rE|B{$^eFJp-Q!pVpdzJM&0cwpE=jYj>kbylL5+ zbt$V~iv_D0whASzhr>a67_G<{u#H>v@wwcDa9G(tNb4BAsZT_aun z^^M9RcXd{E=|(AIAq0|z2qI(8Rbi`13^<>&{+f{09=RHy>+BJ2`SM3Lnwr;2ci{4y zxHYh7b5aAW>dct$%|t>Ce)GIt-Lg?~Wr()hi3y*#wMjGh>r$yPpP&9JmsR^x#%jBP zi%(e69Vwh|4Aw7Wg;LV;bp@ASpk2xr9#I5OdL)<3RCsZ9gC>X53x~VlQ%Kn%3CM7RPL(IAS}|WQ)n)8ZM!NFuI9~8 zcWj9jUKQ5FY`q=wyC`(wR>c`FNG11wiO~xMR;Zg_FN@Aaai!{Sgm0$dfB*q9Ag5~Y zF58h?_0#CAV^oaai8fh{Ej}^POj)S(A;Uu{5i- z1fU8IEI{3`{y4Y5Md>k3Q<8!H2KJ>g2W;L%hzvURJf)@Hat?7c6xKMJM!Krz0ulu1 z@ByTW*Y`LVcvt@~Q!@W|GB9E-A)vLE%`MQPyqI$>3GF-qFGI5mWC=nB1N7^S?+y?y zD*4W_H@n2x#NN1=c_}l^$BI?Od8QQ^c`=P{Jeas_aKPTUBJ(;7Jq%(dZ!Wz4>H=p|If*~T7Q8^;nz`}jE_13n zL)W>8X*7es3R5xC1`XTkRyLs01uhQdUys*QFggkK0ck6s05lF+8NHvp4!usiOsj58 znA%Qo%+~2#QRYTxlhNTb`4P}%-!-{bINGx(Z%RwcOA~DcLnm`1X^$gh*WPtUjq#FIq7N4W7R5oK18F&_bVl@OWfOf&ff| zzyP{s8!{WvZf3{L0mbh=Bp`QII(*Cil~Sh7%Hq7)6->}or*lkiA~ALl-A;>?n+d`( zTz{R0G=5}BLj_90h6PAX*B{%>Bfo|UUcSTFp8F4~RUvN>(;~#n(AQ&Q2=^HRK6gQ>}q&0{q=@DnV)n(yK&j$lCRO0l;Pz7lsfHXhZ8yd-X7!u_n#GTWVfpK8$r#$5$vaJ9OdYk+mq9S=e`^BL zqMsicS(6sy%a;Ae?qCiz}xzI)q&PnOSSFd3`}rWB24nv=q;adu3W z!~q@cZGWZo4|oiN2nFZfHJ%TnD(y&Go>BrBL5hw_-;DqYhyI|)zL{<&mj(WeFbZ++ zXOXedL&{Jv(t9uBQKqXygPlJp_KT#h8f5=_M35qT?O}bUpGlX!7q||x?;sBaJa&{cY`Q1q z4j_tT+BsVkodaA5E+a{P_Pe` zzcYJCReNwz2DcLwY*)&Njkv!AFh{>mf7d>#>jK5r%;Bc3MyEg_Q;AVVie9qsgKne` zY+N2;fSY9czbQMpdfcY6VD*n z;tT+eB;eV89k(xX)x82jFY%Tj_uF3>U?(Rawi{d2)Z@fVzX=ON6bU)H`y~ci-T8*L zD~?@P`_*XUK^Nmbx=aL7j=koaZvW{RWp z$TxShLl_DUh4+j7-Q-zgR$=e-I9DGrTY+W?hAQRq+P$&TmFL;2*$Z7Y%Os2G#+Kld zlqf_$Sssp``m!2`P6flPGww+B`jS1-?kMAZDa^J2v>NGUD%OfJ(UR((@jnM&wO4{- zyD_ZmdBl$kL|L*r6q>?*ab3xJ$f0Xt+*bU0)A~GkOTa3{1y09#6;AL^@&tH{-~3O` zkx+=uZGFeXImDj)k;;Sr6vIA`UCAaZQZCDO!P+F+tcG`s1kxgjiDrjrNKC>5b^Vnr zCJqwReQ6SH{*!l$8nHxxE*Qg^jm>_xeR>@56F8>5ca?`lsS7-;|g4z7}?GZI-TH*?X>ar1}mtGxD?L=tJoHlM;66#6;X^qIYyd%#`Uk((dQ^k-Yw`y7uRb3CUvqk zq0mFOo8dYB!u^ZA>X$*S{R1j|myLJ1*02Lucs&$dw%) zHvlpJixy^|3w{k}CcM$T<7h#}jjI&D`Eg%zBUXZLXI_i3dp`9+t1Pd0rVE>1YeZ(0 zyS`hT4rKlA&t_3}BH1qvilJ{FZ{7w}e*~BRSVAvKJt?gfkAng$*80~9H9v4BV=3=f zul8qh5BNEZmMwf(UV*%pgl0rs%_l3J^WlZ+Y=`$}XbvbqA3u9z z`_TW51m>@T1v;fbacT@U&(LxnYQ zhilnC9UZ2Z#BIbVFe|=-p)oiHh!fP5#jMk9+zNbysiwTns zK&X3i>(x#a!bL5ty87Vdd>UE{!xw41OZgd1WEh|h-p~qhOY~~q+*h#Fm|w-tB(uKR z5EanU2`*o*%B;MgFv$_%zG_ma?<<1oBi3p7|Wc|zsC&vlGOqpDWcRfb_>uYar4yZDY;)0nml*U z=OAr9By07|zuo068hvP42SPZy`GOc0*JpD}joxFfrZ~v7o>DqxpoxsG0i`>$e{JBk zHH_AqWF_*cjXajB4|d|S5Lu| zO-f#T&iv4PyGpH-n&)I%=FhfK(4(mpaxJS!i6U>&k#}yyArvWwE-DM58T`e#Av!6i zr568kO0~=C0nIo`tGs@{fAFhe0H3o7Zh2J@9k>~;lYL!G9mLrI2UeJTUwF;8^SYWKB) z^Jl=_v%4>29_PZ#Ugucn3d^LIE$4yv=B-RY%oqMpNv8X}0LFk6AHBPV!?Cmddh6MM zxqwXHg_fVke6`mrH@ThQKTVnS(bv(?ee1im#mh3%pj-Mty_246x1gnw`^jsJK$^RO ztMk22x6${^Crq#JdG96fGv|peIZj*DnN7d{H1Cux3OvE4#Var}8y=IP|37I*FYSbS zrZa4a-D?%+o5HR&%i%J6pOX(pfBmO5ll}ZF*tD{PPhh0(<)2ElX_Rj&j3PdXtj z*BNSoVDG2qz`N}D4lN)+pj&fij%%eESw7W1Q9-MBs&u`T_~pn>JM8mDYttNo%m=mF z`~~9c+wrp*srnQBGC;#tzmee;dz6=g`g(c(tb&$g;_K)2R6Uo|iPradKP*SY4RPDB@xBw`ldn~hYBvN}Z{(6!S2YY-viEyH zORU=o2F$|`&s~A%gc2Va*Jy+ScB$OovQJ(JCV@EK6CU?KDC1@65|R%FrTN;vsLpeZ ziqV)G;jr$-9gI2bo?uh|RVcS!jJoPEkUyH+J-i)t_mVFHKM70cG85z}*|aBPb1}me zk`qywwhYUB{d*^8S%ck?QxvO8BN~j#rr?sZ&@~w_4Ib_yf2?~KUeVVCT9mf z6dx`)c(D^a|MJb;57`p*5&IjFW}{a|P!iTl!Q*<`Vp?p$=BST>w9eRFQ3(cbgvZ}M z*!=s)wConE?p^26vj_ipRd0}zpIF6xZB0`7Uf}E(scuDs>m7xy#6yNgoW1;4yoUDM z&qj6Z0qf1{Tt#`*!Jjn&s%udlUflo4E+k+5!oe0oJ;_=%FGuWA{-sK<9o0hJvE8Af z#<` z`gYewQqx3t^32d;dw{-A$KcLb zs?&+49#rFFAYaXTB_&UvVi1>%m@FEZ3)z>J6c>*9{lKZ*@t}nN?UTL5iL%!wE22F6 z%XUSIFD<(^xyFXn3n$QR7ubUfxi_$4B0-qFIMtbqlDhVy&Z{ES&wljCG;ZMIH@wVzuvyr(NB7>ahw0D5CGHUmzWPLBGqcYI za-BzMCiEy9IgFue?C9skI2h0qtvNu|p6}NVRk_0(qeiFdSC}wU!+AED1inrmt3Q8C zZ2QHhD%@|lJjc&uv2Xp}==dBSAi|QAF73ah*Mk1K4IS`|+kUz}Et<)_^`UvkJeAdl z{L97x8lBhw;Y;PO*4e*#wD?T#+~gP8c>>)C)TOGM8+YXhS6|D`j_&fpjIgTjmRxrM zQ}B>GdC78H85ulCB)rk=_;O~?()(Vm^xzp7cb`7(k~6RbeRGtim^Z7#>;lM2gFtK()MW8%X+ zmz!kCWE}^|=~jel2?m}I4k8`nyz!DAd%ea8dR7@4nIECh+g`|}1LLvdZ_#t)z+XD2-sZNt9-&h;z(v?HDE?{VuilPlVUvv~-%CAC zdX-#`G6pMb3N>N?#)&0Jz1D+RouWxdkfosV@RrYXb6m)q#cy`GMaCg&&=wQym~H*G zKYZeT-!@|1g4HaP;NzZWq$7E+{FW+1T_X$Ai(?I=f&n{?k()`vR}~F?kIQ&zDKS_V zA06~)u7p{!;#E4k8{LD8U5UY+g-YApX=DhZk zeBad>?)_}NFraz&vZMMboakZQBS>e6y4U>KgOUwuia_osYg#SiSb6)D*o9963|l6B zQ!yqakCjxAL`9@8j|DXK18WzXYUx_na*rvvFN(c75x-WPJ9^?T40AtCT3oUjv{T1T z9^C(Z{ZurG#EnDjdEEO?Db@PX7wdeH9r6lNEGrljspZo&Ct~v)3ZFvL9i%8qDXwwm zsW<(rW}d68#_*&i{&`m=wXVbGRY=j1a)A|Qo2Ry~FlqdP!6E2VK^&|;UoMuU{4Cal zVkA?!XKJFfYD!zCqXIg{Z~5Y5d$7TT4)i(264f7HN&j+ zT8T4e>Md5S-~0sP6P217IqmP#(8+(2?WY_CnR!dU`S1P6@rRnT z!sper$VML17tiJl5bmoI*P75MVr*m39EYKf;zcXR#A&+VA3C}X-xhlq9foauk4&V$ z)7DYqmq@aR-%Kce`R<$h2`VX}#AeZ2uQ>ch;#;;BNhl+)lXC*l&q|CLfkR5E`YsZQ z{aw!Z?KA8Fq@!K&&vD-?_ZhqwwjBefXz2g`UYS-J9Qtd3|gPS3L;3BCX$nlgtUy_PX zzsTJim`rwBCX4CV!B%ohDPOpi-CQ}?A;@F9X-0}PF6j{J*9|Zf2(W+j+`&s+EQ!c! z6FtDEI_j^~jjCy7FF2|>ac4Bra|||he)(&z9A15TEOSG;G)C%$O>{X%YUVv^>x269 zDbU+(m?$~6ersovskn(nivx6hJMHh>Mc&$lWw5w4p(Tr}-upSZ#)M(6?Rx`|HcM>S zkQIMXqjW=fa`kOfHdf%l>9cg=)C=%9gK3PC3N`fyZ~K!X2Djl4(mwYp^C8!YpVHGK z#*d2ay0yAVt#J}i?as5rU8Zqa&EyNB@t$Gkf?i)YL!XVrd+&Sp>U|c}t4CV9S%sUp ztvvhu>LbMt9kHRI7k5>;=1JcqtC`;tsRX%3Wdm|Bh5V8fJKxnkxXMt}sHVu;`_tHl zpffJ>si)Tf14)vFeQ^lff=b~2lPgR6hU3?H6(n_a{f5-y1H9SJ5G4ls?9}F(3y5{4 zmA5Ed_oLyRZ|C`nI#p95FRkZF_{+ua+9BbZ-fd=pxZPNw7FO>0{Tbj#P)*BO^uv?I zKt(jTl9eQ_EpRs9A=%&YMb<*b78&J&GOugH1-=sLOzrN;X_S+{$xN4(o#re4gh~Q$ z1;b7cB_|Ny$1kXuQw1Bgsa>wi;}8RrF?#jgm`FIk+71bST&sWj(&Vo*_3Fx3c!aT$ z0>6w8Gg_iRWt?kv8f^VPo_2@efA3=$0NF5-PF628Gr^*+T`yAhrvmkVV_Y!h8ao)j zT#lJ92KDr11#j1fr&g5tu~~mqT2i*EwkZf8jja@lbMC8zD_+fFZ)b8pSg}3=eeBP{ znIt}#Ic@VW(s?*Di)Tt5+H} zHWXuJd;#7@>j~eA93o?xe5Crp3rlU(bpzeS!Pen|)n5dMcr)9y!a0(-Xz=CWLnYsU z)#0GnPAP-ILB_s;h-jlmbL4QU0RTF;3{hCD{1cHEPx;Le7U2}!*6kMViHKXdZr7A` z4BOi*GcVes#Ki?1g9|3r4_K&C>*Y67h-&3|Rf1IzbrYcgdwS0}7&*0x; z^V8~JlezU}CS-kxWfSu5DV42rd_DQuvC1p|7p*H1+4X;jkgJ~xu10rHp8i%XPqH2ZDnbanYhd=rZ)? zr8}v>;}Qpv{KVwvP7HTA0neoF)OWed(y|?N-`6iZQtpA-}-%sBa6klJ|1{`DvC} z#4-NuB-+io%DddjUmZjw6BIrHQ`A?6%l`XBRzI^9ahdz|=ZcsSXHPMC)%-S|Qv@hj zmNzomHcmqAFs|cPhaz5?OAzy;g-Nf_8Zf0;e>7Eg^__+0xEupW;J5E z!SkFyj+luyoKY@x{L>I^|LlG@j=yqkRK?o_@bFJO9WX znWrPM0WCf>q7;H!pvkcQ7O$RJ)e=b5#&_shZPrDp>h%w z_3#a|D1*OG!$rRhiOVh%K9!JD;RJ{&OgCiq*$xgc1Jw zC{)iKc0Ops`&_u)prgCuop9q>_@ZHnbBM>6OY1OVVZHNnr`bMvk%3lED&~M(qW4q9 z&y7RG*1{HYL{ygrxxxYyx4Mb+WQnA__G=c{I}~kshTbd^exp`HLeDadyA`zYR!DDB ztKo;*p5e9Fe4#NNj<_$Fikjbuonax%zjGNAbZSJDv4Xlw+`4ml~0DnKd8r0l1KOPFSC$I%(L^HjmXwg zwtaVCVT%7^+9WAfF#H(8tIhUfUkuU|N{iYsQCx?eClj3BmqFeqaze&nhw~3{7{|(6 zRwAHL!Q>4DkIuouUp!blN-Rj!gLvM$$%N&^f5S2cc*v@BKQ%U@CiAd9kn79s48>hr z2(7QmG23u|AzC=W1{l(^@o8pHIo=fU&7rjNe~xgPk~b9sRZz4r7Y=Tf4X@5W>T0 zOysqWuUQqNpp_cFSX8w^$^9^PVET|SaJ`Gu0; z%!|j3d)sB)b6AFSU*^a}!k8$=p3oJfRtk>GNj+Sw@*0u1Nq*H^VNuo1 z53)XVyKc8~2CzW3Jo-&}CQ`vs-m19yy6Yn;k>NLV18ZD2@z^Sf5&SqzhR+=g1~DtQ znzyq{eoctikPURln(WBn;Qa4P{ z*RQA%fD%$^J;&VX{Zug^w8Nuaf;6>%nmtZLV85+|cVig(#$BBC;WxmN;%!U2?)S&F zn*bzvKlIbQ?@}YIGi;t9AU5a7uHqnA8;0Pp zHN$FPQ?%Z@QPiwMY6OlIkA;hZ>3ZN$i+IVzOi=ZX)pL3yw!%l%Kg(ljUb^;hlv)ss zxcgtPC+T)1YpW*qwU=7fh~+Ci6f3=Ah5`h25vn4sY(&p>`$yPb<~6fNBrMm3`Fo7~ zoqs^?wdgCY+Av7+Nx>5VL5J7xR_9lpT%#Lvk7LN%?wdmMDQ%64^Xi#p&={2ZxEE67SIM;Q*BzReppci4FKdHd>gX%JPvqQ*#$%xQhNNee+P zzvbRdMC_hzdsc)TO~=~NwtsitEhbY(LOq*kuSsGw9$PvlaP?U($l5#MQqXw`oSHG8 g``OZ3M*S!iQl?C>>6BlKo3oZ%w*0TNvj6`6e?ymUuK)l5 literal 0 HcmV?d00001 diff --git a/bun.lock b/bun.lock index fcca1c89fc..d200a55b1d 100644 --- a/bun.lock +++ b/bun.lock @@ -127,6 +127,7 @@ "idb-keyval": "^6.2.2", "mitt": "^3.0.1", "nanoid": "^5.1.6", + "polygon-clipping": "0.15.7", "zod": ">=4.5.4 <4.6", "zundo": "^2.3.0", "zustand": "^5", @@ -1794,6 +1795,8 @@ "png-js": ["png-js@1.1.0", "", { "dependencies": { "browserify-zlib": "^0.2.0" } }, "sha512-PM/uYGzGdNSzqeOgly68+6wKQDL1SY0a/N+OEa/+br6LnHWOAJB0Npiamnodfq3jd2LS/i2fMeOKSAILjA+m5Q=="], + "polygon-clipping": ["polygon-clipping@0.15.7", "", { "dependencies": { "robust-predicates": "^3.0.2", "splaytree": "^3.1.0" } }, "sha512-nhfdr83ECBg6xtqOAJab1tbksbBAOMUltN60bU+llHVOL0e5Onm1WpAXXWXVB39L8AJFssoIhEVuy/S90MmotA=="], + "possible-typed-array-names": ["possible-typed-array-names@1.1.0", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="], "postcss": ["postcss@8.5.23", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="], @@ -1868,6 +1871,8 @@ "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], + "robust-predicates": ["robust-predicates@3.0.3", "", {}, "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA=="], + "router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="], "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], @@ -1916,6 +1921,8 @@ "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + "splaytree": ["splaytree@3.2.3", "", {}, "sha512-7OXrNWzy6CK+r7Ch9OLPBDTKfB6XlWHjX4P0RU5B3IgFuWPeYN0XtRtlexGRjgbQxpfaUve6jTAwBGWuGntz/w=="], + "stats-gl": ["stats-gl@2.4.2", "", { "dependencies": { "@types/three": "*", "three": "^0.170.0" } }, "sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ=="], "stats.js": ["stats.js@0.17.0", "", {}, "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw=="], diff --git a/packages/core/package.json b/packages/core/package.json index 65312cd035..4503cba3b2 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -16,6 +16,11 @@ "import": "./dist/utils/clone-scene-graph.js", "default": "./dist/utils/clone-scene-graph.js" }, + "./structure-kernel": { + "types": "./dist/lib/structure-kernel.d.ts", + "import": "./dist/lib/structure-kernel.js", + "default": "./dist/lib/structure-kernel.js" + }, "./scene-migrations": { "types": "./dist/utils/scene-migrations.d.ts", "import": "./dist/utils/scene-migrations.js", @@ -97,6 +102,7 @@ "idb-keyval": "^6.2.2", "mitt": "^3.0.1", "nanoid": "^5.1.6", + "polygon-clipping": "0.15.7", "zod": ">=4.5.4 <4.6", "zundo": "^2.3.0", "zustand": "^5" diff --git a/packages/core/src/commands/structure/apply-zone-transform.ts b/packages/core/src/commands/structure/apply-zone-transform.ts new file mode 100644 index 0000000000..793ba0cf52 --- /dev/null +++ b/packages/core/src/commands/structure/apply-zone-transform.ts @@ -0,0 +1,88 @@ +import { containsPoint } from '../../lib/polygon-boolean' +import { roomFloorPlate } from '../../lib/room-floor-plate' +import { runAsSingleSceneHistoryStep } from '../../store/history-control' +import useScene from '../../store/use-scene' +import { + type NodeChange, + type StructureNodes, + type StructurePlan, + structureChangeBatch, +} from './shared' + +export type CeilingHostAssignment = { nodeId: string; zoneId: string; offsetY: number } +export type SupportHostAssignment = { + nodeId: string + zoneId: string + field: 'supportSlabId' | 'deckSlabId' +} +export type HostedZoneTransformPlan = StructurePlan & { + ceilingHosts?: CeilingHostAssignment[] + supportHosts?: SupportHostAssignment[] +} + +export function resolveZoneTransformHosts( + nodes: StructureNodes, + plan: HostedZoneTransformPlan, +): NodeChange[] { + const changes: NodeChange[] = (plan.ceilingHosts ?? []).map(({ nodeId, zoneId, offsetY }) => { + const node = nodes[nodeId] + const rooms = Object.values(nodes).filter( + (candidate) => + candidate.type === 'zone' && + node && + 'position' in node && + Array.isArray(node.position) && + candidate.parentId === node.parentId && + containsPoint( + [{ outer: candidate.polygon, holes: candidate.holes }], + [node.position[0], node.position[2]], + ), + ) + const room = rooms.find((room) => room.id === zoneId) ?? rooms[0] + const ceiling = Object.values(nodes).find( + (candidate) => candidate.type === 'ceiling' && candidate.zoneId === (room?.id ?? zoneId), + ) + if (!node || !ceiling || !('position' in node) || !Array.isArray(node.position)) + throw Error(`Reconcile the copied room before assigning ceiling fixture ${nodeId}.`) + return { + op: 'update', + id: node.id, + data: { parentId: ceiling.id, position: [node.position[0], offsetY, node.position[2]] }, + } + }) + for (const { nodeId, zoneId, field } of plan.supportHosts ?? []) { + const plate = roomFloorPlate( + Object.values(nodes).filter((node) => node.type === 'slab'), + zoneId, + ) + if (plate && nodes[nodeId]) + changes.push({ op: 'update', id: nodes[nodeId]!.id, data: { [field]: plate.id } }) + } + return changes +} + +// The store's synchronous subscriber (or a headless caller's reconcile callback) +// must create the ceiling before its copied fixtures can name that host. +export function applyZoneTransformPlan( + plan: HostedZoneTransformPlan, + runtime: { + getNodes: () => StructureNodes + applyChanges: (changes: NodeChange[]) => void + reconcile: () => void + } = { + getNodes: () => useScene.getState().nodes, + applyChanges: (changes) => useScene.getState().applyNodeChanges(structureChangeBatch(changes)), + reconcile: () => {}, + }, +) { + if (!plan.changes.length) return + runAsSingleSceneHistoryStep(useScene, () => { + runtime.applyChanges(plan.changes) + runtime.reconcile() + const hosts = resolveZoneTransformHosts(runtime.getNodes(), plan) + if (hosts.length) { + runtime.applyChanges(hosts) + runtime.reconcile() + } + }) +} diff --git a/packages/core/src/commands/structure/create-mezzanine.ts b/packages/core/src/commands/structure/create-mezzanine.ts new file mode 100644 index 0000000000..24efa56c80 --- /dev/null +++ b/packages/core/src/commands/structure/create-mezzanine.ts @@ -0,0 +1,73 @@ +import { GROUND_SUPPORT_ID } from '../../hooks/spatial-grid/support-host-id' +import { containsPoint } from '../../lib/polygon-boolean' +import { polygonInteriorPoint } from '../../lib/polygon-label' +import { type SlabNode, ZoneNode } from '../../schema' +import { getStoredLevelHeight } from '../../services/storey' +import { isFloorPlacedIntent } from './mezzanine-content' +import { + type NodeChange, + type Point, + requireZone, + type StructureMintId, + type StructureNodes, + type StructurePlan, +} from './shared' + +import { validateMezzanine } from './validate-mezzanine' + +export type CreateMezzanineInput = { + hostZoneId: string + polygon: Point[] + elevation?: number + thickness?: number + mintId: StructureMintId +} + +export function createMezzanine( + nodes: StructureNodes, + input: CreateMezzanineInput, +): StructurePlan & { zoneId: string } { + const host = requireZone(nodes, input.hostZoneId) + const level = host.parentId ? nodes[host.parentId] : undefined + if (level?.type !== 'level' || host.floor?.support === 'open') + throw Error('A mezzanine needs a host room on a level.') + const polygon = input.polygon + const zone = ZoneNode.parse({ + id: input.mintId('zone'), + parentId: level.id, + name: 'Mezzanine', + spaceRole: 'room', + hostZoneId: host.id, + polygon, + seed: polygonInteriorPoint({ polygon }, true), + floor: { + support: 'open', + elevation: input.elevation ?? Math.round(getStoredLevelHeight(level) * 10) / 20, + thickness: input.thickness ?? 0.2, + }, + }) + const invalid = validateMezzanine(nodes, zone) + if (invalid) return { zoneId: '', changes: [], conflicts: [invalid] } + if (nodes[zone.id]) throw Error(`Duplicate zone id: ${zone.id}`) + const hostPlates = Object.values(nodes).filter( + (node): node is SlabNode => node.type === 'slab' && !!node.zoneIds?.includes(host.id), + ) + hostPlates.sort((a, b) => b.elevation - a.elevation) + const pins: NodeChange[] = Object.values(nodes).flatMap((node): NodeChange[] => { + if ( + !isFloorPlacedIntent(node) || + node.parentId !== level.id || + node.supportSlabId || + !containsPoint([{ outer: polygon, holes: [] }], [node.position[0], node.position[2]]) + ) + return [] + const plate = hostPlates.find((slab) => + containsPoint( + [{ outer: slab.polygon, holes: slab.holes }], + [node.position[0], node.position[2]], + ), + ) + return [{ op: 'update', id: node.id, data: { supportSlabId: plate?.id ?? GROUND_SUPPORT_ID } }] + }) + return { zoneId: zone.id, changes: [{ op: 'create', node: zone }, ...pins] } +} diff --git a/packages/core/src/commands/structure/create-zone.ts b/packages/core/src/commands/structure/create-zone.ts new file mode 100644 index 0000000000..55e35042e2 --- /dev/null +++ b/packages/core/src/commands/structure/create-zone.ts @@ -0,0 +1,170 @@ +import { area, intersection } from '../../lib/polygon-boolean' +import { polygonInteriorPoint } from '../../lib/polygon-label' +import { segmentsIntersect } from '../../lib/polygon-relations' +import { extractRooms } from '../../lib/room-graph' +import { type AnyNodeId, SeparatorNode, type WallNode, ZoneNode } from '../../schema' +import { getWallCurveFrameAt } from '../../systems/wall/wall-curve' +import { planWallInsertion, uncoveredWallSegments } from '../../systems/wall/wall-topology' +import { setZoneIntent, type ZoneIntentPatch } from './set-zone-intent' +import { + applyToScratch, + boundaries, + diffStructure, + type Point, + type StructureMintId, + type StructureNodes, + type StructurePlan, + structureChangeBatch, +} from './shared' + +type Edge = + | { wallId: string; face: 'a' | 'b'; t0: number; t1: number } + | { separator: [Point, Point] } +export type CreateZoneInput = { + levelId: string + polygon?: Point[] + boundaryIds?: string[] + edges?: Edge[] + name?: string + intent?: ZoneIntentPatch + enclose?: boolean + wall?: Pick, 'height' | 'thickness' | 'justification'> + mintId: StructureMintId +} + +export function outdoorRoomConflicts(nodes: StructureNodes, levelId: string, polygon: Point[]) { + return Object.values(nodes).flatMap((node) => + node.type === 'zone' && + node.parentId === levelId && + node.spaceRole === 'room' && + node.enclosureStatus !== 'open' && + node.floor?.support !== 'open' && + area(intersection(polygon, { outer: node.polygon, holes: node.holes })) > 1e-6 + ? [ + { + code: 'outdoor-room-overlap', + nodeIds: [node.id], + message: `The terrace overlaps ${node.name || 'an existing room'}.`, + }, + ] + : [], + ) +} + +export function createZone( + nodes: StructureNodes, + input: CreateZoneInput, +): StructurePlan & { zoneId: string } { + if (nodes[input.levelId]?.type !== 'level') throw Error('Select an editable floor.') + if ([input.polygon, input.boundaryIds, input.edges].filter(Boolean).length !== 1) + throw Error('Supply exactly one polygon, boundary set or edge list.') + let scratch = { ...nodes } + let polygon = input.polygon + let segments: [Point, Point][] = [] + if (input.boundaryIds) { + const selected = boundaries(nodes, input.levelId).filter((n) => + input.boundaryIds!.includes(n.id), + ) + const faces = extractRooms(selected) + if (selected.length !== input.boundaryIds.length || faces.length !== 1) + throw Error('The boundary set must enclose one room.') + polygon = faces[0]!.referencePolygon + } else if (input.edges) { + const edges = input.edges.map((edge): Point[] => { + if ('separator' in edge) { + segments.push(edge.separator) + return edge.separator + } + const wall = nodes[edge.wallId] + if ( + wall?.type !== 'wall' || + wall.parentId !== input.levelId || + !(edge.t0 >= 0 && edge.t1 <= 1 && edge.t0 < edge.t1) + ) + throw Error('Invalid wall edge.') + const count = wall.curveOffset ? 64 : 1 + const points = Array.from({ length: count + 1 }, (_, i): Point => { + const t = edge.t0 + ((edge.t1 - edge.t0) * i) / count + const { point } = getWallCurveFrameAt(wall, t) + return [point.x, point.y] + }) + return edge.face === 'a' ? points : points.reverse() + }) + segments.push( + ...edges.map((edge, i): [Point, Point] => [edge.at(-1)!, edges[(i + 1) % edges.length]![0]!]), + ) + polygon = edges.flat() + } else if (polygon) segments = polygon.map((p, i) => [p, polygon![(i + 1) % polygon!.length]!]) + polygon = polygon?.filter((point, i, points) => { + const next = points[(i + 1) % points.length]! + return Math.hypot(point[0] - next[0], point[1] - next[1]) > 1e-8 + }) + if ( + !polygon || + polygon.length < 3 || + !polygon.flat().every(Number.isFinite) || + area([{ outer: polygon, holes: [] }]) < 0.01 || + polygon.some((a, i) => + polygon!.some( + (b, j) => + j > i + 1 && + !(i === 0 && j === polygon!.length - 1) && + segmentsIntersect( + a, + polygon![(i + 1) % polygon!.length]!, + b, + polygon![(j + 1) % polygon!.length]!, + ), + ), + ) + ) + throw Error('A room needs a valid polygon.') + if (input.enclose === false) { + const conflicts = outdoorRoomConflicts(nodes, input.levelId, polygon) + if (conflicts.length) return { changes: [], conflicts, zoneId: '' } + } + for (const [start, end] of segments) { + if (Math.hypot(end[0] - start[0], end[1] - start[1]) < 1e-8) continue + const walls = boundaries(scratch, input.levelId).filter((n): n is WallNode => n.type === 'wall') + for (const [a, b] of uncoveredWallSegments(start, end, walls)) { + if (input.enclose) { + const result = planWallInsertion(scratch, { + levelId: input.levelId as AnyNodeId, + start: a, + end: b, + joinRadius: 0.001, + wallDefaults: input.wall, + mintId: () => input.mintId('wall'), + }) + if (!result.ok) throw Error(`Cannot enclose room: ${result.reason}`) + scratch = applyToScratch(scratch, result.plan.changes) + } else { + const separator = SeparatorNode.parse({ + id: input.mintId('separator'), + parentId: input.levelId, + start: a, + end: b, + }) + scratch[separator.id] = separator + } + } + } + const zone = ZoneNode.parse({ + id: input.mintId('zone'), + parentId: input.levelId, + name: input.name ?? 'Room', + polygon, + seed: polygonInteriorPoint({ polygon }, true), + spaceRole: 'room', + }) + if (scratch[zone.id]) throw Error(`Duplicate zone id: ${zone.id}`) + scratch[zone.id] = zone + if (input.intent) + scratch = applyToScratch( + scratch, + structureChangeBatch( + setZoneIntent(scratch, { zoneId: zone.id, patch: input.intent }).changes, + ), + ) + return { changes: diffStructure(nodes, scratch), zoneId: zone.id } +} diff --git a/packages/core/src/commands/structure/delete-zone.test.ts b/packages/core/src/commands/structure/delete-zone.test.ts new file mode 100644 index 0000000000..93124a5199 --- /dev/null +++ b/packages/core/src/commands/structure/delete-zone.test.ts @@ -0,0 +1,242 @@ +import { describe, expect, test } from 'bun:test' +import { reconcileLevelStructure } from '../../lib/structure-kernel' +import { ItemNode, SeparatorNode, WallNode, type ZoneNode } from '../../schema' +import { SHARED_WALLS_DELETE_MESSAGE } from './delete-zone' +import { deleteZone, divideZone, setZoneIntent } from './index' +import { applyToScratch, type StructureNodes, structureChangeBatch } from './shared' +import { apply, enclosed, fixture, mint } from './structure.test' + +const zones = (nodes: StructureNodes) => + Object.values(nodes).filter((n): n is ZoneNode => n.type === 'zone') +const boundaryIds = (nodes: StructureNodes, type: 'wall' | 'separator') => + Object.values(nodes) + .filter((n) => n.type === type) + .map((n) => n.id) + .sort() + +function chair(id: string, x: number, z: number) { + return ItemNode.parse({ + id, + parentId: 'level_test', + position: [x, 0, z], + asset: { + id: 'chair', + category: 'chairs', + name: 'Chair', + thumbnail: '', + src: 'https://example.com/chair.glb', + }, + }) +} + +/** The 8×4 enclosed room with an island Divide made in its middle. */ +function island() { + const { nodes, zoneId } = enclosed() + const graph = apply( + nodes, + divideZone(nodes, { + zoneId, + path: [ + [3, 1], + [5, 1], + [5, 3], + [3, 3], + ], + closed: true, + mintId: mint(), + }), + ) + const area = zones(graph).find((zone) => zone.id !== zoneId)! + return { nodes: graph, hostId: zoneId, areaId: area.id } +} + +/** The 8×4 enclosed room split by Divide at x = 2. */ +function split() { + const { nodes, zoneId } = enclosed() + const graph = apply( + nodes, + divideZone(nodes, { + zoneId, + cut: [ + [2, 0], + [2, 4], + ], + mintId: mint(), + }), + ) + const other = zones(graph).find((zone) => zone.id !== zoneId)! + return { nodes: graph, zoneId, otherId: other.id } +} + +describe('deleting a room', () => { + test('an island merges back into the room around it; its items stay', () => { + const { nodes, hostId, areaId } = island() + let graph = apply( + nodes, + setZoneIntent(nodes, { + zoneId: areaId, + patch: { name: 'Nook', floor: { finish: 'tile' } }, + }), + ) + const item = chair('item_island_chair', 4, 2) + graph = { ...graph, [item.id]: item } + const walls = boundaryIds(graph, 'wall') + const plan = deleteZone(graph, { zoneId: areaId, contents: 'delete' }) + expect(plan.conflicts).toBeUndefined() + expect(plan.payload).toMatchObject({ + mode: 'merge', + mergedIntoZoneId: hostId, + wallIds: [], + openingIds: [], + itemIds: [item.id], + }) + expect(plan.payload.separatorIds.sort()).toEqual(boundaryIds(graph, 'separator')) + const after = apply(graph, plan) + expect(zones(after).map((zone) => zone.id)).toEqual([hostId]) + expect(boundaryIds(after, 'separator')).toEqual([]) + expect(boundaryIds(after, 'wall')).toEqual(walls) + expect(after[item.id]).toEqual(item) + // The host's floor covers the whole room again: no hole where the island was. + expect((after[hostId] as ZoneNode).holes).toEqual([]) + }) + + test('one side of a split merges back into the other; every wall stays', () => { + const { nodes, zoneId, otherId } = split() + const walls = boundaryIds(nodes, 'wall') + const plan = deleteZone(nodes, { zoneId, contents: 'delete' }) + expect(plan.payload).toMatchObject({ mode: 'merge', mergedIntoZoneId: otherId, wallIds: [] }) + const after = apply(nodes, plan) + expect(zones(after).map((zone) => zone.id)).toEqual([otherId]) + expect(boundaryIds(after, 'separator')).toEqual([]) + expect(boundaryIds(after, 'wall')).toEqual(walls) + }) + + test('the middle of three merges into one neighbour; the other separator stays', () => { + const nodes: Record = fixture() + let i = 0 + const add = (node: WallNode | SeparatorNode) => { + nodes[node.id] = node + } + for (const x of [0, 2, 4]) { + add( + WallNode.parse({ + id: `wall_r${++i}`, + parentId: 'level_test', + start: [x, 0], + end: [x + 2, 0], + }), + ) + add( + WallNode.parse({ + id: `wall_r${++i}`, + parentId: 'level_test', + start: [x, 4], + end: [x + 2, 4], + }), + ) + } + add(WallNode.parse({ id: 'wall_rw', parentId: 'level_test', start: [0, 0], end: [0, 4] })) + add(WallNode.parse({ id: 'wall_re', parentId: 'level_test', start: [6, 0], end: [6, 4] })) + for (const x of [2, 4]) + add( + SeparatorNode.parse({ + id: `separator_r${x}`, + parentId: 'level_test', + start: [x, 0], + end: [x, 4], + }), + ) + const result = reconcileLevelStructure({ + levelId: 'level_test', + nodes, + mintId: (kind) => `${kind}_r${++i}`, + }) + const graph = applyToScratch(nodes, structureChangeBatch(result.patches)) + const [left, middle, right] = zones(graph).sort((a, b) => a.seed![0] - b.seed![0]) + const plan = deleteZone(graph, { zoneId: middle!.id, contents: 'delete' }) + expect(plan.payload.mode).toBe('merge') + expect(plan.payload.separatorIds).toHaveLength(1) + const merged = plan.payload.mergedIntoZoneId + expect([left!.id, right!.id]).toContain(merged!) + const after = apply(graph, plan) + expect(zones(after)).toHaveLength(2) + expect(boundaryIds(after, 'separator')).toHaveLength(1) + expect(boundaryIds(after, 'wall')).toEqual(boundaryIds(graph, 'wall')) + }) + + test('a room whose walls are all shared is refused with a structured conflict', () => { + const { nodes, zoneId } = enclosed() + const points: [number, number][] = [ + [-2, -2], + [10, -2], + [10, 6], + [-2, 6], + ] + const graph = apply(nodes, { + changes: points.map((start, i) => ({ + op: 'create' as const, + node: WallNode.parse({ + id: `wall_outer${i}`, + parentId: 'level_test', + start, + end: points[(i + 1) % 4], + }), + })), + }) + expect(zones(graph)).toHaveLength(2) + const plan = deleteZone(graph, { zoneId, contents: 'delete' }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts).toEqual([ + { + code: 'shared-walls', + nodeIds: [zoneId, ...plan.payload.keptSharedWallIds], + message: SHARED_WALLS_DELETE_MESSAGE, + }, + ]) + expect(plan.payload).toMatchObject({ mode: 'blocked', wallIds: [], itemIds: [] }) + expect(plan.payload.keptSharedWallIds).toHaveLength(4) + }) + + test('the room around an island is deleted with its own walls, not merged into the island', () => { + const { nodes, hostId } = island() + const plan = deleteZone(nodes, { zoneId: hostId, contents: 'delete' }) + expect(plan.payload.mode).toBe('delete') + expect(plan.payload.mergedIntoZoneId).toBeUndefined() + expect(plan.payload.wallIds).toHaveLength(4) + expect(plan.changes).toContainEqual({ op: 'delete', id: hostId }) + }) + + test('mixed boundaries: own walls plus an unshared separator follow the removal rules', () => { + const nodes: Record = fixture() + const corners: [number, number][] = [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ] + for (let i = 0; i < 3; i++) + nodes[`wall_m${i}`] = WallNode.parse({ + id: `wall_m${i}`, + parentId: 'level_test', + start: corners[i], + end: corners[i + 1], + }) + nodes.separator_m = SeparatorNode.parse({ + id: 'separator_m', + parentId: 'level_test', + start: [0, 4], + end: [0, 0], + }) + let n = 0 + const result = reconcileLevelStructure({ + levelId: 'level_test', + nodes, + mintId: (kind) => `${kind}_m${++n}`, + }) + const graph = applyToScratch(nodes, structureChangeBatch(result.patches)) + const [zone] = zones(graph) + const plan = deleteZone(graph, { zoneId: zone!.id, contents: 'delete' }) + expect(plan.payload).toMatchObject({ mode: 'delete', separatorIds: ['separator_m'] }) + expect(plan.payload.wallIds.sort()).toEqual(['wall_m0', 'wall_m1', 'wall_m2']) + }) +}) diff --git a/packages/core/src/commands/structure/delete-zone.ts b/packages/core/src/commands/structure/delete-zone.ts new file mode 100644 index 0000000000..dd75f21f81 --- /dev/null +++ b/packages/core/src/commands/structure/delete-zone.ts @@ -0,0 +1,425 @@ +import { area, containsPoint, intersection } from '../../lib/polygon-boolean' +import { type ExtractedRoom, extractRooms } from '../../lib/room-graph' +import type { AnyNode, ZoneNode } from '../../schema' +import { isDerivedNode } from '../../store/derived-node-guard' +import { getWallCurveFrameAt, getWallCurveLength } from '../../systems/wall/wall-curve' +import { + containedMezzanines, + electedIntentPlate, + isFloorPlacedIntent, + type PositionedIntent, +} from './mezzanine-content' +import { + applyToScratch, + boundaries, + diffStructure, + pointInRoom, + requireZone, + roomFace, + type StructureNodes, + type StructurePlan, + sharedSpan, + structureChangeBatch, +} from './shared' + +export type DeleteZonePayload = { + zoneId: string + name: string + contents: 'delete' | 'keep' + /** + * `delete`: the room goes with the walls, separators and openings only it + * uses. `merge`: an area Divide made (a separator on its outline) goes back + * into the room across those separators; walls and items stay. `blocked`: + * every boundary is a wall another room shares — nothing of its own to + * remove, so deleting one of those walls is the way (a conflict, no changes). + */ + mode: 'delete' | 'merge' | 'blocked' + /** `merge`: the room the area goes back into. */ + mergedIntoZoneId?: string + opensZoneIds: string[] + keptSharedSeparatorIds: string[] + wallIds: string[] + keptSharedWallIds: string[] + separatorIds: string[] + openingIds: string[] + itemIds: string[] +} + +function levelPose(nodes: StructureNodes, item: PositionedIntent, levelId: string) { + let position = [...item.position] as [number, number, number] + let yaw = Array.isArray(item.rotation) ? item.rotation[1] : item.rotation + let parent = item.parentId ? nodes[item.parentId] : undefined + const visited = new Set() + while (parent && parent.id !== levelId && !visited.has(parent.id)) { + visited.add(parent.id) + if (parent.type === 'wall') { + const frame = getWallCurveFrameAt(parent, position[0] / getWallCurveLength(parent)) + position = [ + frame.point.x + frame.normal.x * position[2], + position[1], + frame.point.y + frame.normal.y * position[2], + ] + yaw -= Math.atan2(parent.end[1] - parent.start[1], parent.end[0] - parent.start[0]) + } else if (parent.type === 'ceiling') position[1] += parent.height ?? 2.7 + else if ('position' in parent && Array.isArray(parent.position)) { + const rotation = + 'rotation' in parent && Array.isArray(parent.rotation) ? (parent.rotation[1] as number) : 0 + const c = Math.cos(rotation), + s = Math.sin(rotation) + position = [ + parent.position[0] + c * position[0] + s * position[2], + parent.position[1] + position[1], + parent.position[2] - s * position[0] + c * position[2], + ] + yaw += rotation + } + parent = parent.parentId ? nodes[parent.parentId] : undefined + } + return parent?.id === levelId + ? { + position, + rotation: Array.isArray(item.rotation) + ? ([item.rotation[0], yaw, item.rotation[2]] as [number, number, number]) + : yaw, + } + : null +} + +export const SHARED_WALLS_DELETE_MESSAGE = 'To remove this room, delete one of its walls.' + +type ZoneInput = { zoneId: string; contents: 'delete' | 'keep' } +type DeleteZonePlan = StructurePlan & { payload: DeleteZonePayload } + +/** + * Deletes a room the way its boundaries allow: + * - an area Divide made (a separator shared with a room on its outline) merges + * back into that room — the one sharing the most separator length — by + * removing those separators; its intent (name, finishes, regions) goes, its + * walls and items stay, and mezzanines it hosts move to the merged room; + * - a room whose every boundary is a wall shared with other rooms is refused + * (`shared-walls`): only deleting one of those walls can remove it; + * - otherwise the room goes with the walls, separators and openings only it + * uses, and its items per `contents`. + */ +export function deleteZone(sourceNodes: StructureNodes, input: ZoneInput): DeleteZonePlan { + const zone = requireZone(sourceNodes, input.zoneId) + const faces = extractRooms(boundaries(sourceNodes, zone.parentId!)) + const target = mergeTarget(sourceNodes, zone, faces) + if (target) return mergeBack(sourceNodes, zone, target, input.contents) + const plan = planZoneRemoval(sourceNodes, input) + const spans = roomFace(sourceNodes, zone, faces)?.spans ?? [] + if (!spans.length || !spans.every((span) => sharedSpan(sourceNodes, zone, span))) return plan + return { + changes: [], + conflicts: [ + { + code: 'shared-walls', + nodeIds: [zone.id, ...plan.payload.keptSharedWallIds], + message: SHARED_WALLS_DELETE_MESSAGE, + }, + ], + payload: { + ...plan.payload, + mode: 'blocked', + opensZoneIds: [], + wallIds: [], + separatorIds: [], + openingIds: [], + itemIds: [], + }, + } +} + +type MergeTarget = { zone: ZoneNode; separatorIds: string[] } + +/** + * The room an area Divide made goes back into: a room across a separator on + * the area's outline (never an island inside one of its holes), preferring the + * one sharing the most separator length, whose separators can go without + * changing any other room. + */ +function mergeTarget( + nodes: StructureNodes, + zone: ZoneNode, + faces: ExtractedRoom[], +): MergeTarget | null { + const face = roomFace(nodes, zone, faces) + const separatorSpans = face?.spans.filter((span) => span.kind === 'separator') ?? [] + if (!(face && separatorSpans.length)) return null + const insideHole = (point: [number, number]) => + face.holes.some((hole) => containsPoint([{ outer: hole, holes: [] }], point)) + const candidates = Object.values(nodes).flatMap((other) => { + if ( + other.type !== 'zone' || + other.id === zone.id || + other.parentId !== zone.parentId || + other.spaceRole !== 'room' || + other.floor?.support === 'open' || + (other.seed && insideHole(other.seed)) + ) + return [] + const otherSpans = roomFace(nodes, other, faces)?.spans ?? [] + let length = 0 + const separatorIds = new Set() + for (const span of separatorSpans) + for (const facing of otherSpans) { + if (facing.boundaryId !== span.boundaryId || facing.face === span.face) continue + const overlap = Math.min(facing.t1, span.t1) - Math.max(facing.t0, span.t0) + const boundary = nodes[span.boundaryId] + if (overlap <= 1e-6 || boundary?.type !== 'separator') continue + separatorIds.add(boundary.id) + length += + overlap * + Math.hypot(boundary.end[0] - boundary.start[0], boundary.end[1] - boundary.start[1]) + } + return separatorIds.size ? [{ zone: other, separatorIds: [...separatorIds], length }] : [] + }) + candidates.sort((a, b) => b.length - a.length || a.zone.id.localeCompare(b.zone.id)) + const before = boundaries(nodes, zone.parentId!) + for (const candidate of candidates) { + const removed = new Set(candidate.separatorIds) + const after = extractRooms(before.filter((node) => !removed.has(node.id))) + if (after.length === faces.length - 1) return candidate + } + return null +} + +function mergeBack( + nodes: StructureNodes, + zone: ZoneNode, + target: MergeTarget, + contents: 'delete' | 'keep', +): DeleteZonePlan { + const levelId = zone.parentId! + const ceilings = new Set( + Object.values(nodes) + .filter((n) => n.type === 'ceiling' && n.zoneId === zone.id) + .map((n) => n.id), + ) + const items = Object.values(nodes).flatMap((n) => { + if (n.type !== 'item' && !isFloorPlacedIntent(n)) return [] + const pose = levelPose(nodes, n, levelId) + return pose && pointInRoom(zone, [pose.position[0], pose.position[2]]) + ? [{ node: n, pose }] + : [] + }) + const scratch: Record = { ...nodes } + delete scratch[zone.id] + for (const id of target.separatorIds) delete scratch[id] + for (const { node, pose } of items) { + const support = node.supportSlabId ? nodes[node.supportSlabId] : undefined + // Its own floor goes with the area; the merged room's floor carries it. + const ownFloor = support?.type === 'slab' && !!support.zoneIds?.includes(zone.id) + // Its ceiling goes too; what hangs from it stays where it is, on the level. + const hung = !!node.parentId && ceilings.has(node.parentId) + if (hung) + scratch[node.id] = { + ...node, + ...pose, + parentId: levelId, + wallId: undefined, + wallT: undefined, + supportSlabId: undefined, + } as AnyNode + else if (ownFloor) scratch[node.id] = { ...node, supportSlabId: undefined } as AnyNode + } + for (const node of Object.values(scratch)) { + if (node.type === 'zone' && node.hostZoneId === zone.id) + scratch[node.id] = { ...node, hostZoneId: target.zone.id } + if (node.type === 'floor-opening' && node.hostZoneId === zone.id) + scratch[node.id] = { ...node, hostZoneId: target.zone.id } + if (node.type === 'unit' && node.members.includes(zone.id)) + scratch[node.id] = { ...node, members: node.members.filter((id) => id !== zone.id) } + } + return { + changes: diffStructure(nodes, pruneDeleted(nodes, scratch)), + payload: { + zoneId: zone.id, + name: zone.name, + contents, + mode: 'merge', + mergedIntoZoneId: target.zone.id, + opensZoneIds: [], + keptSharedSeparatorIds: [], + wallIds: [], + keptSharedWallIds: [], + separatorIds: target.separatorIds, + openingIds: [], + itemIds: items.map(({ node }) => node.id), + }, + } +} + +/** Removes what hangs from deleted nodes and drops deleted ids from `children`. */ +function pruneDeleted(nodes: StructureNodes, scratch: Record) { + const deleted = new Set(Object.keys(nodes).filter((id) => !scratch[id])) + let changed = true + while (changed) { + changed = false + for (const node of Object.values(scratch)) + if (node.parentId && deleted.has(node.parentId)) { + delete scratch[node.id] + deleted.add(node.id) + changed = true + } + } + for (const node of Object.values(scratch)) + if ( + !isDerivedNode(node) && + 'children' in node && + Array.isArray(node.children) && + node.children.some((id) => deleted.has(id)) + ) + scratch[node.id] = { + ...node, + children: node.children.filter((id) => !deleted.has(id)), + } as AnyNode + return scratch +} + +/** + * The room removed with the walls, separators and openings only it uses (and + * its items per `contents`), whatever its neighbours. Wall deletion uses this + * directly for the rooms it takes down. + */ +export function planZoneRemoval(sourceNodes: StructureNodes, input: ZoneInput): DeleteZonePlan { + const zone = requireZone(sourceNodes, input.zoneId) + let nodes = sourceNodes + const stackedItems: string[] = [] + for (const stacked of containedMezzanines(sourceNodes, zone)) { + const plan = planZoneRemoval(nodes, { zoneId: stacked.id, contents: input.contents }) + nodes = applyToScratch(nodes, structureChangeBatch(plan.changes)) + stackedItems.push(...plan.payload.itemIds) + } + const spans = roomFace(nodes, zone)?.spans ?? [] + const wallIds = [...new Set(spans.filter((s) => s.kind === 'wall').map((s) => s.boundaryId))] + const shared = spans.filter((span) => sharedSpan(nodes, zone, span)) + const keptSharedWallIds = [ + ...new Set(shared.filter((s) => s.kind === 'wall').map((s) => s.boundaryId)), + ] + const keptSharedSeparatorIds = [ + ...new Set(shared.filter((s) => s.kind === 'separator').map((s) => s.boundaryId)), + ] + const removedWalls = wallIds.filter((id) => !keptSharedWallIds.includes(id)) + const separatorIds = [ + ...new Set( + spans + .filter((s) => s.kind === 'separator' && !keptSharedSeparatorIds.includes(s.boundaryId)) + .map((s) => s.boundaryId), + ), + ] + const openingIds = Object.values(nodes) + .filter( + (n) => + (n.type === 'door' || n.type === 'window') && + (removedWalls.includes(n.parentId ?? '') || + ('wallId' in n && removedWalls.includes(n.wallId as string))), + ) + .map((n) => n.id) + const floorOpeningIds = Object.values(nodes) + .filter( + (node) => + node.type === 'floor-opening' && + (node.hostZoneId === zone.id || + (!node.hostZoneId && + node.parentId === zone.parentId && + node.polygon.every((point) => pointInRoom(zone, point)))), + ) + .map((node) => node.id) + const items = Object.values(nodes).flatMap((n) => { + if (n.type !== 'item' && !isFloorPlacedIntent(n)) return [] + const pose = levelPose(nodes, n, zone.parentId!) + if (zone.floor?.support === 'open') { + const parent = n.parentId ? nodes[n.parentId] : undefined + const host = + parent?.type === 'level' && isFloorPlacedIntent(n) + ? electedIntentPlate(nodes, n) + : undefined + if ( + !(parent?.type === 'ceiling' && parent.zoneId === zone.id) && + !(host?.type === 'slab' && host.zoneIds?.includes(zone.id)) + ) + return [] + return pose ? [{ node: n, pose }] : [] + } + return pose && + (pointInRoom(zone, [pose.position[0], pose.position[2]]) || + removedWalls.includes(n.parentId ?? '')) + ? [{ node: n, pose }] + : [] + }) + const payload: DeleteZonePayload = { + zoneId: zone.id, + mode: 'delete', + opensZoneIds: [], + keptSharedSeparatorIds, + name: zone.name, + contents: input.contents, + wallIds: removedWalls, + keptSharedWallIds, + separatorIds, + openingIds: [...openingIds, ...floorOpeningIds], + itemIds: [...new Set([...stackedItems, ...items.map(({ node }) => node.id)])], + } + const scratch: Record = { ...nodes } + for (const id of [ + zone.id, + ...removedWalls, + ...separatorIds, + ...openingIds, + ...floorOpeningIds, + ...(input.contents === 'delete' ? payload.itemIds : []), + ]) + delete scratch[id] + const removedHosts = new Set([ + ...removedWalls, + ...Object.values(nodes) + .filter((n) => n.type === 'ceiling' && n.zoneId === zone.id) + .map((n) => n.id), + ]) + if (input.contents === 'keep') + for (const { node, pose } of items) { + if ( + zone.floor?.support === 'open' && + node.supportSlabId && + nodes[node.supportSlabId]?.type === 'slab' && + (nodes[node.supportSlabId] as import('../../schema').SlabNode).zoneIds?.includes(zone.id) + ) + scratch[node.id] = { ...node, supportSlabId: undefined } as AnyNode + if (!node.parentId || !removedHosts.has(node.parentId)) continue + scratch[node.id] = { + ...node, + ...pose, + parentId: zone.parentId, + wallId: undefined, + wallT: undefined, + supportSlabId: undefined, + } as AnyNode + } + for (const node of Object.values(scratch)) + if (node.type === 'unit' && node.members.includes(zone.id)) + scratch[node.id] = { ...node, members: node.members.filter((id) => id !== zone.id) } + pruneDeleted(nodes, scratch) + const beforeFaces = extractRooms(boundaries(nodes, zone.parentId!)) + const afterFaces = extractRooms(boundaries(scratch, zone.parentId!)) + payload.opensZoneIds = Object.values(nodes).flatMap((other) => { + if ( + other.type !== 'zone' || + other.spaceRole !== 'room' || + other.id === zone.id || + other.parentId !== zone.parentId + ) + return [] + const before = roomFace(nodes, other, beforeFaces) + if (!before) return [] + const footprint = { outer: before.referencePolygon, holes: before.holes } + const size = area([footprint]) + const preserved = afterFaces.some((face) => { + const candidate = { outer: face.referencePolygon, holes: face.holes } + const overlap = area(intersection(footprint, candidate)) + return overlap / Math.max(size + area([candidate]) - overlap, 1e-9) > 0.99999 + }) + return preserved ? [] : [other.id] + }) + return { changes: diffStructure(sourceNodes, scratch), payload } +} diff --git a/packages/core/src/commands/structure/divide-zone-path.test.ts b/packages/core/src/commands/structure/divide-zone-path.test.ts new file mode 100644 index 0000000000..467a858222 --- /dev/null +++ b/packages/core/src/commands/structure/divide-zone-path.test.ts @@ -0,0 +1,434 @@ +import { expect, test } from 'bun:test' +import { containsPoint } from '../../lib/polygon-boolean' +import { extractRooms } from '../../lib/room-graph' +import { initSpaceDetectionSync } from '../../lib/space-detection' +import { reconcileSceneStructure } from '../../lib/structure-reconcile' +import { LevelNode, type SeparatorNode, WallNode, type ZoneNode } from '../../schema' +import { subscribeSceneCommits } from '../../store/history-control' +import useScene, { clearSceneHistory } from '../../store/use-scene' +import { getWallCurveFrameAt } from '../../systems/wall/wall-curve' +import { createZone } from './create-zone' +import { divideZone } from './divide-zone' +import { applyToScratch, boundaries, type Point, structureChangeBatch } from './shared' + +const levelId = 'level_path' +const rectangle: Point[] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +const island: Point[] = [ + [3, 1], + [5, 1], + [5, 3], + [3, 3], +] +const elbow: Point[] = [ + [2, 0], + [2, 2], + [8, 2], +] +function setup(thickness = 0.2) { + let i = 0 + const mintId = (kind: string) => `${kind}_path_${++i}` + const level = LevelNode.parse({ id: levelId }) + const source = { [level.id]: level } + const plan = createZone(source, { + levelId, + polygon: rectangle, + enclose: true, + wall: { thickness }, + mintId, + intent: { floor: { finish: 'oak', elevation: 0.2 }, wallMaterial: 'paint' }, + }) + const nodes = reconcileSceneStructure({ + nodes: applyToScratch(source, structureChangeBatch(plan.changes)), + mintId, + }).nodes + return { nodes, zoneId: plan.zoneId, mintId } +} +function run(path: Point[], closed = false, thickness = 0.2) { + const fixture = setup(thickness) + const plan = divideZone(fixture.nodes, { ...fixture, path, closed }) + expect(plan.conflicts).toBeUndefined() + const draft = applyToScratch(fixture.nodes, structureChangeBatch(plan.changes)) + const faces = extractRooms(boundaries(draft, levelId)) + const result = reconcileSceneStructure({ + nodes: draft, + previousNodes: fixture.nodes, + mintId: fixture.mintId, + }) + return { + ...fixture, + plan, + faces, + result, + separators: plan.changes.flatMap((p) => (p.op === 'create' ? [p.node as SeparatorNode] : [])), + } +} + +test('L-shaped open path shares exact endpoints and splits wall T-vertices into two zones', () => { + const { plan, separators, faces, result } = run(elbow) + expect(plan.separatorIds).toHaveLength(2) + expect(separators[0]!.end).toEqual(separators[1]!.start) + expect(separators.map((s) => [s.start, s.end])).toEqual([ + [elbow[0]!, elbow[1]!], + [elbow[1]!, elbow[2]!], + ]) + expect(faces).toHaveLength(2) + expect(Object.values(result.nodes).filter((n) => n.type === 'zone')).toHaveLength(2) + for (const face of faces) expect(face.spans.filter((s) => s.kind === 'separator')).toHaveLength(2) +}) + +test.each([ + false, + true, +])('four-point island preserves outer identity, inherits finishes and keeps one unholed base and two platforms (reverse=%s)', (reverse) => { + const { zoneId, plan, separators, faces, result, mintId } = run( + reverse ? [...island].reverse() : island, + true, + ) + expect(plan.separatorIds).toHaveLength(4) + expect(separators.at(-1)!.end).toEqual(separators[0]!.start) + expect(faces).toHaveLength(2) + const outer = result.nodes[zoneId] as ZoneNode + const zones = Object.values(result.nodes).filter((n) => n.type === 'zone') + expect(zones).toHaveLength(2) + expect(outer.holes).toHaveLength(1) + expect(containsPoint([{ outer: outer.polygon, holes: outer.holes }], outer.seed!)).toBe(true) + for (const zone of zones) + expect(zone).toMatchObject({ floor: { finish: 'oak', elevation: 0.2 }, wallMaterial: 'paint' }) + const inner = zones.find((n) => n.id !== zoneId)! + expect(inner.holes).toEqual([]) + expect(inner.boundaryWallIds).toEqual([]) + expect(inner.boundarySeparatorIds.sort()).toEqual([...plan.separatorIds].sort()) + const plates = Object.values(result.nodes).filter((n) => n.type === 'slab') + expect(plates).toHaveLength(3) + const base = plates.find((plate) => plate.plateRole === 'base')! + expect(base.holes).toEqual([]) + expect(base.zoneIds?.sort()).toEqual(zones.map((z) => z.id).sort()) + const ceilings = Object.values(result.nodes).filter((n) => n.type === 'ceiling') + expect(ceilings).toHaveLength(2) + expect(ceilings.find((c) => c.zoneId === zoneId)!.holes).toHaveLength(1) + expect(reconcileSceneStructure({ nodes: result.nodes, mintId }).patches).toEqual([]) +}) + +test('minimum 0.25 m² island is a graph face', () => { + expect( + run( + [ + [3, 1], + [3.5, 1], + [3.5, 1.5], + [3, 1.5], + ], + true, + ).faces, + ).toHaveLength(2) +}) + +test('5 cm island clearance is measured from thin wall faces, without graph snapping', () => { + const { result, zoneId } = run( + [ + [0.06, 1], + [1.06, 1], + [1.06, 2], + [0.06, 2], + ], + true, + 0.02, + ) + expect((result.nodes[zoneId] as ZoneNode).holes).toHaveLength(1) +}) + +test('open path keeps its snapped curved-wall endpoint connected', () => { + const fixture = setup() + const bottom = Object.values(fixture.nodes).find( + (n) => n.type === 'wall' && n.start[1] === 0 && n.end[1] === 0, + ) as WallNode + const curved = { ...bottom, curveOffset: 1 } + const nodes = reconcileSceneStructure({ + nodes: { ...fixture.nodes, [curved.id]: curved }, + mintId: fixture.mintId, + }).nodes + const { point } = getWallCurveFrameAt(curved, 0.37) + const plan = divideZone(nodes, { + zoneId: fixture.zoneId, + path: [ + [point.x, point.y], + [point.x, 2], + [8, 2], + ], + startBoundaryId: curved.id, + mintId: fixture.mintId, + }) + expect(plan.conflicts).toBeUndefined() + const draft = applyToScratch(nodes, structureChangeBatch(plan.changes)) + expect(extractRooms(boundaries(draft, levelId))).toHaveLength(2) +}) + +test('open paths preserve free intermediate points, legacy cut and boundary hints', () => { + const fixture = setup() + const input = { zoneId: fixture.zoneId, mintId: fixture.mintId } + const path: Point[] = [ + [2.1, 0.1], + [2.123, 2.456], + [7.9, 2.1], + ] + const plan = divideZone(fixture.nodes, { ...input, path }) + expect(plan.conflicts).toBeUndefined() + const nodes = plan.changes.flatMap((p) => (p.op === 'create' ? [p.node as SeparatorNode] : [])) + expect(nodes[0]!.start).toEqual([2.1, 0]) + expect(nodes[0]!.end).toEqual(path[1]!) + expect(nodes[1]!.end).toEqual([8, 2.1]) + expect(path[0]).toEqual([2.1, 0.1]) + const cut = divideZone(fixture.nodes, { + ...input, + cut: [ + [2, 0], + [2, 4], + ], + }) + expect(cut.separatorIds).toEqual([cut.separatorId!]) + expect( + divideZone(fixture.nodes, { + ...input, + path: [ + [4, 2], + [4, 4], + ], + }).conflicts?.[0]?.code, + ).toBe('snap-distance') + const walls = Object.values(fixture.nodes).filter((n) => n.type === 'wall') + const bottom = walls.find((w) => w.start[1] === 0 && w.end[1] === 0)! + const top = walls.find((w) => w.start[1] === 4 && w.end[1] === 4)! + const hinted = divideZone(fixture.nodes, { + ...input, + path: [ + [4, 2], + [4, 2], + ], + startBoundaryId: bottom.id, + endBoundaryId: top.id, + }) + expect(hinted.conflicts).toBeUndefined() +}) + +for (const [label, path, closed, code] of [ + [ + 'open self-intersection', + [ + [1, 0], + [6, 3], + [1, 3], + [6, 0], + ], + false, + 'self-intersection', + ], + [ + 'closed self-intersection', + [ + [1, 1], + [6, 3], + [1, 3], + [6, 1], + ], + true, + 'self-intersection', + ], + [ + 'retraced segment', + [ + [2, 0], + [2, 2], + [2, 1], + [8, 1], + ], + false, + 'self-intersection', + ], + [ + 'outside intermediate point', + [ + [2, 0], + [-1, 2], + [2, 4], + ], + false, + 'outside-room', + ], + [ + 'outside island', + [ + [7, 1], + [9, 1], + [9, 3], + [7, 3], + ], + true, + 'outside-room', + ], + [ + 'boundary overlap', + [ + [0, 1], + [0, 2], + [8, 2], + ], + false, + 'boundary-overlap', + ], + [ + 'short segment', + [ + [2, 0], + [2, 0.04], + [8, 2], + ], + false, + 'short-cut', + ], + [ + 'small island', + [ + [3, 1], + [3.4, 1], + [3.4, 1.4], + [3, 1.4], + ], + true, + 'small-island', + ], + [ + 'wall clearance', + [ + [0.14, 1], + [1.14, 1], + [1.14, 2], + [0.14, 2], + ], + true, + 'wall-clearance', + ], + [ + 'touching island', + [ + [0, 1], + [1, 1], + [1, 2], + [0, 2], + ], + true, + 'outside-room', + ], +] as [string, Point[], boolean, string][]) { + test(`rejects ${label} without changes`, () => { + const fixture = setup() + const plan = divideZone(fixture.nodes, { ...fixture, path, closed }) + expect(plan.changes).toEqual([]) + expect(plan.separatorIds).toEqual([]) + expect(plan.conflicts?.[0]?.code).toBe(code) + }) +} + +test('open and closed paths cannot cross or enclose an existing hole', () => { + const fixture = setup() + const inner: Point[] = [ + [3, 1], + [5, 1], + [5, 3], + [3, 3], + ] + const walls = inner.map((start, i) => + WallNode.parse({ + id: fixture.mintId('wall'), + parentId: levelId, + start, + end: inner[(i + 1) % 4], + }), + ) + const nodes = reconcileSceneStructure({ + nodes: { ...fixture.nodes, ...Object.fromEntries(walls.map((w) => [w.id, w])) }, + mintId: fixture.mintId, + }).nodes + const outer = Object.values(nodes).find((n) => n.type === 'zone' && n.holes.length)! + for (const [path, closed] of [ + [ + [ + [0, 2], + [2, 2], + [8, 2], + ], + false, + ], + [ + [ + [2, 2], + [4, 2], + [4, 3.5], + [2, 3.5], + ], + true, + ], + [ + [ + [2, 0.5], + [6, 0.5], + [6, 3.5], + [2, 3.5], + ], + true, + ], + ] as [Point[], boolean][]) { + const plan = divideZone(nodes, { zoneId: outer.id, path, closed, mintId: fixture.mintId }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]?.code).toBe('outside-room') + } +}) + +test.each([ + false, + true, +])('multi-separator Divide is one commit and one undo step (closed=%s)', (closed) => { + globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame ??= () => {} + const previous = useScene.getState() + const fixture = setup() + useScene.setState({ + nodes: fixture.nodes, + rootNodeIds: [levelId], + readOnly: false, + materials: {}, + collections: {}, + }) + clearSceneHistory() + const stop = initSpaceDetectionSync(useScene, { + getState: () => ({ spaces: {}, setSpaces: () => {} }), + }) + const origins: string[] = [] + const unsubscribe = subscribeSceneCommits((commit) => origins.push(commit.origin)) + try { + const plan = divideZone(fixture.nodes, { ...fixture, path: closed ? island : elbow, closed }) + expect(plan.conflicts).toBeUndefined() + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const after = useScene.getState().nodes + expect(Object.values(after).filter((n) => n.type === 'separator')).toHaveLength(closed ? 4 : 2) + expect(Object.values(after).filter((n) => n.type === 'zone')).toHaveLength(2) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + expect(origins).toEqual(['local']) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(fixture.nodes) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + } finally { + unsubscribe() + stop() + useScene.setState(previous) + clearSceneHistory() + } +}) diff --git a/packages/core/src/commands/structure/divide-zone.ts b/packages/core/src/commands/structure/divide-zone.ts new file mode 100644 index 0000000000..49cfa2830c --- /dev/null +++ b/packages/core/src/commands/structure/divide-zone.ts @@ -0,0 +1,241 @@ +import { area, containsPoint, difference, union } from '../../lib/polygon-boolean' +import { segmentsIntersect } from '../../lib/polygon-relations' +import { extractRooms } from '../../lib/room-graph' +import { SeparatorNode, type WallNode } from '../../schema' +import { getWallCurveFrameAt } from '../../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../../systems/wall/wall-footprint' +import { + at, + boundaries, + type Point, + project, + requireZone, + roomFace, + type StructureMintId, + type StructureNodes, + type StructurePlan, +} from './shared' + +export function createZoneDivisionContext(nodes: StructureNodes, zoneId: string) { + const zone = requireZone(nodes, zoneId) + const boundaryNodes = boundaries(nodes, zone.parentId!) + const faces = extractRooms(boundaryNodes) + return { zoneId, boundaryNodes, face: roomFace(nodes, zone, faces), roomCount: faces.length } +} +export type ZoneDivisionContext = ReturnType + +export function snapZoneBoundary( + nodes: StructureNodes, + zoneId: string, + point: Point, + gridStep = 0, + context = createZoneDivisionContext(nodes, zoneId), + // Set when the pointer landed on a boundary's own surface. The cut belongs on + // that boundary however thick it is, so the proximity cap — which only exists + // to reject pointers floating in the middle of the room — does not apply. + boundaryId?: string, +) { + const face = context.face + if (!point.every(Number.isFinite)) throw Error('Invalid cut coordinates.') + if (!face) throw Error('The room must be enclosed.') + const named = boundaryId ? face.spans.filter((span) => span.boundaryId === boundaryId) : [] + const candidates = (named.length ? named : face.spans).flatMap((span) => { + const node = nodes[span.boundaryId] + if (node?.type !== 'wall' && node?.type !== 'separator') return [] + const pointAt = (t: number): Point => { + if (node.type === 'separator') return at(node.start, node.end, t) + const { point: p } = getWallCurveFrameAt(node, t) + return [p.x, p.y] + } + const samples = node.type === 'wall' && node.curveOffset ? 64 : 1 + return Array.from({ length: samples }, (_, i) => { + const a = pointAt(span.t0 + ((span.t1 - span.t0) * i) / samples) + const b = pointAt(span.t0 + ((span.t1 - span.t0) * (i + 1)) / samples) + const projected = project(point, a, b) + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + const t = + gridStep > 0 && samples === 1 + ? Math.max( + 0, + Math.min(1, (Math.round((projected.t * length) / gridStep) * gridStep) / length), + ) + : projected.t + return { + ...projected, + point: at(a, b, t), + boundaryId: node.id, + direction: [(b[0] - a[0]) / length, (b[1] - a[1]) / length] as Point, + } + }) + }) + const nearest = candidates.sort( + (a, b) => a.distance - b.distance || a.boundaryId.localeCompare(b.boundaryId), + )[0] + if (!nearest || !Number.isFinite(nearest.distance)) return null + if (!named.length && nearest.distance > 1) return null + const distance = Math.hypot(nearest.point[0] - point[0], nearest.point[1] - point[1]) + return named.length || distance <= 1 ? { ...nearest, distance } : null +} + +function overlapsSegment(a: Point, b: Point, c: Point, d: Point) { + const dx = b[0] - a[0], + dz = b[1] - a[1] + const length = Math.hypot(dx, dz) + if ([c, d].some((p) => Math.abs((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) > 1e-8 * length)) + return false + const station = (p: Point) => ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length + const t0 = station(c), + t1 = station(d) + return Math.min(length, Math.max(t0, t1)) - Math.max(0, Math.min(t0, t1)) > 1e-8 +} + +function segmentDistance(a: Point, b: Point, c: Point, d: Point) { + if (segmentsIntersect(a, b, c, d)) return 0 + return Math.min( + project(a, c, d).distance, + project(b, c, d).distance, + project(c, a, b).distance, + project(d, a, b).distance, + ) +} + +export function divideZone( + nodes: StructureNodes, + input: { + zoneId: string + path?: Point[] + cut?: [Point, Point] + closed?: boolean + startBoundaryId?: string + endBoundaryId?: string + mintId: StructureMintId + }, + context = createZoneDivisionContext(nodes, input.zoneId), +): StructurePlan & { separatorIds: string[]; separatorId?: string } { + const zone = requireZone(nodes, input.zoneId) + const reject = (code: string, message: string) => ({ + changes: [], + separatorIds: [], + conflicts: [{ code, nodeIds: [zone.id], message }], + }) + const source = input.path ?? input.cut + const closed = input.closed ?? false + if ((input.path && input.cut) || !source || source.length < (closed ? 3 : 2)) + return reject( + 'invalid-path', + 'Supply one path with at least two points, or three for an island.', + ) + if (source.some((p) => p.length !== 2 || !p.every(Number.isFinite))) + throw Error('Invalid cut coordinates.') + const face = context.face + if (!face) return reject('open-room', 'The room must be enclosed.') + const rings = [face.referencePolygon, ...face.holes].map((ring) => [...ring]) + const points: Point[] = source.map(([x, z]) => [x, z]) + if (!closed) { + const first = snapZoneBoundary(nodes, zone.id, points[0]!, 0, context, input.startBoundaryId) + const last = snapZoneBoundary(nodes, zone.id, points.at(-1)!, 0, context, input.endBoundaryId) + if (!first || !last) return reject('snap-distance', 'Move within 1 m of a room boundary.') + points[0] = first.point + points[points.length - 1] = last.point + // The graph's adaptive curve samples are coarser than endpoint snapping. + // Include the snapped station so its tiny chord deviation is not an exit. + for (const snapped of [first, last]) { + const boundary = nodes[snapped.boundaryId] + if (boundary?.type !== 'wall' || !boundary.curveOffset) continue + const closest = rings + .flatMap((ring) => + ring.map((a, i) => ({ + ring, + i, + ...project(snapped.point, a, ring[(i + 1) % ring.length]!), + })), + ) + .sort((a, b) => a.distance - b.distance)[0] + if (closest && closest.t > 1e-8 && closest.t < 1 - 1e-8) + closest.ring.splice(closest.i + 1, 0, snapped.point) + } + } + const segments: [Point, Point][] = points + .slice(0, closed ? points.length : -1) + .map((start, i) => [start, points[(i + 1) % points.length]!]) + if (segments.some(([a, b]) => Math.hypot(b[0] - a[0], b[1] - a[1]) < 0.05 - 1e-9)) + return reject('short-cut', 'Each segment must be at least 5 cm long.') + for (let i = 0; i < segments.length; i++) { + const [a, b] = segments[i]! + for (let j = i + 1; j < segments.length; j++) { + const [c, d] = segments[j]! + const adjacent = j === i + 1 || (closed && i === 0 && j === segments.length - 1) + if (overlapsSegment(a, b, c, d) || (!adjacent && segmentsIntersect(a, b, c, d))) + return reject('self-intersection', 'The path must not cross or retrace itself.') + } + } + if (closed && area([{ outer: points, holes: [] }]) < 0.25 - 1e-9) + return reject('small-island', 'An island must cover at least 0.25 m².') + const footprint = { outer: rings[0]!, holes: rings.slice(1) } + const boundarySegments: [Point, Point][] = [footprint.outer, ...footprint.holes].flatMap((ring) => + ring.map((a, i): [Point, Point] => [a, ring[(i + 1) % ring.length]!]), + ) + for (const [index, [start, end]] of segments.entries()) { + if (boundarySegments.some(([a, b]) => overlapsSegment(start, end, a, b))) + return reject('boundary-overlap', 'The path must not run along an existing boundary.') + for (const [a, b] of boundarySegments) { + if (!segmentsIntersect(start, end, a, b)) continue + const dx = end[0] - start[0], + dz = end[1] - start[1] + const sx = b[0] - a[0], + sz = b[1] - a[1] + const denominator = dx * sz - dz * sx + const t = + Math.abs(denominator) > 1e-9 + ? ((a[0] - start[0]) * sz - (a[1] - start[1]) * sx) / denominator + : project(a, start, end).t + const endpoint = + !closed && + ((index === 0 && Math.abs(t) < 1e-6) || + (index === segments.length - 1 && Math.abs(t - 1) < 1e-6)) + if (!endpoint) + return reject('outside-room', 'Only the ends of an open path may touch the room boundary.') + } + if (!containsPoint([footprint], at(start, end, 0.5))) + return reject('outside-room', 'The entire path must stay inside the room, outside its holes.') + } + if (closed) { + const walls = context.boundaryNodes.filter((node): node is WallNode => node.type === 'wall') + const miters = calculateLevelMiters(walls) + const wallPolygons = walls.map((wall) => + getWallPlanFootprint(wall, miters).map(({ x, y }): Point => [x, y]), + ) + const clear = difference(footprint, union(wallPolygons)) + if (area(difference(points, clear)) > 1e-8) + return reject('outside-room', 'The island must fit entirely inside the clear room polygon.') + const wallSegments = wallPolygons.flatMap((ring) => + ring.map((a, i): [Point, Point] => [a, ring[(i + 1) % ring.length]!]), + ) + if ( + segments.some(([a, b]) => + wallSegments.some(([c, d]) => segmentDistance(a, b, c, d) < 0.05 - 1e-8), + ) + ) + return reject('wall-clearance', 'Keep the island at least 5 cm from wall faces.') + } + const ids = new Set() + const separators = segments.map(([start, end]) => { + const separator = SeparatorNode.parse({ + id: input.mintId('separator'), + parentId: zone.parentId, + start, + end, + }) + if (nodes[separator.id] || ids.has(separator.id)) + throw Error(`Duplicate separator id: ${separator.id}`) + ids.add(separator.id) + return separator + }) + if (extractRooms([...context.boundaryNodes, ...separators]).length !== context.roomCount + 1) + return reject('invalid-cut', 'The path must divide this room into exactly two rooms.') + return { + changes: separators.map((node) => ({ op: 'create', node })), + separatorIds: separators.map((node) => node.id), + separatorId: separators[0]!.id, + } +} diff --git a/packages/core/src/commands/structure/duplicate-zone.ts b/packages/core/src/commands/structure/duplicate-zone.ts new file mode 100644 index 0000000000..bc5b0bdb8f --- /dev/null +++ b/packages/core/src/commands/structure/duplicate-zone.ts @@ -0,0 +1,24 @@ +import { type Point, requireZone, type StructureNodes } from './shared' +import { planZoneTransform, type TransformZoneInput } from './transform-zone' + +export type DuplicateZoneInput = Omit & { translate: Point } + +export function duplicateZone(nodes: StructureNodes, input: DuplicateZoneInput) { + const zone = requireZone(nodes, input.zoneId) + const first = planZoneTransform(nodes, input, true) + if (zone.floor?.support !== 'open' || !first.conflicts?.length) return first + const xs = zone.polygon.map(([x]) => x), + zs = zone.polygon.map(([, z]) => z) + const width = Math.max(...xs) - Math.min(...xs), + depth = Math.max(...zs) - Math.min(...zs) + for (const translate of [ + [width, 0], + [0, depth], + [-width, 0], + [0, -depth], + ] as Point[]) { + const plan = planZoneTransform(nodes, { ...input, translate }, true) + if (!plan.conflicts?.length) return plan + } + return first +} diff --git a/packages/core/src/commands/structure/floor-foundation-lift.test.ts b/packages/core/src/commands/structure/floor-foundation-lift.test.ts new file mode 100644 index 0000000000..7af011ac7f --- /dev/null +++ b/packages/core/src/commands/structure/floor-foundation-lift.test.ts @@ -0,0 +1,518 @@ +import { afterEach, expect, test } from 'bun:test' +import { GROUND_SUPPORT_ID } from '../../hooks/spatial-grid/support-host-id' +import { floorConstructionLift, liftedManualSlab } from '../../lib/floor-construction-lift' +import { automaticFloorHeight } from '../../lib/floor-foundation-datum' +import { expandFloorIntentChanges, floorIntentConflicts } from '../../lib/floor-intent-changes' +import { wallSupportForNodes } from '../../lib/opening-floor-datum' +import { + type AnyNode, + BuildingNode, + CeilingNode, + ColumnNode, + FenceNode, + LevelNode, + RoofNode, + RoofSegmentNode, + SlabNode, + WallNode, + ZoneNode, +} from '../../schema' +import { resolveCeilingHeight } from '../../services/level-height' +import { getLevelElevations, getWallPlaneTop } from '../../services/storey' +import useScene from '../../store/use-scene' +import { resolveRoofElevation } from '../../systems/roof/roof-elevation' +import { reconcileStructureOnLoad } from '../../utils/reconcile-structure-on-load' +import { createZone, outdoorRoomConflicts } from './create-zone' +import { setFloorFoundation } from './set-floor-foundation' +import { type StructurePlan, structureChangeBatch } from './shared' + +const rect = (x: number, width = 4): [number, number][] => [ + [x, 0], + [x + width, 0], + [x + width, 4], + [x, 4], +] + +function scene(shared = false) { + const building = BuildingNode.parse({ id: 'building_lift' }) + const levels = [0, 1, 2].map((level) => + LevelNode.parse({ id: `level_lift${level}`, parentId: building.id, level, height: 3 }), + ) + building.children = levels.map((level) => level.id) + const nodes: Record = Object.fromEntries( + [building, ...levels].map((node) => [node.id, node]), + ) + for (const [i, x] of [0, 10].entries()) { + const polygon = rect(x) + const zone = ZoneNode.parse({ + id: `zone_lift${i}`, + parentId: levels[0]!.id, + name: i ? 'Shed floor' : 'Shared floor', + spaceRole: 'room', + polygon, + }) + nodes[zone.id] = zone + polygon.forEach((start, at) => { + const wall = WallNode.parse({ + id: `wall_lift${i}_${at}`, + parentId: levels[0]!.id, + start, + end: polygon[(at + 1) % 4], + }) + nodes[wall.id] = wall + }) + const ceiling = CeilingNode.parse({ + id: `ceiling_lift${i}`, + parentId: levels[0]!.id, + polygon, + boundary: 'auto', + autoFromWalls: true, + zoneId: zone.id, + }) + nodes[ceiling.id] = ceiling + } + for (const level of levels.slice(1)) { + const slab = SlabNode.parse({ + id: `slab_${level.level}`, + parentId: level.id, + polygon: rect(0, shared ? 14 : 4), + }) + nodes[slab.id] = slab + } + const roof = RoofNode.parse({ + id: 'roof_lift', + parentId: levels[0]!.id, + support: { kind: 'walls' }, + position: [2, 0, 2], + children: ['rseg_lift'], + }) + const segment = RoofSegmentNode.parse({ id: 'rseg_lift', parentId: roof.id, width: 4, depth: 4 }) + nodes[roof.id] = roof + nodes[segment.id] = segment + nodes.roof_custom = RoofNode.parse({ + id: 'roof_custom', + parentId: levels[0]!.id, + position: [2, 3, 2], + }) + for (const level of levels) + level.children = Object.values(nodes) + .filter((node) => node.parentId === level.id) + .map((node) => node.id) as LevelNode['children'] + return reconcileStructureOnLoad(nodes).nodes +} + +function base(nodes: Record, zone = 'zone_lift0') { + return Object.values(nodes).find( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && !!node.zoneIds?.includes(zone), + )! +} +function apply(nodes: Record, plan: StructurePlan) { + expect(plan.conflicts).toEqual([]) + const next = { ...nodes } + for (const change of plan.changes) + if (change.op === 'update') next[change.id] = { ...next[change.id], ...change.data } as AnyNode + return reconcileStructureOnLoad(next).nodes +} + +afterEach(() => { + useScene.getState().unloadScene() + useScene.temporal.getState().clear() +}) + +test('footprint lift follows the storey, ceilings and roofs; upper levels move once; shed stays put; reset reverses', () => { + const before = scene() + const plate = base(before) + const wall = before.wall_lift0_0 as WallNode + const raised = apply( + before, + setFloorFoundation(before, { slabId: plate.id, patch: { floorHeight: 0.55 } }), + ) + expect(raised[wall.id]).not.toHaveProperty('height') + expect(getWallPlaneTop(wall, wall.parentId!, raised)).toBeCloseTo(3.5) + expect(wallSupportForNodes(wall, raised).elevation).toBeCloseTo(0.55) + expect(resolveCeilingHeight(raised.ceiling_lift0 as CeilingNode, raised)).toBeCloseTo(3.49) + expect(resolveRoofElevation(raised.roof_lift as RoofNode, raised)).toBeCloseTo(3.5) + expect((raised.roof_custom as RoofNode).position[1]).toBe(3.5) + expect(getWallPlaneTop(before.wall_lift1_0 as WallNode, wall.parentId!, raised)).toBe(3) + expect(resolveCeilingHeight(raised.ceiling_lift1 as CeilingNode, raised)).toBeCloseTo(2.99) + expect(base(raised, 'zone_lift1')).toEqual(base(before, 'zone_lift1')) + expect(getLevelElevations(raised).get('level_lift1')!.baseY).toBe(3.5) + expect(getLevelElevations(raised).get('level_lift2')!.baseY).toBe(6.5) + const taller = { ...raised, level_lift0: { ...raised.level_lift0, height: 4 } as AnyNode } + expect(getWallPlaneTop(wall, wall.parentId!, taller)).toBeCloseTo(4.5) + const reset = apply( + raised, + setFloorFoundation(raised, { slabId: plate.id, patch: { floorHeight: null } }), + ) + expect(reset[wall.id]).not.toHaveProperty('height') + expect(getWallPlaneTop(wall, wall.parentId!, reset)).toBe(3) + expect(getLevelElevations(reset)).toEqual(getLevelElevations(before)) + expect(reset.roof_custom).toEqual(before.roof_custom) + expect(reconcileStructureOnLoad(raised).nodes).toEqual(raised) +}) + +test('an upper floor spanning house and shed refuses one lift, accepts a matching batch', () => { + const nodes = scene(true) + const house = base(nodes), + shed = base(nodes, 'zone_lift1') + const plan = setFloorFoundation(nodes, { slabId: house.id, patch: { floorHeight: 0.55 } }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]).toMatchObject({ + code: 'floor-foundation-shared-storey', + message: 'The upper floor also sits over Shed floor; raise both or neither.', + }) + const updates = expandFloorIntentChanges( + nodes, + [house, shed].map((plate) => ({ id: plate.id, data: { floorHeight: 0.55 } })), + ) + expect(floorIntentConflicts(nodes, updates)).toEqual([]) + expect(updates.filter((update) => update.id === 'level_lift1')).toEqual([]) + const batch = setFloorFoundation(nodes, { + slabIds: [house.id, shed.id], + patch: { floorHeight: 0.55 }, + }) + const raised = apply(nodes, batch) + expect(getLevelElevations(raised).get('level_lift1')!.baseY).toBe(3.5) +}) + +test('the whole lift is one undo step', () => { + const nodes = scene() + useScene.setState({ nodes, rootNodeIds: ['building_lift'], readOnly: false }) + useScene.temporal.getState().clear() + const plan = setFloorFoundation(nodes, { slabId: base(nodes).id, patch: { floorHeight: 0.55 } }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + expect(getLevelElevations(useScene.getState().nodes).get('level_lift2')!.baseY).toBe(6.5) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(nodes) +}) + +test('migration removes only explicit wall heights equal to footprint following', () => { + const nodes = scene() + const plate = base(nodes) + const old = { + ...nodes, + [plate.id]: { ...plate, floorHeight: 0.55 }, + wall_lift0_0: { ...nodes.wall_lift0_0, height: 2.95 }, + wall_lift0_1: { ...nodes.wall_lift0_1, height: 1.7 }, + } as Record + const first = reconcileStructureOnLoad(old).nodes + expect(first.wall_lift0_0).not.toHaveProperty('height') + expect(first.wall_lift0_1).toHaveProperty('height', 1.7) + expect(reconcileStructureOnLoad(first).nodes).toEqual(first) +}) + +test('a rotated custom roof follows its segment footprint even when its origin is outside the house', () => { + const nodes = scene() + const roof = RoofNode.parse({ + id: 'roof_offset', + parentId: 'level_lift0', + position: [20, 3, 2], + rotation: Math.PI / 2, + children: ['rseg_offset'], + }) + const segment = RoofSegmentNode.parse({ + id: 'rseg_offset', + parentId: roof.id, + width: 4, + depth: 4, + position: [0, 0, -18], + }) + const source = { ...nodes, [roof.id]: roof, [segment.id]: segment } + const plan = setFloorFoundation(source, { slabId: base(source).id, patch: { floorHeight: 0.55 } }) + expect(plan.conflicts).toEqual([]) + expect( + plan.changes.find((change) => change.op === 'update' && change.id === roof.id), + ).toMatchObject({ data: { position: [20, 3.5, 2] } }) +}) + +test('existing upper-level offsets are preserved when lifting and resetting a footprint', () => { + const initial = scene() + const nodes: Record = { + ...initial, + level_lift1: { ...initial.level_lift1, baseElevation: 0.7 } as AnyNode, + } + const wall = nodes.wall_lift0_0 as WallNode + const before = getWallPlaneTop(wall, wall.parentId!, nodes) + const raised = apply( + nodes, + setFloorFoundation(nodes, { slabId: base(nodes).id, patch: { floorHeight: 0.55 } }), + ) + expect(getWallPlaneTop(wall, wall.parentId!, raised) - before).toBeCloseTo(0.5) + expect(getLevelElevations(raised).get('level_lift2')!.baseY).toBeCloseTo(7.2) + const reset = apply( + raised, + setFloorFoundation(raised, { slabId: base(raised).id, patch: { floorHeight: null } }), + ) + expect(getLevelElevations(reset)).toEqual(getLevelElevations(nodes)) +}) + +test('automatic footprint datum refreshes after support changes in a reconciliation graph', () => { + const nodes = scene() + const plate = base(nodes) + expect(automaticFloorHeight(nodes, plate)).toBeCloseTo(0.05) + const wall = nodes.wall_lift0_0 as WallNode + nodes[wall.id] = { ...wall, supportSlabId: GROUND_SUPPORT_ID, supportOffset: 0.2 } + expect(automaticFloorHeight(nodes, plate)).toBeCloseTo(0.25) + expect(automaticFloorHeight({ ...nodes }, plate)).toBeCloseTo(0.25) + nodes[wall.id] = wall + expect(automaticFloorHeight(nodes, plate)).toBeCloseTo(0.05) +}) + +test('upper construction can appear or disappear while raised without wall drift or reset residue', () => { + const initial = scene() + for (const empty of [false, true]) { + const before = { ...initial } + if (empty) { + delete before.slab_1 + delete before.slab_2 + } + const raised = apply( + before, + setFloorFoundation(before, { slabId: base(before).id, patch: { floorHeight: 0.55 } }), + ) + const changed = { ...raised } + if (empty) { + changed.slab_1 = initial.slab_1! + changed.slab_2 = initial.slab_2! + } else { + delete changed.slab_1 + delete changed.slab_2 + } + expect(getWallPlaneTop(changed.wall_lift0_0 as WallNode, 'level_lift0', changed)).toBeCloseTo( + 3.5, + ) + expect(getWallPlaneTop(changed.wall_lift1_0 as WallNode, 'level_lift0', changed)).toBe(3) + expect(getLevelElevations(changed).get('level_lift1')!.baseY).toBe(empty ? 3.5 : 3) + const reset = apply( + changed, + setFloorFoundation(changed, { slabId: base(changed).id, patch: { floorHeight: null } }), + ) + expect(getLevelElevations(reset).get('level_lift1')!.baseY).toBe(3) + expect(reset.level_lift1).toHaveProperty('baseElevation', 0) + } +}) + +test('automatic ground datum changes leave no stack residue on reset', () => { + const before = scene() + const raised = apply( + before, + setFloorFoundation(before, { slabId: base(before).id, patch: { floorHeight: 0.55 } }), + ) + const changed = { + ...raised, + wall_lift0_0: { ...raised.wall_lift0_0, supportSlabId: 'ground', supportOffset: 0.3 }, + } as Record + expect(getLevelElevations(changed).get('level_lift1')!.baseY).toBeCloseTo(3.2) + const reset = apply( + changed, + setFloorFoundation(changed, { slabId: base(changed).id, patch: { floorHeight: null } }), + ) + expect(getLevelElevations(reset).get('level_lift1')!.baseY).toBe(3) + expect(getLevelElevations(reset).get('level_lift2')!.baseY).toBe(6) +}) + +test('shared roof and custom ceiling require both footprints, and translate only once', () => { + for (const type of ['roof', 'ceiling']) { + const before = scene() + const shared = + type === 'roof' + ? RoofNode.parse({ + id: 'roof_shared', + parentId: 'level_lift0', + position: [7, 3, 2], + children: ['rseg_shared'], + }) + : CeilingNode.parse({ + id: 'ceiling_shared', + parentId: 'level_lift0', + polygon: rect(0, 14), + height: 2.5, + }) + const nodes = { + ...before, + [shared.id]: shared, + rseg_shared: RoofSegmentNode.parse({ + id: 'rseg_shared', + parentId: 'roof_shared', + width: 14, + depth: 4, + }), + } + const ids = [base(nodes).id, base(nodes, 'zone_lift1').id] + expect( + setFloorFoundation(nodes, { slabId: ids[0], patch: { floorHeight: 0.55 } }).conflicts?.[0] + ?.code, + ).toBe('floor-foundation-shared-storey') + const plan = setFloorFoundation(nodes, { slabIds: ids, patch: { floorHeight: 0.55 } }) + expect(plan.conflicts).toEqual([]) + expect( + plan.changes.filter((change) => change.op === 'update' && change.id === shared.id), + ).toEqual([ + { + op: 'update', + id: shared.id, + data: type === 'roof' ? { position: [7, 3.5, 2] } : { height: 3 }, + }, + ]) + } +}) + +test('roomless and tiny footprint remnants do not block the upper storey and follow its lift', () => { + const nodes = scene() + const sliver = SlabNode.parse({ + id: 'slab_sliver', + parentId: 'level_lift0', + plateRole: 'base', + boundary: 'auto', + polygon: [ + [3.8, 0], + [4, 0], + [4, 4], + [3.8, 4], + ], + zoneIds: [], + }) + nodes[sliver.id] = sliver + const plan = setFloorFoundation(nodes, { slabId: base(nodes).id, patch: { floorHeight: 0.55 } }) + expect(plan.conflicts).toEqual([]) + expect( + plan.changes.find((change) => change.op === 'update' && change.id === sliver.id), + ).toMatchObject({ data: { floorHeight: 0.55 } }) +}) + +test('roof overhang on an upper storey does not make the shed its support', () => { + const nodes = scene() + nodes.roof_overhang = RoofNode.parse({ + id: 'roof_overhang', + parentId: 'level_lift1', + position: [12, 0, 2], + }) + expect( + setFloorFoundation(nodes, { slabId: base(nodes).id, patch: { floorHeight: 0.55 } }).conflicts, + ).toEqual([]) +}) + +test('manual decks and ground-hosted construction keep ground-relative heights inside the lifted footprint', () => { + const before = scene() + const deck = SlabNode.parse({ + id: 'slab_deck', + parentId: 'level_lift0', + polygon: [ + [1, 1], + [3, 1], + [3, 3], + [1, 3], + ], + elevation: 0.3, + }) + const fence = FenceNode.parse({ + id: 'fence_ground', + parentId: deck.parentId, + start: [1, 1], + end: [3, 1], + supportSlabId: 'ground', + }) + const column = ColumnNode.parse({ + id: 'column_ground', + parentId: deck.parentId, + position: [2, 0.2, 2], + supportSlabId: 'ground', + }) + const wall = WallNode.parse({ + id: 'wall_ground', + parentId: deck.parentId, + start: [1, 0.5], + end: [3, 0.5], + supportSlabId: 'ground', + supportOffset: 0.2, + }) + const nodes = { + ...before, + [deck.id]: deck, + [fence.id]: fence, + [column.id]: column, + [wall.id]: wall, + } + const plan = setFloorFoundation(nodes, { slabId: base(nodes).id, patch: { floorHeight: 0.55 } }) + expect(plan.conflicts).toEqual([]) + const raised = { ...nodes } + for (const change of plan.changes) + if (change.op === 'update') + raised[change.id] = { ...raised[change.id], ...change.data } as AnyNode + expect(liftedManualSlab(raised, deck).elevation).toBeCloseTo(0.8) + expect(floorConstructionLift(raised, fence)).toBeCloseTo(0.5) + expect(floorConstructionLift(raised, column)).toBeCloseTo(0.5) + expect(wallSupportForNodes(wall, raised).elevation).toBeCloseTo(0.7) + expect(liftedManualSlab(raised, { ...deck, polygon: rect(10, 2) }).elevation).toBe(0.3) + expect(raised[deck.id]).toEqual(deck) + const reset = { ...raised, [base(nodes).id]: { ...base(nodes), floorHeight: undefined } } + expect(liftedManualSlab(reset, deck)).toBe(deck) + expect(wallSupportForNodes(wall, reset).elevation).toBeCloseTo(0.2) +}) + +test('core outdoor overlap is refused before creating separators; adjoining terraces are allowed', () => { + const nodes = scene() + const polygon = rect(1) + expect(outdoorRoomConflicts(nodes, 'level_lift0', polygon)).toHaveLength(1) + const mintId = () => { + throw new Error('must not mint on refusal') + } + expect( + createZone(nodes, { levelId: 'level_lift0', polygon, enclose: false, mintId }).conflicts?.[0] + ?.code, + ).toBe('outdoor-room-overlap') + expect(outdoorRoomConflicts(nodes, 'level_lift0', rect(4))).toEqual([]) +}) + +test('an upper wall retains its storey height when the next upper storey is empty', () => { + const nodes = scene() + delete nodes.slab_2 + const wall = WallNode.parse({ + id: 'wall_upper', + parentId: 'level_lift1', + start: [0, 0], + end: [4, 0], + }) + nodes[wall.id] = wall + const raised = apply( + nodes, + setFloorFoundation(nodes, { slabId: base(nodes).id, patch: { floorHeight: 0.55 } }), + ) + expect(getLevelElevations(raised).get('level_lift1')!.baseY).toBe(3.5) + expect(getWallPlaneTop(wall, wall.parentId!, raised)).toBe(3) + expect(raised[wall.id]).not.toHaveProperty('height') +}) + +test('a tiny room carried under the upper storey retains its own floor step', () => { + const nodes = scene() + const polygon: [number, number][] = [ + [3.8, 0], + [4, 0], + [4, 4], + [3.8, 4], + ] + const zone = ZoneNode.parse({ + id: 'zone_tiny', + name: 'Tiny room', + parentId: 'level_lift0', + polygon, + spaceRole: 'room', + floor: { elevation: 0.25 }, + }) + const sliver = SlabNode.parse({ + id: 'slab_tiny', + parentId: zone.parentId, + plateRole: 'base', + boundary: 'auto', + polygon, + zoneIds: [zone.id], + }) + const graph = { ...nodes, [zone.id]: zone, [sliver.id]: sliver } + const plan = setFloorFoundation(graph, { slabId: base(graph).id, patch: { floorHeight: 0.55 } }) + expect(plan.conflicts).toEqual([]) + expect( + plan.changes.find((change) => change.op === 'update' && change.id === zone.id), + ).toMatchObject({ data: { floor: { elevation: 0.75 } } }) +}) diff --git a/packages/core/src/commands/structure/floor-grade-round-trip.test.ts b/packages/core/src/commands/structure/floor-grade-round-trip.test.ts new file mode 100644 index 0000000000..0be42fd04b --- /dev/null +++ b/packages/core/src/commands/structure/floor-grade-round-trip.test.ts @@ -0,0 +1,79 @@ +import { expect, test } from 'bun:test' +import { groundFloorConstruction } from '../../lib/floor-foundation-datum' +import { expandFloorIntentChanges } from '../../lib/floor-intent-changes' +import type { AnyNode, SlabNode } from '../../schema' +import { filterDerivedNodeWrites } from '../../store/derived-node-guard' +import { floorStepFixture } from '../../systems/slab/__fixtures__/floor-step' +import { reconcileStructureWithStableIds } from '../../utils/structure-id' +import { setRoomFloorConstruction } from './set-room-floor-construction' +import { applyToScratch, structureChangeBatch } from './shared' + +const reconcile = (nodes: Record) => ({ + ...reconcileStructureWithStableIds({ nodes }).nodes, +}) + +for (const footprint of [undefined, 'own']) { + test(`${footprint ?? 'shared'} ground floor foundation 0 → 0.05 → 0 round-trips its finish`, () => { + const fixture = floorStepFixture(true) + const zoneId = fixture.zones[1]!.id + let nodes = reconcile( + Object.fromEntries(Object.entries(fixture.nodes).filter(([, node]) => node.type !== 'slab')), + ) + const room = nodes[zoneId]! + nodes = reconcile({ ...nodes, [zoneId]: { ...room, floor: { footprint } } as AnyNode }) + const plate = Object.values(nodes).find( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && !!node.zoneIds?.includes(zoneId), + )! + const { grade } = groundFloorConstruction(nodes, plate) + const write = (foundationHeight: number) => { + const plan = setRoomFloorConstruction(nodes, { zoneId, patch: { foundationHeight } }) + expect(plan.conflicts ?? []).toEqual([]) + nodes = reconcile( + applyToScratch(nodes, filterDerivedNodeWrites(nodes, structureChangeBatch(plan.changes))), + ) + expect((nodes[plate.id] as SlabNode).elevation).toBeCloseTo( + grade + foundationHeight + plate.thickness, + ) + } + write(0) + nodes = reconcile({ + ...nodes, + [plate.id]: { + ...nodes[plate.id], + foundation: { type: 'none', material: 'library:stone' }, + } as SlabNode, + }) + const before = nodes + for (let trip = 0; trip < 2; trip++) { + write(0.05) + expect((nodes[plate.id] as SlabNode).foundation).toEqual({ + type: 'solid', + material: 'library:stone', + }) + expect((nodes[plate.id] as SlabNode).thickness).toBe(plate.thickness) + expect(reconcile(nodes)).toEqual(nodes) + write(0) + expect(nodes).toEqual(before) + } + const stale = { + ...nodes, + [plate.id]: { + ...nodes[plate.id], + foundation: { type: 'solid', material: 'library:stone' }, + } as SlabNode, + } + const plan = setRoomFloorConstruction(stale, { zoneId, patch: { foundationHeight: 0.05 } }) + expect(plan.conflicts ?? []).toEqual([]) + const raised = reconcile(applyToScratch(stale, structureChangeBatch(plan.changes)))[ + plate.id + ] as SlabNode + expect(raised.elevation).toBeCloseTo(grade + 0.05 + plate.thickness) + expect(raised.foundation).toEqual({ type: 'solid', material: 'library:stone' }) + const top = grade + 0.05 + plate.thickness + const direct = expandFloorIntentChanges(nodes, [{ id: plate.id, data: { floorHeight: top } }]) + expect(direct.find((update) => update.id === plate.id)?.data).toMatchObject({ + foundation: { type: 'solid' }, + }) + }) +} diff --git a/packages/core/src/commands/structure/floor-opening.ts b/packages/core/src/commands/structure/floor-opening.ts new file mode 100644 index 0000000000..7eb1d4a112 --- /dev/null +++ b/packages/core/src/commands/structure/floor-opening.ts @@ -0,0 +1,172 @@ +import { adjacentLevelId, floorOpeningTargets } from '../../lib/floor-opening-intent' +import { area, intersection, type Ring, union } from '../../lib/polygon-boolean' +import { type AnyNode, type AnyNodeId, FloorOpeningNode } from '../../schema' +import type { StructureNodes, StructurePlan } from './shared' + +export type CutFloorOpeningInput = { + levelId?: string + zoneId?: string + levelIds?: string[] + polygon?: Ring + rect?: { x: number; z: number; width: number; depth: number } + drawnOn?: 'floor' | 'ceiling' + cutsPrimary?: boolean + cutsAdjacent?: boolean + source?: string + ownerId?: string + mintId: (kind: 'floor-opening') => string +} + +export type FloorOpeningHint = { + code: 'manual-ceiling' + openingId: string + surfaceIds: string[] + message: string +} + +function surfaceFootprint(node: { polygon: Ring; holes?: Ring[] }) { + return { outer: node.polygon, holes: node.holes ?? [] } +} + +export function floorOpeningHints( + nodes: StructureNodes, + opening: FloorOpeningNode, +): FloorOpeningHint[] { + const ceilingTargets = floorOpeningTargets(nodes, opening).filter( + (target) => target.surface === 'ceiling', + ) + const surfaceIds = Object.values(nodes) + .filter( + (node) => + node.type === 'ceiling' && + node.boundary !== 'auto' && + ceilingTargets.some((target) => target.levelId === node.parentId) && + area(intersection(opening.polygon, surfaceFootprint(node))) > 1e-6, + ) + .map((node) => node.id) + .sort() + return surfaceIds.length + ? [ + { + code: 'manual-ceiling', + openingId: opening.id, + surfaceIds, + message: 'The adjacent ceiling is manual. Cut it in Edit ceiling.', + }, + ] + : [] +} + +function adjacentSurfaceExists( + nodes: StructureNodes, + levelId: string, + drawnOn: 'floor' | 'ceiling', + polygon: Ring, +) { + const adjacent = adjacentLevelId(nodes, levelId, drawnOn === 'floor' ? -1 : 1) + if (!adjacent) return false + return Object.values(nodes).some( + (node) => + node.parentId === adjacent && + (drawnOn === 'floor' ? node.type === 'ceiling' : node.type === 'slab') && + (node.type === 'ceiling' || node.type === 'slab') && + area(intersection(polygon, surfaceFootprint(node))) > 1e-6, + ) +} + +export function cutFloorOpening( + nodes: StructureNodes, + input: CutFloorOpeningInput, +): StructurePlan & { openingIds: string[]; hints: FloorOpeningHint[] } { + const zone = input.zoneId ? nodes[input.zoneId] : undefined + if (input.zoneId && (zone?.type !== 'zone' || zone.spaceRole !== 'room')) + throw Error(`Room not found: ${input.zoneId}`) + const levelIds = [...new Set(input.levelIds ?? [input.levelId ?? zone?.parentId ?? ''])] + if (!levelIds.length || levelIds.some((id) => nodes[id]?.type !== 'level')) + throw Error('Specify an existing levelId or room zoneId.') + if (zone && input.levelId && zone.parentId !== input.levelId) + throw Error('The room is not on the specified level.') + const polygon = + input.polygon ?? + (input.rect + ? ([ + [input.rect.x, input.rect.z], + [input.rect.x + input.rect.width, input.rect.z], + [input.rect.x + input.rect.width, input.rect.z + input.rect.depth], + [input.rect.x, input.rect.z + input.rect.depth], + ] as Ring) + : undefined) + if (!polygon || polygon.length < 3 || !polygon.every((point) => point.every(Number.isFinite))) + throw Error('Supply a finite polygon with at least three vertices, or a rect.') + if (area(union([polygon])) <= 1e-6) throw Error('The opening polygon has no area.') + const drawnOn = input.drawnOn ?? 'floor' + if (zone?.type === 'zone' && zone.floor?.support === 'open' && drawnOn !== 'floor') + throw Error('A mezzanine hatch must be drawn on its floor.') + const openings = levelIds.map((levelId) => { + const hostZoneId = + zone?.type === 'zone' && zone.floor?.support === 'open' && zone.parentId === levelId + ? zone.id + : undefined + const id = input.mintId('floor-opening') + if (nodes[id]) throw Error(`Duplicate opening id: ${id}`) + return FloorOpeningNode.parse({ + id, + parentId: levelId, + name: 'Floor opening', + polygon, + ...(hostZoneId ? { hostZoneId } : {}), + source: input.source ?? 'manual', + ownerId: input.ownerId, + drawnOn, + cutsPrimary: input.cutsPrimary ?? true, + cutsAdjacent: + hostZoneId !== undefined + ? false + : (input.cutsAdjacent ?? adjacentSurfaceExists(nodes, levelId, drawnOn, polygon)), + }) + }) + const levelUpdates = levelIds.map((levelId) => { + const level = nodes[levelId] as Extract + return { + op: 'update' as const, + id: level.id, + data: { + children: [ + ...level.children, + ...openings + .filter((opening) => opening.parentId === levelId) + .map((opening) => opening.id), + ], + }, + } + }) + return { + changes: [...openings.map((node) => ({ op: 'create' as const, node })), ...levelUpdates], + openingIds: openings.map((opening) => opening.id), + hints: openings.flatMap((opening) => floorOpeningHints(nodes, opening)), + } +} + +export function removeFloorOpening( + nodes: StructureNodes, + id: string, +): StructurePlan & { openingId: string } { + const opening = nodes[id] + if (opening?.type !== 'floor-opening') throw Error(`Floor opening not found: ${id}`) + const level = opening.parentId ? nodes[opening.parentId] : undefined + return { + openingId: id, + changes: [ + { op: 'delete', id: opening.id as AnyNodeId }, + ...(level?.type === 'level' + ? [ + { + op: 'update' as const, + id: level.id, + data: { children: level.children.filter((child) => child !== id) }, + }, + ] + : []), + ], + } +} diff --git a/packages/core/src/commands/structure/ground-floor-construction.test.ts b/packages/core/src/commands/structure/ground-floor-construction.test.ts new file mode 100644 index 0000000000..014576ca77 --- /dev/null +++ b/packages/core/src/commands/structure/ground-floor-construction.test.ts @@ -0,0 +1,157 @@ +import { expect, test } from 'bun:test' +import { groundFloorConstruction } from '../../lib/floor-foundation-datum' +import { wallSupportForNodes } from '../../lib/opening-floor-datum' +import { + type AnyNode, + BuildingNode, + LevelNode, + type SlabNode, + type WallNode, + type ZoneNode, +} from '../../schema' +import { filterDerivedNodeWrites } from '../../store/derived-node-guard' +import { floorStepFixture } from '../../systems/slab/__fixtures__/floor-step' +import { reconcileStructureOnLoad } from '../../utils/reconcile-structure-on-load' +import { type FloorFoundationPatch, setFloorFoundation } from './set-floor-foundation' + +// Ground floors: slab thickness + foundation height are the two inputs; the top +// is grade + foundation + thickness, the slab grows upward and carries everything. + +function scene() { + const f = floorStepFixture() + const nodes = Object.fromEntries( + Object.entries(f.nodes).filter(([, node]) => node.type !== 'slab'), + ) as Record + const loaded = reconcileStructureOnLoad(nodes).nodes as Record + const plate = Object.values(loaded).find( + (n): n is SlabNode => n.type === 'slab' && n.plateRole === 'base', + )! + return { nodes: loaded, plate, wall: loaded.wall_step_0 as WallNode, step: f.zones[1]!.id } +} + +function apply(nodes: Record, slabId: string, patch: FloorFoundationPatch) { + const plan = setFloorFoundation(nodes, { slabId, patch }) + expect(plan.conflicts ?? []).toEqual([]) + const updates = plan.changes.flatMap((c) => (c.op === 'update' ? [c] : [])) + const next = { ...nodes } + for (const { id, data } of filterDerivedNodeWrites(nodes, { update: updates }).update) + next[id] = { ...next[id], ...data } as AnyNode + return reconcileStructureOnLoad(next).nodes as Record +} + +const plateOf = (nodes: Record, id: string) => nodes[id] as SlabNode +const top = (plate: SlabNode) => plate.floorHeight ?? plate.elevation + +test('a legacy default plate loads unchanged and reads on the ground, slab 0.05, top 0.05', () => { + const { nodes, plate } = scene() + expect(plate.floorHeight).toBeUndefined() + expect(plate.elevation).toBeCloseTo(0.05) + expect(plate.thickness).toBeCloseTo(0.05) + expect(groundFloorConstruction(nodes, plate)).toMatchObject({ + grade: expect.closeTo(0), + top: expect.closeTo(0.05), + foundationHeight: 0, + }) + expect(reconcileStructureOnLoad(nodes).nodes).toEqual(nodes) +}) + +test('thicker slab 0.05 → 0.10 raises the top by 0.05 and the walls and room steps with it', () => { + const { nodes, plate, wall, step } = scene() + const wallBefore = wallSupportForNodes(wall, nodes).elevation + const stepBefore = (nodes[step] as ZoneNode).floor!.elevation! + const next = apply(nodes, plate.id, { thickness: 0.1 }) + const after = plateOf(next, plate.id) + expect(top(after)).toBeCloseTo(0.1) + expect(after.thickness).toBeCloseTo(0.1) + expect(top(after) - after.thickness).toBeCloseTo(0) + expect(after.foundation?.type ?? 'none').toBe('none') + expect(wallSupportForNodes(wall, next).elevation).toBeCloseTo(wallBefore + 0.05) + expect((next[step] as ZoneNode).floor!.elevation).toBeCloseTo(stepBefore + 0.05) +}) + +test('foundation 0 → 0.3 raises everything by 0.3 with a solid foundation; back to the ground', () => { + const { nodes, plate, wall, step } = scene() + const wallBefore = wallSupportForNodes(wall, nodes).elevation + const stepBefore = (nodes[step] as ZoneNode).floor!.elevation! + const raised = apply(nodes, plate.id, { foundationHeight: 0.3 }) + const up = plateOf(raised, plate.id) + expect(top(up)).toBeCloseTo(0.35) + expect(top(up) - up.thickness).toBeCloseTo(0.3) + expect(up.foundation?.type).toBe('solid') + expect(groundFloorConstruction(raised, up).foundationHeight).toBeCloseTo(0.3) + expect(wallSupportForNodes(wall, raised).elevation).toBeCloseTo(wallBefore + 0.3) + expect((raised[step] as ZoneNode).floor!.elevation).toBeCloseTo(stepBefore + 0.3) + const lowered = apply(raised, plate.id, { foundationHeight: 0 }) + const down = plateOf(lowered, plate.id) + expect(top(down)).toBeCloseTo(0.05) + expect(down.foundation?.type).toBe('none') + expect(wallSupportForNodes(wall, lowered).elevation).toBeCloseTo(wallBefore) +}) + +test('thicker slab on a foundation keeps the underside on the foundation', () => { + const { nodes, plate } = scene() + const raised = apply(nodes, plate.id, { foundationHeight: 0.3 }) + const thick = plateOf(apply(raised, plate.id, { thickness: 0.2 }), plate.id) + expect(top(thick)).toBeCloseTo(0.5) + expect(top(thick) - thick.thickness).toBeCloseTo(0.3) + expect(thick.foundation?.type).toBe('solid') +}) + +test('slab 0.01 on the ground sits on grade: no gap under it', () => { + const { nodes, plate, wall } = scene() + const next = apply(nodes, plate.id, { thickness: 0.01 }) + const thin = plateOf(next, plate.id) + expect(thin.thickness).toBeCloseTo(0.01) + expect(top(thin)).toBeCloseTo(0.01) + expect(top(thin) - thin.thickness).toBeCloseTo(0) + expect(thin.elevation).toBeCloseTo(0.01) + expect(wallSupportForNodes(wall, next).elevation).toBeCloseTo(0.01) +}) + +test('slab thickness 0 is clamped to 0.01', () => { + const { nodes, plate } = scene() + const thin = plateOf(apply(nodes, plate.id, { thickness: 0 }), plate.id) + expect(thin.thickness).toBeCloseTo(0.01) + expect(top(thin) - thin.thickness).toBeCloseTo(0) +}) + +test('a legacy thick slab under a lower top reads on the ground and lands on grade on its next edit', () => { + const { nodes, plate } = scene() + const legacy = { ...nodes, [plate.id]: { ...plate, thickness: 0.2 } as SlabNode } + expect(groundFloorConstruction(legacy, legacy[plate.id] as SlabNode).foundationHeight).toBe(0) + const edited = plateOf(apply(legacy, plate.id, { foundationHeight: 0 }), plate.id) + expect(top(edited)).toBeCloseTo(0.2) + expect(top(edited) - edited.thickness).toBeCloseTo(0) +}) + +test('upper storeys keep their model: thickness grows up from the walls below, no foundation', () => { + const { nodes: ground, plate } = scene() + const f = floorStepFixture() + const lower = LevelNode.parse({ id: 'level_ground', level: 0 }) + const building = BuildingNode.parse({ children: [lower.id, f.level.id] }) + const nodes = { + ...ground, + [building.id]: building, + [lower.id]: { ...lower, parentId: building.id }, + [f.level.id]: { ...ground[f.level.id], level: 1, parentId: building.id }, + zone_ground_room: { ...f.zones[0]!, id: 'zone_ground_room', parentId: lower.id }, + slab_ground_plate: { + ...plate, + id: 'slab_ground_plate', + parentId: lower.id, + zoneIds: ['zone_ground_room'], + }, + } as Record + const upper = plateOf(nodes, plate.id) + const underside = top(upper) - upper.thickness + const plan = setFloorFoundation(nodes, { slabId: upper.id, patch: { thickness: 0.2 } }) + expect(plan.conflicts ?? []).toEqual([]) + const write = plan.changes.find((c) => c.op === 'update' && c.id === upper.id) + expect(write).toMatchObject({ + data: { thickness: expect.closeTo(0.2), elevation: expect.closeTo(underside + 0.2) }, + }) + expect( + setFloorFoundation(nodes, { slabId: upper.id, patch: { foundationHeight: 0.3 } }).conflicts?.[0] + ?.code, + ).toBe('floor-foundation-level') +}) diff --git a/packages/core/src/commands/structure/index.ts b/packages/core/src/commands/structure/index.ts new file mode 100644 index 0000000000..643cf6f6b8 --- /dev/null +++ b/packages/core/src/commands/structure/index.ts @@ -0,0 +1,52 @@ +export { + applyZoneTransformPlan, + type CeilingHostAssignment, + type HostedZoneTransformPlan, + resolveZoneTransformHosts, + type SupportHostAssignment, +} from './apply-zone-transform' +export { type CreateMezzanineInput, createMezzanine } from './create-mezzanine' +export { type CreateZoneInput, createZone, outdoorRoomConflicts } from './create-zone' +export { type DeleteZonePayload, deleteZone, SHARED_WALLS_DELETE_MESSAGE } from './delete-zone' +export { + createZoneDivisionContext, + divideZone, + snapZoneBoundary, + type ZoneDivisionContext, +} from './divide-zone' +export { type DuplicateZoneInput, duplicateZone } from './duplicate-zone' +export { + type CutFloorOpeningInput, + cutFloorOpening, + type FloorOpeningHint, + floorOpeningHints, + removeFloorOpening, +} from './floor-opening' +export { type LockOutsideFacesInput, lockOutsideFaces } from './lock-outside-faces' +export { mergeZones } from './merge-zones' +export { type MezzanineStairPlan, planMezzanineStair } from './plan-mezzanine-stair' +export { planWallDeletion } from './plan-wall-deletion' +export { rebaseFloorReference } from './rebase-floor-reference' +export type { MezzanineEdgeInput } from './resize-mezzanine' +export { type RotateZoneInput, rotateZone } from './rotate-zone' +export { + DEFAULT_FOUNDATION_HEIGHT, + DEFAULT_FOUNDATION_MATERIAL, + FloorFoundationPatch, + setFloorFoundation, +} from './set-floor-foundation' +export { setRoomFloorConstruction } from './set-room-floor-construction' +export { setWallGeometry } from './set-wall-geometry' +export { setZoneEdges } from './set-zone-edges' +export { setZoneIntent, ZoneIntentPatch } from './set-zone-intent' +export { + type NodeChange, + type Point, + type SpanRef, + type StructureConflict, + type StructureMintId, + type StructureNodes, + type StructurePlan, + structureChangeBatch, +} from './shared' +export { type TransformZoneInput, transformZone, type ZoneTransformPlan } from './transform-zone' diff --git a/packages/core/src/commands/structure/legacy-floor-reference.test.ts b/packages/core/src/commands/structure/legacy-floor-reference.test.ts new file mode 100644 index 0000000000..96ac296b6b --- /dev/null +++ b/packages/core/src/commands/structure/legacy-floor-reference.test.ts @@ -0,0 +1,299 @@ +import { afterEach, expect, test } from 'bun:test' +import { buildFloorPlates, type PlateRoom } from '../../lib/floor-plates' +import { type AnyNode, LevelNode, SlabNode, ZoneNode } from '../../schema' +import { getLevelElevations } from '../../services/storey' +import useScene from '../../store/use-scene' +import { migrateFloorPlates } from '../../utils/floor-plate-migration' +import { rebaseFloorReference } from './rebase-floor-reference' +import { setRoomFloorConstruction } from './set-room-floor-construction' +import { applyToScratch, structureChangeBatch } from './shared' + +const polygon: [number, number][] = [ + [0, 0], + [5, 0], + [5, 5], + [0, 5], +] + +function scene() { + const ground = LevelNode.parse({ id: 'level_ground', level: 0, height: 3 }) + const upper = LevelNode.parse({ id: 'level_upper', level: 1, height: 3 }) + const room = ZoneNode.parse({ + id: 'zone_ground', + parentId: ground.id, + name: 'Room', + spaceRole: 'room', + polygon, + }) + const upstairs = ZoneNode.parse({ + id: 'zone_upper', + parentId: upper.id, + name: 'Upper room', + spaceRole: 'room', + polygon, + }) + const base = SlabNode.parse({ + id: 'slab_ground', + parentId: ground.id, + polygon, + elevation: 0.2, + thickness: 0.05, + referenceFloorElevation: 0.2, + plateRole: 'base', + boundary: 'auto', + autoFromWalls: true, + zoneIds: [room.id], + }) + const upperPlate = SlabNode.parse({ + id: 'slab_upper', + parentId: upper.id, + polygon, + elevation: 0.05, + plateRole: 'base', + boundary: 'auto', + autoFromWalls: true, + zoneIds: [upstairs.id], + }) + ground.children = [room.id, base.id] + upper.children = [upstairs.id, upperPlate.id] + return Object.fromEntries( + [ground, upper, room, upstairs, base, upperPlate].map((node) => [node.id, node]), + ) as Record +} + +afterEach(() => { + useScene.getState().unloadScene() + useScene.temporal.getState().clear() +}) + +test('reference rebase is one atomic plan and keeps upper world placement', () => { + const nodes = scene() + const before = getLevelElevations(nodes).get('level_upper')!.baseY + const plan = rebaseFloorReference(nodes, { + slabId: 'slab_ground', + referenceFloorElevation: 0.05, + }) + expect(plan.conflicts).toBeUndefined() + const next = applyToScratch(nodes, structureChangeBatch(plan.changes)) + expect((next.slab_ground as SlabNode).elevation).toBe(0.2) + expect((next.slab_ground as SlabNode).referenceFloorElevation).toBe(0.05) + expect(getLevelElevations(next).get('level_upper')!.baseY).toBeCloseTo(before) + expect(plan.changes).toHaveLength(2) +}) + +test('shared upper storeys require a grouped reference rebase', () => { + const nodes = scene() + const garage = ZoneNode.parse({ + id: 'zone_garage', + parentId: 'level_ground', + name: 'Garage', + spaceRole: 'room', + polygon: [ + [5, 0], + [10, 0], + [10, 5], + [5, 5], + ], + }) + nodes[garage.id] = garage + const second = SlabNode.parse({ + ...(nodes.slab_ground as SlabNode), + id: 'slab_garage', + polygon: [ + [5, 0], + [10, 0], + [10, 5], + [5, 5], + ], + zoneIds: [garage.id], + }) + nodes[second.id] = second + nodes.slab_upper = { + ...(nodes.slab_upper as SlabNode), + polygon: [ + [0, 0], + [10, 0], + [10, 5], + [0, 5], + ], + } + nodes.zone_upper = { + ...(nodes.zone_upper as ZoneNode), + polygon: (nodes.slab_upper as SlabNode).polygon, + } + const before = getLevelElevations(nodes).get('level_upper')!.baseY + expect( + rebaseFloorReference(nodes, { + slabId: 'slab_ground', + referenceFloorElevation: 0.05, + }).conflicts?.[0]?.code, + ).toBe('floor-reference-shared-storey') + const grouped = rebaseFloorReference(nodes, { + slabIds: ['slab_ground', second.id], + referenceFloorElevation: 0.05, + }) + expect(grouped.conflicts).toBeUndefined() + const next = applyToScratch(nodes, structureChangeBatch(grouped.changes)) + expect(getLevelElevations(next).get('level_upper')!.baseY).toBeCloseTo(before) + expect((next.slab_garage as SlabNode).referenceFloorElevation).toBe(0.05) +}) + +test('room floor construction and reference rebase each undo and redo atomically', () => { + const nodes = scene() + useScene.setState({ nodes, rootNodeIds: ['level_ground', 'level_upper'], readOnly: false }) + useScene.temporal.getState().clear() + const edit = setRoomFloorConstruction(nodes, { + zoneId: 'zone_ground', + patch: { thickness: 0.1 }, + }) + useScene.getState().applyNodeChanges(structureChangeBatch(edit.changes)) + expect((useScene.getState().nodes.slab_ground as SlabNode).thickness).toBe(0.1) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(nodes) + useScene.temporal.getState().redo() + expect((useScene.getState().nodes.slab_ground as SlabNode).thickness).toBe(0.1) + + const beforeRebase = useScene.getState().nodes + const rebase = rebaseFloorReference(beforeRebase, { + slabId: 'slab_ground', + referenceFloorElevation: 0.05, + }) + useScene.getState().applyNodeChanges(structureChangeBatch(rebase.changes)) + expect((useScene.getState().nodes.slab_ground as SlabNode).referenceFloorElevation).toBe(0.05) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(beforeRebase) + useScene.temporal.getState().redo() + expect((useScene.getState().nodes.slab_ground as SlabNode).referenceFloorElevation).toBe(0.05) +}) + +test('room construction edits the associated footprint or authored slab in one plan', () => { + const nodes = scene() + const platePlan = setRoomFloorConstruction(nodes, { + zoneId: 'zone_ground', + patch: { thickness: 0.1 }, + }) + expect(platePlan.conflicts).toEqual([]) + expect( + platePlan.changes.some((change) => change.op === 'update' && change.id === 'slab_ground'), + ).toBe(true) + const authored = SlabNode.parse({ + id: 'slab_authored', + parentId: 'level_ground', + polygon, + thickness: 0.05, + }) + const room = nodes.zone_ground as ZoneNode + const manualNodes = { + ...nodes, + [authored.id]: authored, + [room.id]: { ...room, floor: { ...room.floor, sourceSlabId: authored.id } }, + } + const manualPlan = setRoomFloorConstruction(manualNodes, { + zoneId: room.id, + patch: { thickness: 0.12 }, + }) + expect(manualPlan.changes).toEqual([{ op: 'update', id: authored.id, data: { thickness: 0.12 } }]) + const chosen = setRoomFloorConstruction(manualNodes, { + zoneId: room.id, + slabId: authored.id, + patch: { thickness: 0.12 }, + }) + expect(chosen.changes).toEqual([{ op: 'update', id: authored.id, data: { thickness: 0.12 } }]) + const raised = setRoomFloorConstruction(manualNodes, { + zoneId: room.id, + patch: { floorHeight: 0.35 }, + }) + const moved = applyToScratch(manualNodes, structureChangeBatch(raised.changes)) + expect((moved[authored.id] as SlabNode).elevation).toBe(0.35) + expect((moved[room.id] as ZoneNode).floor?.sourceSlabId).toBe(authored.id) +}) + +test('old legacyFloor is migrated once into the normal reference datum', () => { + const nodes = scene() + const plate = nodes.slab_ground as SlabNode + const { referenceFloorElevation: _reference, ...legacy } = plate + const first = migrateFloorPlates({ ...nodes, [plate.id]: { ...legacy, legacyFloor: 0.2 } }).nodes + expect(first[plate.id]).toMatchObject({ referenceFloorElevation: 0.2 }) + expect(first[plate.id]).not.toHaveProperty('legacyFloor') + expect(migrateFloorPlates(first).nodes).toBe(first) +}) + +test('split footprints inherit their reference and unequal references remain separate on merge', () => { + const context = { revision: 0, walls: new Map(), wallFootprints: new Map() } + const room = (id: string, x0: number, x1: number): PlateRoom => { + const polygon: [number, number][] = [ + [x0, 0], + [x1, 0], + [x1, 5], + [x0, 5], + ] + const zone = ZoneNode.parse({ + id, + name: id, + parentId: 'level_ground', + spaceRole: 'room', + polygon, + }) + return { + id, + zone, + polygon, + holes: [], + spans: [], + context, + } + } + const source = SlabNode.parse({ + id: 'slab_source', + parentId: 'level_ground', + polygon: [ + [0, 0], + [10, 0], + [10, 5], + [0, 5], + ], + boundary: 'auto', + autoFromWalls: true, + plateRole: 'base', + referenceFloorElevation: 0.2, + }) + const mintId = (ids: string[], component = 0) => `slab_${ids.join('_')}_${component}` + const split = buildFloorPlates({ + levelId: 'level_ground', + rooms: [room('zone_left', 0, 4), room('zone_right', 6, 10)], + slabs: [source], + mintId, + }) + expect(split.plates).toHaveLength(2) + expect(split.plates.map((plate) => plate.referenceFloorElevation)).toEqual([0.2, 0.2]) + + const right = SlabNode.parse({ + ...source, + id: 'slab_right', + polygon: [ + [5, 0], + [10, 0], + [10, 5], + [5, 5], + ], + referenceFloorElevation: 0.4, + }) + const left = { + ...source, + polygon: [ + [0, 0], + [5, 0], + [5, 5], + [0, 5], + ] as [number, number][], + } + const merged = buildFloorPlates({ + levelId: 'level_ground', + rooms: [room('zone_left', 0, 5), room('zone_right', 5, 10)], + slabs: [left, right], + mintId, + }) + expect(merged.plates).toHaveLength(2) + expect(merged.plates.map((plate) => plate.referenceFloorElevation).sort()).toEqual([0.2, 0.4]) +}) diff --git a/packages/core/src/commands/structure/lock-outside-faces.ts b/packages/core/src/commands/structure/lock-outside-faces.ts new file mode 100644 index 0000000000..a7e4006249 --- /dev/null +++ b/packages/core/src/commands/structure/lock-outside-faces.ts @@ -0,0 +1,43 @@ +import { justificationForFaceOnLine, planWallJustification } from '../../systems/wall/wall-frame' +import { roomSideFaces } from '../../systems/wall/wall-room-sides' +import { requireZone, roomFace, type StructureNodes, type StructurePlan } from './shared' + +export type LockOutsideFacesInput = + | { levelId: string; zoneIds?: never } + | { zoneIds: string[]; levelId?: never } + +export function lockOutsideFaces( + nodes: StructureNodes, + input: LockOutsideFacesInput, +): StructurePlan & { wallIds: string[] } { + if (input.levelId && nodes[input.levelId]?.type !== 'level') + throw Error('Select an editable floor.') + const zones = + input.zoneIds?.map((id) => requireZone(nodes, id)) ?? + Object.values(nodes).filter( + (node) => + node.type === 'zone' && node.spaceRole === 'room' && node.parentId === input.levelId, + ) + const targets = new Set( + input.levelId + ? Object.values(nodes) + .filter((node) => node.type === 'wall' && node.parentId === input.levelId) + .map((node) => node.id) + : [], + ) + for (const zone of zones) { + if (zone.type !== 'zone') continue + for (const span of roomFace(nodes, zone)?.spans ?? []) + if (span.kind === 'wall') targets.add(span.boundaryId) + } + const patches: ReturnType = [] + for (const wallId of targets) { + const { outside } = roomSideFaces(nodes, wallId) + if (!outside) continue + patches.push(...planWallJustification(nodes, wallId, justificationForFaceOnLine(outside))) + } + return { + changes: patches.map((patch) => ({ op: 'update', ...patch })), + wallIds: patches.map((patch) => patch.id), + } +} diff --git a/packages/core/src/commands/structure/merge-zones.ts b/packages/core/src/commands/structure/merge-zones.ts new file mode 100644 index 0000000000..fc435cda8a --- /dev/null +++ b/packages/core/src/commands/structure/merge-zones.ts @@ -0,0 +1,50 @@ +import { extractRooms } from '../../lib/room-graph' +import { + boundaries, + conflict, + requireZone, + roomFace, + type StructureNodes, + type StructurePlan, +} from './shared' + +export function mergeZones( + nodes: StructureNodes, + input: { zoneIds: [string, string] }, +): StructurePlan { + const [a, b] = input.zoneIds.map((id) => requireZone(nodes, id)) + if (a!.id === b!.id || a!.parentId !== b!.parentId) + return conflict( + 'different-levels', + input.zoneIds, + 'Select two different rooms on the same level.', + ) + const left = roomFace(nodes, a!)?.spans ?? [] + const right = roomFace(nodes, b!)?.spans ?? [] + const common = left.filter((s) => + right.some( + (r) => + r.boundaryId === s.boundaryId && + r.face !== s.face && + Math.min(r.t1, s.t1) - Math.max(r.t0, s.t0) > 1e-6, + ), + ) + const separators = new Set(common.filter((s) => s.kind === 'separator').map((s) => s.boundaryId)) + if (!separators.size) + return conflict( + 'wall-boundary', + common.map((s) => s.boundaryId), + common.length + ? 'These rooms are separated by walls. Merge never removes walls.' + : 'These rooms do not share a separator.', + ) + const before = boundaries(nodes, a!.parentId!) + const after = before.filter((n) => !separators.has(n.id)) + if (extractRooms(after).length !== extractRooms(before).length - 1) + return conflict( + 'shared-separator', + [...separators], + 'Removing these separators would affect additional rooms.', + ) + return { changes: [...separators].map((id) => ({ op: 'delete', id: nodes[id]!.id })) } +} diff --git a/packages/core/src/commands/structure/mezzanine-content.ts b/packages/core/src/commands/structure/mezzanine-content.ts new file mode 100644 index 0000000000..7e0b9f1e63 --- /dev/null +++ b/packages/core/src/commands/structure/mezzanine-content.ts @@ -0,0 +1,134 @@ +import { getFloorPlacedFootprints } from '../../hooks/spatial-grid/floor-placed-footprints' +import { GROUND_SUPPORT_ID } from '../../hooks/spatial-grid/support-host-id' +import { resolvedFootprintPlane } from '../../lib/floor-foundation-datum' +import { itemOverlapsPolygon } from '../../lib/item-polygon-overlap' +import { area, difference } from '../../lib/polygon-boolean' +import { getRenderableSlabPolygon } from '../../lib/slab-polygon' +import type { ProceduralItemNode } from '../../procedural-items/node' +import { proceduralFootprint } from '../../procedural-items/query' +import { nodeRegistry } from '../../registry' +import type { FloorPlacedFootprint } from '../../registry/types' +import { + type AnyNode, + getScaledDimensions, + type SlabNode, + type WallNode, + type ZoneNode, +} from '../../schema' +import { getStoredLevelHeight } from '../../services/storey' +import { isDerivedNode } from '../../store/derived-node-guard' +import { pointInPolygon } from '../../systems/slab/slab-support' +import { getStairFloorPlacedFootprints } from '../../systems/stair/stair-floor-footprints' +import { roomFace, type StructureNodes } from './shared' + +export type PositionedIntent = AnyNode & { + position: [number, number, number] + rotation: number | [number, number, number] + supportSlabId?: string +} + +export function isFloorPlacedIntent(node: AnyNode): node is PositionedIntent { + if (isDerivedNode(node) || !('position' in node) || !Array.isArray(node.position)) return false + const definition = nodeRegistry.get(node.type) + if (definition) { + const capability = definition.capabilities?.floorPlaced + return !!capability && (!capability.applies || capability.applies(node)) + } + // Headless authorities do not load renderer definitions. + if (node.type === 'item') return !node.asset.attachTo + if (node.type === 'procedural-item') + return !(node as unknown as ProceduralItemNode).recipe.mounting + if (node.type === 'duct-terminal') return node.mount === 'floor' + return [ + 'cabinet', + 'cabinet-module', + 'shelf', + 'stair', + 'column', + 'block', + 'spawn', + 'hvac-equipment', + ].includes(node.type) +} + +export function containedMezzanines(nodes: StructureNodes, host: ZoneNode): ZoneNode[] { + if (host.floor?.support === 'open') return [] + const face = roomFace(nodes, host) + const footprint = { + outer: face?.referencePolygon ?? host.polygon, + holes: face?.holes ?? host.holes, + } + return Object.values(nodes).filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.floor?.support === 'open' && + node.parentId === host.parentId && + area(difference({ outer: node.polygon, holes: node.holes }, footprint)) <= 1e-6, + ) +} + +export function mezzanineElevationConflict(nodes: StructureNodes, zone: ZoneNode) { + const level = zone.parentId ? nodes[zone.parentId] : undefined + const thickness = zone.floor?.thickness ?? 0.2 + const elevation = zone.floor?.elevation + const maximum = + level?.type === 'level' + ? resolvedFootprintPlane(nodes, zone, getStoredLevelHeight(level)) - 0.3 + : 0 + return elevation === undefined || + !Number.isFinite(elevation) || + elevation <= thickness || + elevation > maximum + ? { + code: 'mezzanine-elevation', + nodeIds: [zone.id], + message: `Mezzanine elevation must be greater than thickness (${thickness} m) and at most ${maximum} m.`, + } + : undefined +} + +export function electedIntentPlate( + nodes: StructureNodes, + node: PositionedIntent, +): SlabNode | undefined { + if (node.supportSlabId === GROUND_SUPPORT_ID) return undefined + const capability = nodeRegistry.get(node.type)?.capabilities?.floorPlaced + const rotation: [number, number, number] = Array.isArray(node.rotation) + ? node.rotation + : [0, node.rotation, 0] + const dimensions: [number, number, number] = + node.type === 'item' + ? getScaledDimensions(node) + : [ + 'width' in node && typeof node.width === 'number' ? node.width : 0.6, + 1, + 'depth' in node && typeof node.depth === 'number' ? node.depth : 0.6, + ] + const footprints: FloorPlacedFootprint[] = capability + ? getFloorPlacedFootprints(capability, node, { nodes }) + : node.type === 'stair' + ? getStairFloorPlacedFootprints(node, nodes) + : node.type === 'procedural-item' + ? [proceduralFootprint(node as unknown as ProceduralItemNode)] + : [{ dimensions, rotation }] + const siblings = Object.values(nodes).filter((n) => n.parentId === node.parentId) + const slabs = siblings.filter((n): n is SlabNode => n.type === 'slab') + const walls = siblings.filter((n): n is WallNode => n.type === 'wall') + const supported = slabs.filter((slab) => { + const polygon = getRenderableSlabPolygon(slab, { + walls, + siblingSlabs: slabs.filter((n) => n.id !== slab.id), + }) + return footprints.some((footprint) => { + const position = footprint.position ?? node.position + return ( + itemOverlapsPolygon(position, footprint.dimensions, footprint.rotation, polygon, 0.01) && + !slab.holes.some((hole) => pointInPolygon(position[0], position[2], hole)) + ) + }) + }) + return ( + supported.find((slab) => slab.id === node.supportSlabId) ?? + supported.sort((a, b) => b.elevation - a.elevation)[0] + ) +} diff --git a/packages/core/src/commands/structure/mezzanine-transform.test.ts b/packages/core/src/commands/structure/mezzanine-transform.test.ts new file mode 100644 index 0000000000..e5e9abcb88 --- /dev/null +++ b/packages/core/src/commands/structure/mezzanine-transform.test.ts @@ -0,0 +1,438 @@ +import { afterEach, expect, test } from 'bun:test' +import { mezzanineFixture } from '../../lib/__fixtures__/mezzanine' +import { initSpaceDetectionSync } from '../../lib/space-detection' +import { ItemNode, type SlabNode, StairNode, StairSegmentNode, type ZoneNode } from '../../schema' +import useScene, { clearSceneHistory } from '../../store/use-scene' +import { + applyZoneTransformPlan, + createMezzanine, + duplicateZone, + planMezzanineStair, + rotateZone, + setZoneEdges, + transformZone, +} from './index' + +globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} + +let stop = () => {} +afterEach(() => { + stop() + stop = () => {} +}) +function mount(nodes: ReturnType['nodes']) { + useScene.setState({ + nodes, + rootNodeIds: [], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + useScene.temporal.getState().resume() + clearSceneHistory() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) +} +function furnished() { + const f = mezzanineFixture() + const ground = Object.values(f.nodes).find((n) => n.type === 'slab' && n.support !== 'open')! + const upper = ItemNode.parse({ + id: 'item_upper', + parentId: f.level.id, + position: [2, 0, 2], + supportSlabId: f.plate.id, + asset: { + id: 'chair', + name: 'Chair', + category: 'seating', + thumbnail: '', + src: 'asset://chair', + dimensions: [0.5, 1, 0.5], + }, + }) + const lower = { ...upper, id: 'item_lower' as const, supportSlabId: ground.id } + const ceiling = Object.values(f.nodes).find( + (n) => n.type === 'ceiling' && n.zoneId === f.zone.id, + )! + const light = { ...upper, id: 'item_light' as const, parentId: ceiling.id } + const segment = StairSegmentNode.parse({ id: 'sseg_upper', parentId: 'stair_upper', length: 0.5 }) + const stair = StairNode.parse({ + id: 'stair_upper', + parentId: f.level.id, + position: [2, 0, 1], + supportSlabId: f.plate.id, + children: [segment.id], + }) + return { + ...f, + nodes: { + ...f.nodes, + [upper.id]: upper, + [lower.id]: lower, + [light.id]: light, + [stair.id]: stair, + [segment.id]: segment, + }, + upper, + lower, + light, + stair, + segment, + ceiling, + } +} + +test('mezzanine move carries supported content and derived surfaces, never walls or lower furniture; host then carries it', () => { + const f = furnished() + mount(f.nodes) + const before = useScene.getState().nodes + const plan = transformZone(before, { zoneId: f.zone.id, translate: [1, 1], mintId: f.mintId }) + expect(plan.conflicts).toBeUndefined() + expect(plan.changes.some((c) => c.op === 'create' || c.op === 'delete')).toBe(false) + applyZoneTransformPlan(plan) + const nodes = useScene.getState().nodes + expect(nodes[f.zone.id]).toMatchObject({ hostZoneId: f.host.id }) + expect(nodes[f.plate.id]).toMatchObject({ + polygon: f.zone.polygon.map(([x, z]) => [x + 1, z + 1]), + }) + expect(nodes[f.ceiling.id]).toMatchObject({ polygon: (nodes[f.zone.id] as ZoneNode).polygon }) + expect(nodes[f.upper.id]).toMatchObject({ position: [3, 0, 3], supportSlabId: f.plate.id }) + expect(nodes[f.stair.id]).toMatchObject({ position: [3, 0, 2], supportSlabId: f.plate.id }) + expect(nodes[f.segment.id]).toEqual(f.segment) + expect(nodes[f.light.id]).toMatchObject({ position: [3, 0, 3] }) + expect(nodes[f.lower.id]).toEqual(f.lower) + for (const wall of f.walls) expect(nodes[wall.id]).toEqual(before[wall.id]) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + applyZoneTransformPlan( + transformZone(nodes, { zoneId: f.host.id, translate: [20, 0], mintId: f.mintId }), + ) + expect(useScene.getState().nodes[f.zone.id]).toMatchObject({ + polygon: f.zone.polygon.map(([x, z]) => [x + 21, z + 1]), + hostZoneId: f.host.id, + }) + expect(useScene.getState().nodes[f.upper.id]).toMatchObject({ position: [23, 0, 3] }) +}) + +test('quarter turns use exact mezzanine centroid, carry orientations, and roundtrip', () => { + const f = furnished() + const moved = f.apply( + f.nodes, + transformZone(f.nodes, { zoneId: f.zone.id, translate: [1, 1], mintId: f.mintId }), + ) + const left = rotateZone(moved, { zoneId: f.zone.id, quarterTurns: 1, mintId: f.mintId }) + expect(left.conflicts).toBeUndefined() + const rotated = f.apply(moved, left) + expect(rotated[f.stair.id]).toMatchObject({ rotation: Math.PI / 2 }) + const right = rotateZone(rotated, { zoneId: f.zone.id, quarterTurns: -1, mintId: f.mintId }) + const restored = f.apply(rotated, right)[f.zone.id] as ZoneNode + for (const [i, p] of restored.polygon.entries()) + for (const [j, v] of p.entries()) + expect(v).toBeCloseTo((moved[f.zone.id] as ZoneNode).polygon[i]![j]!) +}) + +test('duplicate searches fitting offsets and rehosts copied items, stairs, segments and ceiling fixtures in one undo', () => { + const f = furnished() + mount(f.nodes) + const plan = duplicateZone(f.nodes, { zoneId: f.zone.id, translate: [100, 0], mintId: f.mintId }) + expect(plan.conflicts).toBeUndefined() + applyZoneTransformPlan(plan) + const nodes = useScene.getState().nodes + const plate = Object.values(nodes).find( + (n) => n.type === 'slab' && n.zoneIds?.includes(plan.zoneId), + )! + expect(nodes[plan.zoneId]).toMatchObject({ hostZoneId: f.host.id }) + expect(nodes[plan.idMap[f.upper.id]![0]!]).toMatchObject({ supportSlabId: plate.id }) + const stair = nodes[plan.idMap[f.stair.id]![0]!]! + expect(stair).toMatchObject({ + supportSlabId: plate.id, + children: [plan.idMap[f.segment.id]![0]!], + }) + expect(StairSegmentNode.safeParse(nodes[plan.idMap[f.segment.id]![0]!]).success).toBe(true) + expect(plan.idMap[f.lower.id]).toBeUndefined() + expect(nodes[f.zone.id]).toEqual(f.zone) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(f.nodes) +}) + +test('edge push grows and shrinks the plate in one undo without wall writes', () => { + const f = mezzanineFixture() + mount(f.nodes) + const plan = setZoneEdges(f.nodes, { zoneId: f.zone.id, edgeIndex: 1, distance: 1 }) + expect(plan.conflicts).toBeUndefined() + applyZoneTransformPlan(plan) + expect((useScene.getState().nodes[f.plate.id] as SlabNode).polygon).toEqual([ + [0.1, 0.1], + [5, 0.1], + [5, 3], + [0.1, 3], + ]) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(f.nodes) + const shrunk = f.apply( + f.nodes, + setZoneEdges(f.nodes, { zoneId: f.zone.id, edgeIndex: 1, distance: -1 }), + ) + expect((shrunk[f.zone.id] as ZoneNode).polygon[1]).toEqual([3, 0.1]) +}) + +test('all mezzanine refusals write nothing, including force, overlapping siblings and no duplicate space', () => { + const f = mezzanineFixture() + const snapshot = structuredClone(f.nodes) + const sibling = createMezzanine(f.nodes, { + hostZoneId: f.host.id, + polygon: [ + [5, 1], + [7, 1], + [7, 4], + [5, 4], + ], + mintId: f.mintId, + }) + const nodes = f.apply(f.nodes, sibling) + const plans = [ + [ + transformZone(f.nodes, { + zoneId: f.zone.id, + translate: [-1, 0], + force: true, + mintId: f.mintId, + }), + 'outside-host', + ], + [rotateZone(f.nodes, { zoneId: f.zone.id, quarterTurns: 1, mintId: f.mintId }), 'outside-host'], + [ + transformZone(nodes, { zoneId: f.zone.id, translate: [3, 1], mintId: f.mintId }), + 'overlaps-mezzanine', + ], + [setZoneEdges(f.nodes, { zoneId: f.zone.id, edgeIndex: 1, distance: -3.8 }), 'too-small'], + [setZoneEdges(f.nodes, { zoneId: f.zone.id, edgeIndex: 1, distance: 10 }), 'outside-host'], + ] as const + for (const [plan, code] of plans) { + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]?.code).toBe(code) + } + expect(f.nodes).toEqual(snapshot) + const full = createMezzanine(f.before, { + hostZoneId: f.host.id, + polygon: [ + [0.1, 0.1], + [7.9, 0.1], + [7.9, 5.9], + [0.1, 5.9], + ], + mintId: f.mintId, + }) + const fullNodes = f.apply(f.before, full) + const refused = duplicateZone(fullNodes, { + zoneId: full.zoneId, + translate: [0, 0], + mintId: f.mintId, + }) + expect(refused.changes).toEqual([]) + expect(refused.conflicts?.[0]?.code).toBe('overlaps-mezzanine') +}) + +test('shared create validation reports crossing edges before area and rejects outside reference boundaries', () => { + const f = mezzanineFixture() + for (const [polygon, code] of [ + [ + [ + [1, 1], + [4, 4], + [1, 4], + [4, 1], + ], + 'self-intersecting', + ], + [ + [ + [-0.1, 0], + [2, 0], + [2, 2], + [-0.1, 2], + ], + 'outside-host', + ], + ] as const) { + const plan = createMezzanine(f.before, { + hostZoneId: f.host.id, + polygon: polygon.map(([x, z]) => [x, z]), + mintId: f.mintId, + }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]?.code).toBe(code) + } +}) + +const railingLength = (plate: SlabNode) => + plate.railing!.reduce( + (sum, { start, end }) => sum + Math.hypot(end[0] - start[0], end[1] - start[1]), + 0, + ) +test('stair planner picks longest free edge, arrives flush, opens railing and applies in one undo step', () => { + const f = mezzanineFixture() + mount(f.nodes) + const plan = planMezzanineStair(f.nodes, f.zone.id) + expect(plan.conflicts).toBeUndefined() + expect(plan.edgeIndex).toBe(1) + applyZoneTransformPlan(plan) + const nodes = useScene.getState().nodes + const stair = nodes[plan.stairId!] as StairNode + const segment = nodes[stair.children[0]!] as StairSegmentNode + expect(stair).toMatchObject({ + parentId: f.level.id, + deckSlabId: f.plate.id, + rotation: -Math.PI / 2, + }) + expect(segment.height).toBeCloseTo(2.45) + expect(stair.position[0] - segment.length).toBeCloseTo(4) + expect(stair.position[2]).toBeCloseTo(1.55) + expect(railingLength(nodes[f.plate.id] as SlabNode)).toBeCloseTo( + railingLength(f.plate) - stair.width, + ) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(f.nodes) +}) + +test('stair planner refuses without writes when walls or item footprints block every run', () => { + const f = furnished() + const blocker = { + ...f.lower, + position: [6, 0, 3] as [number, number, number], + asset: { ...f.lower.asset, dimensions: [4, 1, 6] as [number, number, number] }, + } + const nodes = { ...f.nodes, [blocker.id]: blocker } + const before = structuredClone(nodes) + expect(planMezzanineStair(nodes, f.zone.id)).toMatchObject({ + changes: [], + conflicts: [{ code: 'no-room-for-stair' }], + }) + expect(nodes).toEqual(before) +}) + +test('edge pushes respect clockwise winding and refuse crossing a concave boundary', () => { + const f = mezzanineFixture() + const clockwise = { ...f.zone, polygon: [...f.zone.polygon].reverse() } + const nodes = { ...f.nodes, [clockwise.id]: clockwise } + const plan = setZoneEdges(nodes, { zoneId: clockwise.id, edgeIndex: 1, distance: 1 }) + expect(plan.conflicts).toBeUndefined() + const grown = f.apply(nodes, plan)[clockwise.id] as ZoneNode + expect(grown.polygon[1]![0]).toBe(5) + const concave = createMezzanine(f.before, { + hostZoneId: f.host.id, + polygon: [ + [1, 1], + [4, 1], + [4, 2], + [2, 2], + [2, 4], + [1, 4], + ], + mintId: f.mintId, + }) + const concaveNodes = f.apply(f.before, concave) + mount(concaveNodes) + const invalid = setZoneEdges(concaveNodes, { zoneId: concave.zoneId, edgeIndex: 0, distance: -2 }) + expect(invalid).toMatchObject({ changes: [], conflicts: [{ code: 'self-intersecting' }] }) + applyZoneTransformPlan(invalid) + expect(useScene.getState().nodes).toEqual(concaveNodes) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) +}) + +test('stair planner skips a blocked longer edge for a free edge and sizes the rise from the host floor', () => { + const f = mezzanineFixture() + const host = { ...f.host, floor: { ...f.host.floor, elevation: 0.5 } } + const before = f.reconcile({ ...f.before, [host.id]: host }).nodes + const mezzanine = createMezzanine(before, { + hostZoneId: host.id, + polygon: [ + [1, 1], + [3, 1], + [3, 3], + [1, 3], + ], + elevation: 2, + mintId: f.mintId, + }) + const nodes = f.apply(before, mezzanine) + const sibling = createMezzanine(nodes, { + hostZoneId: host.id, + polygon: [ + [3, 0.1], + [7.9, 0.1], + [7.9, 4], + [3, 4], + ], + mintId: f.mintId, + }) + const blocked = f.apply(nodes, sibling) + const plan = planMezzanineStair(blocked, mezzanine.zoneId) + expect(plan.conflicts).toBeUndefined() + expect(plan.edgeIndex).toBe(2) + const after = f.apply(blocked, plan) + const stair = after[plan.stairId!] as StairNode + const segment = after[stair.children[0]!] as StairSegmentNode + expect(segment.height).toBeCloseTo(1.5) + expect(segment.length).toBeCloseTo(1.8) + expect(stair.position[2] - segment.length).toBeCloseTo(3) + const deck = after[stair.deckSlabId!] as SlabNode + expect(railingLength(deck)).toBeCloseTo(railingLength(blocked[deck.id] as SlabNode) - stair.width) +}) + +function hasNegativeZero(value: unknown): boolean { + if (typeof value === 'number') return Object.is(value, -0) + if (Array.isArray(value)) return value.some(hasNegativeZero) + return !!value && typeof value === 'object' && Object.values(value).some(hasNegativeZero) +} + +test('stair planner canonicalizes atan2 signed zero before committing', () => { + const f = mezzanineFixture() + const mezzanine = createMezzanine(f.before, { + hostZoneId: f.host.id, + polygon: [ + [1, 4], + [7, 4], + [7, 5], + [1, 5], + ], + mintId: f.mintId, + }) + const nodes = f.apply(f.before, mezzanine) + const plan = planMezzanineStair(nodes, mezzanine.zoneId) + expect(plan.conflicts).toBeUndefined() + expect(plan.edgeIndex).toBe(0) + const stair = plan.changes.find((c) => c.op === 'create' && c.node.type === 'stair') + expect(stair).toMatchObject({ node: { rotation: 0 } }) + expect(hasNegativeZero(plan.changes)).toBe(false) + mount(nodes) + applyZoneTransformPlan(plan) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(nodes) +}) + +test('move and duplicate canonicalize signed zero in content poses', () => { + const f = furnished() + const stair = { ...f.stair, rotation: -0, position: [2, -0, 1] as [number, number, number] } + const nodes = { ...f.nodes, [stair.id]: stair } + for (const planner of [transformZone, duplicateZone]) { + const plan = planner(nodes, { + zoneId: f.zone.id, + translate: [1, 0], + rotate: { angle: -0 }, + mintId: f.mintId, + }) + expect(plan.conflicts).toBeUndefined() + expect(hasNegativeZero(plan.changes)).toBe(false) + } +}) diff --git a/packages/core/src/commands/structure/plan-mezzanine-stair.ts b/packages/core/src/commands/structure/plan-mezzanine-stair.ts new file mode 100644 index 0000000000..ffa09ebb6a --- /dev/null +++ b/packages/core/src/commands/structure/plan-mezzanine-stair.ts @@ -0,0 +1,139 @@ +import { planFootprintCorners } from '../../lib/plan-footprint' +import { area, difference, intersection, union } from '../../lib/polygon-boolean' +import { roomFloorPlate } from '../../lib/room-floor-plate' +import { getScaledDimensions, StairNode, StairSegmentNode } from '../../schema' +import { createDefaultStairSegment } from '../../systems/stair/stair-flight' +import { stairFootprintAABB } from '../../systems/stair/stair-footprint' +import { + conflict, + type Point, + requireZone, + type StructureNodes, + type StructurePlan, +} from './shared' +import { mezzanineHostClearance } from './validate-mezzanine' + +export type MezzanineStairPlan = StructurePlan & { stairId?: string; edgeIndex?: number } + +export function planMezzanineStair( + nodes: StructureNodes, + mezzanineZoneId: string, +): MezzanineStairPlan { + const zone = requireZone(nodes, mezzanineZoneId) + const host = nodes[zone.hostZoneId ?? ''] + if (zone.floor?.support !== 'open' || host?.type !== 'zone') + throw Error('Select a mezzanine with a host room.') + const refuse = () => + conflict( + 'no-room-for-stair', + [zone.id], + 'No mezzanine edge has enough free host floor for a straight stair.', + ) + const slabs = Object.values(nodes).filter((node) => node.type === 'slab') + const deck = slabs.find((node) => node.zoneIds?.includes(zone.id)) + const floor = roomFloorPlate(slabs, host.id) + if (!deck || !floor) return refuse() + const defaults = createDefaultStairSegment() + const rise = deck.elevation - floor.elevation + if (!(rise > 0)) return refuse() + const stepCount = Math.max(2, Math.ceil(rise / (defaults.height / defaults.stepCount))) + const run = (stepCount * defaults.length) / defaults.stepCount + const width = defaults.width + const obstacles: Point[][] = [] + for (const node of Object.values(nodes)) { + if (node.parentId !== zone.parentId) continue + if (node.type === 'zone' && node.floor?.support === 'open') obstacles.push(node.polygon) + if (node.type === 'item' && !node.asset.attachTo) + obstacles.push( + planFootprintCorners(node.position, getScaledDimensions(node), node.rotation[1]), + ) + if (node.type === 'stair') { + const box = stairFootprintAABB(node, nodes) + if (box) + obstacles.push([ + [box.minX, box.minZ], + [box.maxX, box.minZ], + [box.maxX, box.maxZ], + [box.minX, box.maxZ], + ]) + } + } + const free = difference(mezzanineHostClearance(nodes, host), union(obstacles)) + const winding = Math.sign( + zone.polygon.reduce((sum, p, i) => { + const q = zone.polygon[(i + 1) % zone.polygon.length]! + return sum + p[0] * q[1] - q[0] * p[1] + }, 0), + ) + const candidates: { edgeIndex: number; arrival: Point; normal: Point; freeRun: number }[] = [] + const extent = Math.hypot( + Math.max(...host.polygon.map(([x]) => x)) - Math.min(...host.polygon.map(([x]) => x)), + Math.max(...host.polygon.map(([, z]) => z)) - Math.min(...host.polygon.map(([, z]) => z)), + ) + for (const [edgeIndex, start] of zone.polygon.entries()) { + const end = zone.polygon[(edgeIndex + 1) % zone.polygon.length]! + const length = Math.hypot(end[0] - start[0], end[1] - start[1]) + if (length < width) continue + const tangent: Point = [(end[0] - start[0]) / length, (end[1] - start[1]) / length] + const normal: Point = [winding * tangent[1], -winding * tangent[0]] + for (const along of [...new Set([length / 2, width / 2, length - width / 2])]) { + const arrival: Point = [start[0] + tangent[0] * along, start[1] + tangent[1] * along] + const footprint = (depth: number): Point[] => + [ + [-width / 2, 0], + [width / 2, 0], + [width / 2, depth], + [-width / 2, depth], + ].map(([x, z]) => [ + arrival[0] + tangent[0] * x! + normal[0] * z!, + arrival[1] + tangent[1] * x! + normal[1] * z!, + ]) + if (area(difference(footprint(run), free)) > 1e-6) continue + let lo = run, + hi = extent + for (let i = 0; i < 16; i++) { + const mid = (lo + hi) / 2 + if (area(difference(footprint(mid), free)) <= 1e-6) lo = mid + else hi = mid + } + // Both ends of the flight must land on the selected host floor. + if (area(difference(footprint(run), { outer: floor.polygon, holes: floor.holes })) > 1e-6) + continue + if (area(intersection(footprint(run), zone.polygon)) > 1e-6) continue + candidates.push({ edgeIndex, arrival, normal, freeRun: lo }) + } + } + const best = candidates.sort((a, b) => b.freeRun - a.freeRun)[0] + if (!best) return refuse() + const stair = StairNode.parse({ + parentId: zone.parentId, + name: 'Mezzanine stair', + fromLevelId: zone.parentId, + supportSlabId: floor.id, + deckSlabId: deck.id, + width, + stepCount, + position: [ + best.arrival[0] + best.normal[0] * run + 0, + 0, + best.arrival[1] + best.normal[1] * run + 0, + ], + rotation: Math.atan2(-best.normal[0], -best.normal[1]) + 0, + }) + const segment = StairSegmentNode.parse({ + ...defaults, + parentId: stair.id, + height: rise, + length: run, + stepCount, + }) + stair.children = [segment.id] + return { + stairId: stair.id, + edgeIndex: best.edgeIndex, + changes: [ + { op: 'create', node: stair }, + { op: 'create', node: segment }, + ], + } +} diff --git a/packages/core/src/commands/structure/plan-wall-deletion.test.ts b/packages/core/src/commands/structure/plan-wall-deletion.test.ts new file mode 100644 index 0000000000..dbae398224 --- /dev/null +++ b/packages/core/src/commands/structure/plan-wall-deletion.test.ts @@ -0,0 +1,297 @@ +import { afterEach, expect, test } from 'bun:test' +import { + initSpaceDetectionSync, + pauseSpaceDetection, + resumeSpaceDetection, +} from '../../lib/space-detection' +import { + BuildingNode, + DoorNode, + ItemNode, + LevelNode, + UnitNode, + WallNode, + type ZoneNode, +} from '../../schema' +import { type SceneCommit, subscribeSceneCommits } from '../../store/history-control' +import useScene, { clearSceneHistory } from '../../store/use-scene' +import { createZone, planWallDeletion, structureChangeBatch } from './index' + +globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} +let stop = () => {} +afterEach(() => { + stop() + useScene.temporal.getState().resume() +}) +const all = () => Object.values(useScene.getState().nodes) +const walls = () => all().filter((n) => n.type === 'wall') +const zones = () => all().filter((n) => n.type === 'zone') +const separators = () => all().filter((n) => n.type === 'separator') +function setup() { + const level = LevelNode.parse({ id: 'level_deletion', parentId: 'building_deletion' }) + const building = BuildingNode.parse({ id: 'building_deletion', children: [level.id] }) + useScene.setState({ + nodes: { [level.id]: level, [building.id]: building }, + rootNodeIds: [building.id], + collections: {}, + materials: {}, + dirtyNodes: new Set(), + readOnly: false, + }) + useScene.temporal.getState().resume() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) + let i = 0 + const plan = createZone(useScene.getState().nodes, { + levelId: level.id, + polygon: [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ], + enclose: true, + name: 'Balcony', + intent: { floor: { finish: 'tile' }, wallMaterial: 'paint' }, + mintId: (kind) => `${kind}_deletion${++i}`, + }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + clearSceneHistory() + return { level, building, zoneId: plan.zoneId as ZoneNode['id'] } +} + +test('exterior wall deletion preserves zone, finishes, plate and ceiling in one commit and undo', () => { + const { zoneId } = setup() + const wall = walls()[0]! + const door = DoorNode.parse({ parentId: wall.id, wallId: wall.id, position: [2, 0, 0] }) + useScene.getState().createNode(door, wall.id) + clearSceneHistory() + const before = useScene.getState().nodes + const surfaces = all().filter((n) => n.type === 'slab' || n.type === 'ceiling') + const commits: SceneCommit[] = [] + const unsubscribe = subscribeSceneCommits((c) => commits.push(c)) + try { + useScene.getState().deleteNode(wall.id) + expect(separators()).toHaveLength(1) + expect(separators()[0]).toMatchObject({ start: wall.start, end: wall.end }) + expect(useScene.getState().nodes[door.id]).toBeUndefined() + expect(zones()).toHaveLength(1) + expect(zones()[0]).toMatchObject({ + id: zoneId, + name: 'Balcony', + enclosureStatus: 'enclosed', + floor: { finish: 'tile' }, + wallMaterial: 'paint', + }) + for (const surface of surfaces) + expect(useScene.getState().nodes[surface.id]?.type).toBe(surface.type) + expect(commits).toHaveLength(1) + expect(commits[0]!.current.nodes[separators()[0]!.id]).toBeDefined() + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + const after = useScene.getState().nodes + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + } finally { + unsubscribe() + } +}) + +test('shared wall deletion merges rooms, retaining largest overlap and unit membership', () => { + const { level, building, zoneId } = setup() + const partition = WallNode.parse({ parentId: level.id, start: [2, 0], end: [2, 4] }) + useScene.getState().createNode(partition, level.id) + expect(zones()).toHaveLength(2) + const smaller = zones().find((n) => n.id !== zoneId)! + const unit = UnitNode.parse({ parentId: building.id, members: [smaller.id] }) + useScene.getState().createNode(unit, building.id) + useScene.getState().deleteNode(partition.id) + expect(separators()).toHaveLength(0) + expect(zones()).toHaveLength(1) + expect(zones()[0]!.id).toBe(zoneId) + expect(useScene.getState().nodes[unit.id]).toMatchObject({ members: [zoneId] }) +}) + +test('free wall deletion creates no separator', () => { + const { level } = setup() + const wall = WallNode.parse({ parentId: level.id, start: [10, 0], end: [12, 0] }) + useScene.getState().createNode(wall, level.id) + useScene.getState().deleteNode(wall.id) + expect(useScene.getState().nodes[wall.id]).toBeUndefined() + expect(separators()).toHaveLength(0) + expect(zones()).toHaveLength(1) +}) + +test('multi-wall deletion preserves each exterior span until every boundary is deleted', () => { + setup() + useScene.getState().deleteNodes( + walls() + .slice(0, 2) + .map((n) => n.id), + ) + expect(separators()).toHaveLength(2) + expect(zones()[0]!.enclosureStatus).toBe('enclosed') + useScene.getState().deleteNodes(walls().map((n) => n.id)) + expect(zones()).toHaveLength(0) + expect(separators()).toHaveLength(0) +}) + +test('deleting all room walls removes zone, finishes, contents and derived surfaces', () => { + const { level, building, zoneId } = setup() + const item = ItemNode.parse({ + parentId: level.id, + position: [2, 0, 2], + asset: { id: 'chair', name: 'Chair', category: 'chairs', src: '/chair.glb', thumbnail: '' }, + }) + const unit = UnitNode.parse({ parentId: building.id, members: [zoneId] }) + useScene.getState().createNodes([ + { node: item, parentId: level.id }, + { node: unit, parentId: building.id }, + ]) + clearSceneHistory() + const before = useScene.getState().nodes + useScene.getState().deleteNodes(walls().map((n) => n.id)) + expect( + all().filter((n) => ['zone', 'slab', 'ceiling', 'separator', 'item'].includes(n.type)), + ).toHaveLength(0) + expect(useScene.getState().nodes[unit.id]).toMatchObject({ members: [] }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) +}) + +test('partial long wall deletion replaces only the derived room span despite stale mirrors', () => { + setup() + const wall = walls().find((n) => n.start[1] === 0 && n.end[1] === 0)! + useScene.getState().updateNode(wall.id, { start: [-4, 0], end: [12, 0] }) + const nodes = { ...useScene.getState().nodes } + for (const zone of zones()) nodes[zone.id] = { ...zone, boundaryWallIds: [] } + const before = JSON.stringify(nodes) + const plan = planWallDeletion(nodes, { nodeIds: [wall.id], mintId: () => 'separator_partial' }) + expect(JSON.stringify(nodes)).toBe(before) + expect(plan.changes.filter((c) => c.op === 'create')).toMatchObject([ + { node: { type: 'separator', start: [0, 0], end: [8, 0] } }, + ]) + useScene.getState().deleteNode(wall.id) + expect(separators()).toHaveLength(1) + expect(zones()[0]!.enclosureStatus).toBe('enclosed') +}) + +test('deleting a level cascades without preserving room boundaries', () => { + const { level } = setup() + useScene.getState().deleteNode(level.id) + expect(all().map((n) => n.type)).toEqual(['building']) +}) + +test('a wall shared on only part of its length merges there and preserves its exterior span', () => { + const { level, zoneId } = setup() + const bottom = walls().find((n) => n.start[1] === 0 && n.end[1] === 0)! + const points: [number, number][] = [ + [0, 0], + [0, -4], + [4, -4], + [4, 0], + ] + useScene.getState().createNodes( + points.slice(0, 3).map((start, i) => ({ + node: WallNode.parse({ parentId: level.id, start, end: points[i + 1] }), + parentId: level.id, + })), + ) + expect(zones()).toHaveLength(2) + useScene.getState().deleteNode(bottom.id) + expect(separators()).toHaveLength(1) + expect(separators()[0]).toMatchObject({ start: [4, 0], end: [8, 0] }) + expect(zones()).toHaveLength(1) + expect(zones()[0]).toMatchObject({ id: zoneId, enclosureStatus: 'enclosed' }) +}) + +test('P4a: deleting every wall of A preserves surviving neighbour B with separators', () => { + const { level } = setup() + const partition = WallNode.parse({ parentId: level.id, start: [2, 0], end: [2, 4] }) + useScene.getState().createNode(partition, level.id) + const a = zones().find((z) => Math.max(...z.polygon.map((p) => p[0])) === 2)! + const b = zones().find((z) => z.id !== a.id)! + useScene.getState().deleteNodes(a.boundaryWallIds) + expect(zones()).toHaveLength(1) + expect(zones()[0]).toMatchObject({ id: b.id, enclosureStatus: 'enclosed' }) + expect(separators().some((s) => s.start[0] === 2 && s.end[0] === 2)).toBe(true) + expect(all().filter((n) => n.type === 'slab')).toHaveLength(1) +}) + +test('P11: cancelling an in-place duplicate leaves no separator beneath its original wall', () => { + const { level } = setup() + const original = walls()[0]! + const duplicate = WallNode.parse({ ...original, id: 'wall_000_duplicate' }) + useScene.getState().createNode(duplicate, level.id) + useScene.getState().deleteNode(duplicate.id) + expect(separators()).toHaveLength(0) + expect(useScene.getState().nodes[original.id]).toBeDefined() + expect(zones()).toHaveLength(1) +}) + +test('P9: cancelling a partition while space detection is paused restores the unsplit room', () => { + const { level, zoneId } = setup() + pauseSpaceDetection() + try { + const partition = WallNode.parse({ parentId: level.id, start: [4, 0], end: [4, 4] }) + useScene.getState().createNode(partition, level.id) + const draft = useScene.getState().nodes + expect( + planWallDeletion(draft, { + nodeIds: [partition.id], + mintId: () => 'separator_stale', + }).changes.filter((c) => c.op === 'create'), + ).toEqual([]) + useScene.getState().deleteNode(partition.id) + } finally { + resumeSpaceDetection() + } + expect(separators()).toHaveLength(0) + expect(zones()).toHaveLength(1) + expect(zones()[0]!.id).toBe(zoneId) +}) + +test('deleting walls one by one retains a separator-only terrace with its floor', () => { + const { zoneId } = setup() + const ids = walls().map((w) => w.id) + for (const id of ids) useScene.getState().deleteNode(id) + expect(walls()).toHaveLength(0) + expect(separators()).toHaveLength(4) + expect(zones()).toHaveLength(1) + expect(zones()[0]).toMatchObject({ id: zoneId, enclosureStatus: 'enclosed' }) + expect(all().filter((n) => n.type === 'slab')).toHaveLength(1) +}) + +test('a wall drawn over an open edge absorbs only the covered separator span', () => { + const { level, zoneId } = setup() + const bottom = walls().find((w) => w.start[1] === 0 && w.end[1] === 0)! + useScene.getState().deleteNode(bottom.id) + const replacement = WallNode.parse({ parentId: level.id, start: [2, 0], end: [6, 0] }) + useScene.getState().createNode(replacement, level.id) + expect( + separators() + .map((s) => [s.start, s.end]) + .sort(), + ).toEqual([ + [ + [0, 0], + [2, 0], + ], + [ + [6, 0], + [8, 0], + ], + ]) + expect(zones()).toHaveLength(1) + expect(zones()[0]!.id).toBe(zoneId) + const before = useScene.getState().nodes + useScene.getState().createNode(WallNode.parse({ ...bottom }), level.id) + expect(separators()).toHaveLength(0) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) +}) diff --git a/packages/core/src/commands/structure/plan-wall-deletion.ts b/packages/core/src/commands/structure/plan-wall-deletion.ts new file mode 100644 index 0000000000..ed633b1ffb --- /dev/null +++ b/packages/core/src/commands/structure/plan-wall-deletion.ts @@ -0,0 +1,187 @@ +import { area, intersection } from '../../lib/polygon-boolean' +import { extractRooms, sampleWallPointsForRoomDetection } from '../../lib/room-graph' +import { type AnyNodeId, SeparatorNode, type WallNode } from '../../schema' +import { omitUndefined } from '../../utils/omit-undefined' +import { planZoneRemoval } from './delete-zone' +import { + at, + boundaries, + project, + roomFace, + type StructureNodes, + type StructurePlan, +} from './shared' + +/** Plans user deletion, including room-preserving boundaries, before reconciliation. */ +export function planWallDeletion( + nodes: StructureNodes, + input: { + nodeIds: readonly string[] + mintId: (kind: 'separator') => string + /** Authored batch state, so replacement walls/separators do not get duplicated. */ + nextNodes?: StructureNodes + }, +): StructurePlan { + const deleted = new Set(input.nodeIds) + const collect = () => { + let changed = true + while (changed) { + changed = false + for (const previous of Object.values(nodes)) { + const node = input.nextNodes?.[previous.id] ?? previous + if (deleted.has(node.id)) { + if ('children' in node && Array.isArray(node.children)) + for (const id of node.children) + if (!deleted.has(id)) { + const child = input.nextNodes?.[id] + if (child && child.parentId !== nodes[id]?.parentId && child.parentId !== node.id) + continue + deleted.add(id) + changed = true + } + } else if ( + (node.parentId && deleted.has(node.parentId)) || + ((node.type === 'door' || node.type === 'window') && + node.wallId && + deleted.has(node.wallId)) + ) { + deleted.add(node.id) + changed = true + } + } + } + } + collect() + const walls = Object.values(nodes).filter( + (n): n is WallNode => n.type === 'wall' && deleted.has(n.id), + ) + const changes: StructurePlan['changes'] = [] + for (const levelId of new Set(walls.map((wall) => wall.parentId))) { + if (!levelId || deleted.has(levelId)) continue + const faces = extractRooms(boundaries(nodes, levelId)) + const rooms = Object.values(nodes).flatMap((zone) => { + if (zone.type !== 'zone' || zone.spaceRole !== 'room' || zone.parentId !== levelId) return [] + const face = roomFace(nodes, zone, faces) + if (!face) return [] + const stored = { outer: zone.polygon, holes: zone.holes } + const current = { outer: face.referencePolygon, holes: face.holes } + const overlap = area(intersection(stored, current)) + if (overlap / Math.max(area([stored]) + area([current]) - overlap, 1e-9) < 0.9) return [] + return [{ zone, spans: face.spans }] + }) + const replacements = boundaries(input.nextNodes ?? nodes, levelId).filter( + (n) => !deleted.has(n.id), + ) + // Topology planners replace walls in their own patches. Only fill uncovered + // portions, using the same sampled reference lines as the room graph. + const uncovered = (start: [number, number], end: [number, number]) => { + let ranges: [number, number][] = [[0, 1]] + for (const boundary of replacements) { + const points = + boundary.type === 'wall' + ? sampleWallPointsForRoomDetection(boundary).map((p): [number, number] => [p.x, p.y]) + : [boundary.start, boundary.end] + for (let i = 1; i < points.length; i++) { + const a = project(points[i - 1]!, start, end), + b = project(points[i]!, start, end) + const onLine = (p: [number, number]) => + Math.abs( + (p[0] - start[0]) * (end[1] - start[1]) - (p[1] - start[1]) * (end[0] - start[0]), + ) < 1e-7 + if (!onLine(points[i - 1]!) || !onLine(points[i]!)) continue + const lo = Math.min(a.t, b.t), + hi = Math.max(a.t, b.t) + ranges = ranges.flatMap(([from, to]) => { + if (hi <= from || lo >= to) return [[from, to]] + return [ + ...(lo > from ? [[from, lo] as [number, number]] : []), + ...(hi < to ? [[hi, to] as [number, number]] : []), + ] + }) + } + } + return ranges + } + for (const { zone, spans } of rooms) { + const wallSpans = spans.filter((s) => s.kind === 'wall') + // Removing the final wall individually leaves a valid separator-only terrace. + if ( + deleted.has(zone.id) || + new Set(wallSpans.map((s) => s.boundaryId)).size < 2 || + !wallSpans.every((s) => deleted.has(s.boundaryId)) + ) + continue + if ( + wallSpans.some((span) => { + const boundary = nodes[span.boundaryId] + if (boundary?.type !== 'wall' && boundary?.type !== 'separator') return false + return ( + uncovered( + at(boundary.start, boundary.end, span.t0), + at(boundary.start, boundary.end, span.t1), + ).reduce((sum, [a, b]) => sum + b - a, 0) < + 1 - 1e-7 + ) + }) + ) + continue + deleted.add(zone.id) + const payload = planZoneRemoval(nodes, { zoneId: zone.id, contents: 'delete' }).payload + for (const id of [...payload.itemIds, ...payload.separatorIds]) deleted.add(id) + } + for (const wall of walls) { + if (wall.parentId !== levelId) continue + const spans = rooms.flatMap(({ zone, spans }) => + spans.filter((s) => s.boundaryId === wall.id).map((s) => ({ ...s, zoneId: zone.id })), + ) + const stations = [...new Set(spans.flatMap((s) => [s.t0, s.t1]))].sort((a, b) => a - b) + const points = sampleWallPointsForRoomDetection(wall) + for (let i = 1; i < stations.length; i++) { + const t0 = stations[i - 1]!, + t1 = stations[i]!, + mid = (t0 + t1) / 2 + const owners = [ + ...new Set( + spans + .filter((s) => !deleted.has(s.zoneId) && s.t0 < mid && s.t1 > mid) + .map((s) => s.zoneId), + ), + ] + if (owners.length !== 1 || deleted.has(owners[0]!)) continue + for (let j = 1; j < points.length; j++) { + const a: [number, number] = [points[j - 1]!.x, points[j - 1]!.y] + const b: [number, number] = [points[j]!.x, points[j]!.y] + const from = project(a, wall.start, wall.end).t, + to = project(b, wall.start, wall.end).t + const lo = Math.max(t0, from), + hi = Math.min(t1, to) + if (hi - lo < 1e-7) continue + const start = at(a, b, (lo - from) / (to - from)), + end = at(a, b, (hi - from) / (to - from)) + for (const [u, v] of uncovered(start, end)) + changes.push({ + op: 'create', + node: omitUndefined( + SeparatorNode.parse({ + id: input.mintId('separator'), + parentId: levelId, + start: at(start, end, u), + end: at(start, end, v), + }), + ), + }) + } + } + } + } + collect() + for (const node of Object.values(input.nextNodes ?? nodes)) + if (node.type === 'unit' && !deleted.has(node.id) && node.members.some((id) => deleted.has(id))) + changes.push({ + op: 'update', + id: node.id, + data: { members: node.members.filter((id) => !deleted.has(id)) }, + }) + changes.push(...[...deleted].map((id) => ({ op: 'delete' as const, id: id as AnyNodeId }))) + return { changes } +} diff --git a/packages/core/src/commands/structure/rebase-floor-reference.ts b/packages/core/src/commands/structure/rebase-floor-reference.ts new file mode 100644 index 0000000000..7dfe5fad01 --- /dev/null +++ b/packages/core/src/commands/structure/rebase-floor-reference.ts @@ -0,0 +1,103 @@ +import { floorPlateAtGroundContact, footprintLift } from '../../lib/floor-foundation-datum' +import { + levelConstructionDisplacements, + upperStoreyFootprints, +} from '../../lib/floor-foundation-stack' +import { roundFloorElevation } from '../../lib/room-floor-feasibility' +import type { SlabNode } from '../../schema' +import { getAuthoredLevelElevations, getLevelElevations } from '../../services/storey' +import type { StructureNodes, StructurePlan } from './shared' + +export function rebaseFloorReference( + nodes: StructureNodes, + input: { slabId?: string; slabIds?: string[]; referenceFloorElevation: number | null }, +): StructurePlan { + if (!!input.slabId === !!input.slabIds?.length) + throw new Error('Supply slabId or a non-empty slabIds array.') + const plates = [...new Set(input.slabIds ?? [input.slabId!])].map((id) => { + const plate = nodes[id] + if (plate?.type !== 'slab' || plate.plateRole !== 'base') + throw new Error(`Base plate not found: ${id}`) + return plate + }) + const reference = input.referenceFloorElevation + if (reference !== null && !Number.isFinite(reference)) + throw new Error('The floor reference must be a finite level-local elevation.') + const nextPlates = plates.map( + (plate): SlabNode => ({ + ...plate, + referenceFloorElevation: reference ?? undefined, + ...(floorPlateAtGroundContact(nodes, plate) && plate.floorHeight === undefined + ? { floorHeight: plate.elevation } + : {}), + }), + ) + let draft: StructureNodes = { + ...nodes, + ...Object.fromEntries(nextPlates.map((plate) => [plate.id, plate])), + } + const supports = upperStoreyFootprints(nodes) + const beforeDisplacement = levelConstructionDisplacements(nodes, supports) + const afterDisplacement = levelConstructionDisplacements(draft, supports) + for (const [levelId, owners] of supports) { + const shifts = owners.map((owner) => { + const nextOwner = draft[owner.id] as SlabNode + return ( + (afterDisplacement.get(owner.parentId!) ?? 0) + + footprintLift(draft, nextOwner) - + (beforeDisplacement.get(owner.parentId!) ?? 0) - + footprintLift(nodes, owner) + ) + }) + if (shifts.some((shift) => Math.abs(shift - shifts[0]!) > 1e-6)) + return { + changes: [], + conflicts: [ + { + code: 'floor-reference-shared-storey', + nodeIds: [levelId, ...owners.map((owner) => owner.id)], + message: + 'This storey spans floor references that would move by different amounts. Rebase the supporting footprints together.', + }, + ], + } + } + const before = getLevelElevations(nodes) + const ordered = [...getAuthoredLevelElevations(nodes)].sort((a, b) => a[1].ordinal - b[1].ordinal) + for (const [levelId] of ordered) { + const level = draft[levelId] + if (level?.type !== 'level') continue + const delta = + (before.get(levelId)?.baseY ?? 0) - (getLevelElevations(draft).get(levelId)?.baseY ?? 0) + if (Math.abs(delta) <= 1e-6) continue + draft = { + ...draft, + [levelId]: { + ...level, + baseElevation: roundFloorElevation((level.baseElevation ?? 0) + delta), + }, + } + } + const changes: StructurePlan['changes'] = [ + ...nextPlates.map((nextPlate, index) => ({ + op: 'update' as const, + id: nextPlate.id, + data: { + referenceFloorElevation: nextPlate.referenceFloorElevation, + ...(nextPlate.floorHeight !== plates[index]!.floorHeight + ? { floorHeight: nextPlate.floorHeight } + : {}), + }, + })), + ...ordered.flatMap(([levelId]) => { + const old = nodes[levelId] + const next = draft[levelId] + return old?.type === 'level' && + next?.type === 'level' && + old.baseElevation !== next.baseElevation + ? [{ op: 'update' as const, id: old.id, data: { baseElevation: next.baseElevation } }] + : [] + }), + ] + return { changes } +} diff --git a/packages/core/src/commands/structure/resize-mezzanine.ts b/packages/core/src/commands/structure/resize-mezzanine.ts new file mode 100644 index 0000000000..c539c92d2c --- /dev/null +++ b/packages/core/src/commands/structure/resize-mezzanine.ts @@ -0,0 +1,61 @@ +import { polygonInteriorPoint } from '../../lib/polygon-label' +import { + conflict, + type Point, + requireZone, + type StructureNodes, + type StructurePlan, +} from './shared' +import { validateMezzanine } from './validate-mezzanine' + +export type MezzanineEdgeInput = { zoneId: string; edgeIndex: number; distance: number } + +export function resizeMezzanine(nodes: StructureNodes, input: MezzanineEdgeInput): StructurePlan { + const zone = requireZone(nodes, input.zoneId) + if (zone.floor?.support !== 'open') + return conflict('invalid-edge', [zone.id], 'Polygon edge pushes require a mezzanine.') + const { edgeIndex, distance } = input + if ( + !Number.isInteger(edgeIndex) || + edgeIndex < 0 || + edgeIndex >= zone.polygon.length || + !Number.isFinite(distance) + ) + return conflict( + 'invalid-edge', + [zone.id], + 'Use a polygon edge index and a finite distance in metres.', + ) + const polygon = zone.polygon.map((p): Point => [...p]) + const nextIndex = (edgeIndex + 1) % polygon.length + const start = polygon[edgeIndex]!, + end = polygon[nextIndex]! + const dx = end[0] - start[0], + dz = end[1] - start[1], + length = Math.hypot(dx, dz) + if (length < 1e-6) return conflict('too-small', [zone.id], 'The edge has no length.') + const winding = Math.sign( + polygon.reduce((sum, p, i) => { + const q = polygon[(i + 1) % polygon.length]! + return sum + p[0] * q[1] - q[0] * p[1] + }, 0), + ) + for (const index of [edgeIndex, nextIndex]) { + const point = polygon[index]! + polygon[index] = [ + point[0] + ((winding * dz) / length) * distance + 0, + point[1] - ((winding * dx) / length) * distance + 0, + ] + } + const invalid = validateMezzanine(nodes, { ...zone, polygon }, zone.id) + if (invalid) return { changes: [], conflicts: [invalid] } + return { + changes: [ + { + op: 'update', + id: zone.id, + data: { polygon, seed: polygonInteriorPoint({ polygon }, true) }, + }, + ], + } +} diff --git a/packages/core/src/commands/structure/rotate-zone.ts b/packages/core/src/commands/structure/rotate-zone.ts new file mode 100644 index 0000000000..ad1439049e --- /dev/null +++ b/packages/core/src/commands/structure/rotate-zone.ts @@ -0,0 +1,35 @@ +import { polygonCentroid } from '../../lib/polygon-label' +import { type Point, requireZone, roomFace, type StructureNodes } from './shared' +import { type TransformZoneInput, transformZone } from './transform-zone' + +export type RotateZoneInput = Pick & { + quarterTurns: 1 | -1 + gridStep?: number +} + +export function rotateZone(nodes: StructureNodes, input: RotateZoneInput) { + const gridStep = input.gridStep ?? 0.5 + if (!(Number.isFinite(gridStep) && gridStep > 0) || ![1, -1].includes(input.quarterTurns)) + throw Error('Use quarterTurns 1 or -1 and a positive finite gridStep.') + const zone = requireZone(nodes, input.zoneId) + if (zone.floor?.support === 'open') + return transformZone(nodes, { ...input, rotate: { angle: (input.quarterTurns * Math.PI) / 2 } }) + const face = roomFace(nodes, zone) + if (!face) return transformZone(nodes, input) + const pivot = polygonCentroid({ outer: face.referencePolygon, holes: face.holes }) + const first = face.referencePolygon[0]! + const rotated: Point = [ + pivot[0] + input.quarterTurns * (first[1] - pivot[1]), + pivot[1] - input.quarterTurns * (first[0] - pivot[0]), + ] + const translate: Point = rotated.map( + (value) => Math.round(value / gridStep) * gridStep - value, + ) as Point + return transformZone(nodes, { + zoneId: input.zoneId, + mintId: input.mintId, + force: input.force, + translate, + rotate: { angle: (input.quarterTurns * Math.PI) / 2, pivot }, + }) +} diff --git a/packages/core/src/commands/structure/set-floor-foundation-height.test.ts b/packages/core/src/commands/structure/set-floor-foundation-height.test.ts new file mode 100644 index 0000000000..ee4bf3d3e9 --- /dev/null +++ b/packages/core/src/commands/structure/set-floor-foundation-height.test.ts @@ -0,0 +1,90 @@ +import { expect, test } from 'bun:test' +import { automaticFloorHeight } from '../../lib/floor-foundation-datum' +import type { AnyNode, SlabNode } from '../../schema' +import { floorStepFixture } from '../../systems/slab/__fixtures__/floor-step' +import { reconcileStructureOnLoad } from '../../utils/reconcile-structure-on-load' +import { DEFAULT_FOUNDATION_MATERIAL, setFloorFoundation } from './set-floor-foundation' + +function scene() { + const f = floorStepFixture() + const nodes = Object.fromEntries( + Object.entries(f.nodes).filter(([, node]) => node.type !== 'slab'), + ) as Record + const loaded = reconcileStructureOnLoad(nodes).nodes as Record + const plate = Object.values(loaded).find( + (n): n is SlabNode => n.type === 'slab' && n.plateRole === 'base', + )! + return { nodes: loaded, plate } +} + +function write(nodes: Record, plan: ReturnType) { + const next = { ...nodes } + for (const change of plan.changes) + if (change.op === 'update') next[change.id] = { ...next[change.id], ...change.data } as AnyNode + return reconcileStructureOnLoad(next).nodes as Record +} + +test('raising a footprint gives it a grey solid foundation; back to the ground removes it', () => { + const { nodes, plate } = scene() + const ground = automaticFloorHeight(nodes, plate) + const raised = setFloorFoundation(nodes, { + slabId: plate.id, + patch: { floorHeight: ground + 0.5 }, + }) + expect(raised.conflicts).toEqual([]) + const up = write(nodes, raised) + expect(up[plate.id]).toMatchObject({ + floorHeight: ground + 0.5, + foundation: { type: 'solid', material: DEFAULT_FOUNDATION_MATERIAL }, + }) + + const lowered = setFloorFoundation(up, { slabId: plate.id, patch: { floorHeight: null } }) + const down = write(up, lowered) + expect((down[plate.id] as SlabNode).floorHeight).toBeUndefined() + expect((down[plate.id] as SlabNode).foundation?.type).toBe('none') +}) + +test('a finish already chosen for the foundation is kept when raising again', () => { + const { nodes, plate } = scene() + const ground = automaticFloorHeight(nodes, plate) + const stone = { ...plate, foundation: { type: 'none' as const, material: 'library:stone' } } + const withStone = { ...nodes, [plate.id]: stone } + const up = write( + withStone, + setFloorFoundation(withStone, { slabId: plate.id, patch: { floorHeight: ground + 0.3 } }), + ) + expect((up[plate.id] as SlabNode).foundation).toEqual({ + type: 'solid', + material: 'library:stone', + }) +}) + +test('an explicit foundation choice with the height wins over the default', () => { + const { nodes, plate } = scene() + const ground = automaticFloorHeight(nodes, plate) + const plan = setFloorFoundation(nodes, { + slabId: plate.id, + patch: { floorHeight: ground + 0.3, foundation: { type: 'solid', material: 'library:brick' } }, + }) + expect(write(nodes, plan)[plate.id]).toMatchObject({ + foundation: { type: 'solid', material: 'library:brick' }, + }) +}) + +test('on the ground uses terrain support rather than an imported floor reference', () => { + const { nodes, plate } = scene() + const ground = automaticFloorHeight(nodes, plate) + const imported = { + ...plate, + elevation: ground + 0.2, + referenceFloorElevation: ground + 0.2, + } + const raised = { ...nodes, [plate.id]: imported } + const plan = setFloorFoundation(raised, { slabId: plate.id, patch: { floorHeight: null } }) + expect(plan.conflicts).toEqual([]) + const lowered = write(raised, plan)[plate.id] as SlabNode + expect(lowered.elevation).toBeCloseTo(ground) + expect(lowered.floorHeight).toBeCloseTo(ground) + expect(lowered.referenceFloorElevation).toBeCloseTo(ground + 0.2) + expect(lowered.foundation?.type).toBe('none') +}) diff --git a/packages/core/src/commands/structure/set-floor-foundation.test.ts b/packages/core/src/commands/structure/set-floor-foundation.test.ts new file mode 100644 index 0000000000..8e5285a84d --- /dev/null +++ b/packages/core/src/commands/structure/set-floor-foundation.test.ts @@ -0,0 +1,197 @@ +import { expect, test } from 'bun:test' +import { getOpeningFloorDatum, wallSupportForNodes } from '../../lib/opening-floor-datum' +import { type AnyNode, BuildingNode, LevelNode, type SlabNode, type ZoneNode } from '../../schema' +import { filterDerivedNodeWrites } from '../../store/derived-node-guard' +import { floorStepFixture } from '../../systems/slab/__fixtures__/floor-step' +import { migrateFloorPlates } from '../../utils/floor-plate-migration' +import { reconcileStructureOnLoad } from '../../utils/reconcile-structure-on-load' +import { FloorFoundationPatch, setFloorFoundation } from './set-floor-foundation' + +function scene() { + const f = floorStepFixture() + const nodes = Object.fromEntries( + Object.entries(f.nodes).filter(([, node]) => node.type !== 'slab'), + ) + for (const node of Object.values({ ...nodes })) { + if (node.type === 'level') continue + const copy = { ...node, id: `${node.id}_shed` } + if (copy.type === 'wall') + Object.assign(copy, { + start: [copy.start[0] + 20, copy.start[1]], + end: [copy.end[0] + 20, copy.end[1]], + }) + if (copy.type === 'zone') + Object.assign(copy, { polygon: copy.polygon.map(([x, z]) => [x + 20, z]) }) + nodes[copy.id] = copy as AnyNode + } + nodes[f.door.id] = f.door + nodes[f.divider.id] = { ...f.divider, children: [f.door.id] } + nodes[f.level.id] = { + ...f.level, + children: Object.values(nodes) + .filter((n) => n.parentId === f.level.id) + .map((n) => n.id) as LevelNode['children'], + } + return { ...f, nodes: reconcileStructureOnLoad(nodes).nodes } +} +const bases = (nodes: Record) => + Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab' && n.plateRole === 'base') + +test('one footprint command moves its walls, opening and explicit room steps; shed stays unchanged', () => { + const s = scene() + const base = bases(s.nodes).find((p) => p.zoneIds?.includes(s.zones[0]!.id))! + const shed = bases(s.nodes).find((p) => p.id !== base.id)! + const plan = setFloorFoundation(s.nodes, { + slabId: base.id, + patch: { + floorHeight: 0.55, + thickness: 0.2, + foundation: { type: 'solid', material: 'library:concrete-raw' }, + }, + }) + expect(plan.conflicts).toEqual([]) + expect(plan.changes.length).toBeGreaterThanOrEqual(3) + const updates = plan.changes.flatMap((c) => (c.op === 'update' ? [c] : [])) + const filtered = filterDerivedNodeWrites(s.nodes, { update: updates }) + expect(filtered.update.map(({ id, data }) => ({ id, data }))).toEqual( + updates.map(({ id, data }) => ({ id, data })), + ) + let nodes = { ...s.nodes } + for (const { id, data } of filtered.update) nodes[id] = { ...nodes[id], ...data } as AnyNode + nodes = reconcileStructureOnLoad(nodes).nodes + expect(nodes[base.id]).toMatchObject({ + elevation: 0.55, + floorHeight: 0.55, + thickness: 0.2, + foundation: { type: 'solid' }, + }) + expect(nodes[shed.id]).toEqual(shed) + expect((nodes[s.zones[1]!.id] as ZoneNode).floor!.elevation).toBeCloseTo(0.1) + expect(wallSupportForNodes(s.divider, nodes).elevation).toBe(0.55) + expect(getOpeningFloorDatum(s.divider, s.door, nodes)).toBe(0.55) + expect(reconcileStructureOnLoad(nodes).nodes).toEqual(nodes) + const reset = setFloorFoundation(nodes, { slabId: base.id, patch: { floorHeight: null } }) + expect(reset.conflicts).toEqual([]) + expect(reset.changes.find((c) => c.op === 'update' && c.id === s.zones[1]!.id)).toMatchObject({ + // Back on the ground the 0.2 slab sits on grade: its top drops 0.35, not to the default 0.05. + data: { floor: { elevation: expect.closeTo(-0.25) } }, + }) +}) + +test.each([ + true, + false, +])('migration replaces level intent and fillToTerrain=%s once, manual slabs unchanged', (fillToTerrain) => { + const s = scene() + const plates = bases(s.nodes) + const input = { + ...s.nodes, + [s.level.id]: { ...s.nodes[s.level.id], floorElevation: 0.35 }, + } as Record + for (const plate of plates) + input[plate.id] = { + ...plate, + foundation: undefined, + fillToTerrain, + slots: { edge: 'library:stone' }, + } + const manual = { + ...plates[0]!, + id: 'slab_manual' as SlabNode['id'], + boundary: undefined, + autoFromWalls: false, + plateRole: undefined, + fillToTerrain, + } + input[manual.id] = manual + const first = migrateFloorPlates(input).nodes as Record + expect(first[s.level.id]).not.toHaveProperty('floorElevation') + for (const plate of plates) { + expect(first[plate.id]).toMatchObject({ + floorHeight: 0.35, + foundation: { type: fillToTerrain ? 'solid' : 'none' }, + }) + expect(first[plate.id]).not.toHaveProperty('fillToTerrain') + if (fillToTerrain) + expect((first[plate.id] as SlabNode).foundation!.material).toBe('library:stone') + } + expect(first[manual.id]).toEqual(manual) + expect(migrateFloorPlates(first).nodes).toEqual(first) +}) + +test('a newly drawn shed gets thin construction without copying the house settings', () => { + const s = scene() + const [house, shed] = bases(s.nodes) + const nodes = { + ...s.nodes, + [house!.id]: { + ...house!, + thickness: 0.3, + floorHeight: 0.4, + foundation: { type: 'solid' as const }, + slots: { edge: 'library:stone' }, + }, + } + delete nodes[shed!.id] + const next = reconcileStructureOnLoad(nodes).nodes + const fresh = bases(next).find((p) => p.id !== house!.id)! + expect(fresh.thickness).toBe(0.05) + expect(fresh.floorHeight).toBeUndefined() + expect(fresh.foundation).toEqual({ type: 'none' }) + expect(fresh.slots?.edge).toBeUndefined() +}) + +test('a plate with actual support accepts height and refuses a solid foundation', () => { + const s = scene() + const base = bases(s.nodes)[0]! + const ground = LevelNode.parse({ id: 'level_ground', level: 0 }) + const building = BuildingNode.parse({ children: [ground.id, s.level.id] }) + const nodes = { + ...s.nodes, + [building.id]: building, + [ground.id]: { ...ground, parentId: building.id }, + [s.level.id]: { ...s.level, level: 1, parentId: building.id }, + zone_ground_room: { ...s.zones[0]!, id: 'zone_ground_room', parentId: ground.id }, + slab_ground_plate: { + ...base, + id: 'slab_ground_plate', + parentId: ground.id, + zoneIds: ['zone_ground_room'], + }, + } + const height = setFloorFoundation(nodes, { slabId: base.id, patch: { floorHeight: 1 } }) + expect(height.conflicts).toEqual([]) + expect( + height.changes.find((change) => change.op === 'update' && change.id === base.id), + ).toMatchObject({ + data: { elevation: 1, thickness: 1, floorHeight: undefined }, + }) + const plan = setFloorFoundation(nodes, { + slabId: base.id, + patch: { floorHeight: 1, foundation: { type: 'solid' } }, + }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]?.code).toBe('floor-foundation-level') + const loaded = reconcileStructureOnLoad({ + ...nodes, + [base.id]: { ...base, floorHeight: 1, foundation: { type: 'solid' } }, + }).nodes + expect(loaded[base.id]).toMatchObject({ + elevation: 1, + thickness: 1, + foundation: { type: 'none' }, + }) + expect((loaded[base.id] as SlabNode).floorHeight).toBeUndefined() +}) + +test('foundation patch only accepts construction side slots', () => { + expect( + FloorFoundationPatch.safeParse({ + slots: { edge: 'library:stone', riser: 'library:stone', underside: 'library:stone' }, + }).success, + ).toBe(true) + for (const key of ['surface', 'foundation', 'anything']) + expect(FloorFoundationPatch.safeParse({ slots: { [key]: 'library:stone' } }).success).toBe( + false, + ) +}) diff --git a/packages/core/src/commands/structure/set-floor-foundation.ts b/packages/core/src/commands/structure/set-floor-foundation.ts new file mode 100644 index 0000000000..d559a2439b --- /dev/null +++ b/packages/core/src/commands/structure/set-floor-foundation.ts @@ -0,0 +1,205 @@ +import { z } from 'zod' +import { + floorPlateHoldsUnderside, + groundFloorConstruction, + supportDerivedFloorHeight, + upperFloorHeightControl, +} from '../../lib/floor-foundation-datum' +import { expandFloorIntentChanges, floorIntentConflicts } from '../../lib/floor-intent-changes' +import { roundFloorElevation } from '../../lib/room-floor-feasibility' +import { SlabNode } from '../../schema' +import { MIN_GROUND_FLOOR_THICKNESS, MIN_SLAB_THICKNESS } from '../../schema/nodes/slab' +import type { StructureNodes, StructurePlan } from './shared' + +export const FloorFoundationPatch = z.strictObject({ + thickness: z + .number() + .finite() + .min(0) + .optional() + .describe( + 'Slab thickness in meters. On the ground it sits on the foundation (or the ground) and grows upward: a thicker slab raises the floor top and everything on it. Never below 0.01 m (smaller values are clamped). Upstairs the underside stays on the walls below.', + ), + foundationHeight: z + .number() + .finite() + .min(0) + .optional() + .describe( + 'Ground-bearing floors only: height of the foundation under the slab, in meters. 0 = on the ground (no foundation); > 0 = raised on a solid foundation. The floor top is derived: grade + foundationHeight + thickness.', + ), + floorHeight: z + .number() + .finite() + .nullable() + .optional() + .describe( + 'Legacy: a target floor top in level-local meters. On the ground it is mapped to foundationHeight = top - grade - thickness (never below 0); null = on the ground. Prefer thickness and foundationHeight.', + ), + foundation: SlabNode.shape.foundation, + slots: z + .strictObject({ + edge: z.string().optional(), + riser: z.string().optional(), + underside: z.string().optional(), + }) + .optional(), +}) +export type FloorFoundationPatch = z.infer + +/** A new solid foundation's finish: mid grey, apart from the white edge band and the walls. */ +export const DEFAULT_FOUNDATION_MATERIAL = 'library:preset-midgrey' + +/** A footprint switched to "Raised on a foundation" without a height starts this high. */ +export const DEFAULT_FOUNDATION_HEIGHT = 0.3 + +/** Foundations this low count as on the ground. */ +const ON_GROUND = 0.0005 + +const touchesGroundConstruction = (patch: FloorFoundationPatch) => + patch.thickness !== undefined || + patch.foundationHeight !== undefined || + Object.hasOwn(patch, 'floorHeight') || + patch.foundation !== undefined + +/** + * A ground-bearing plate's write, bottom up: the foundation stands on the + * grade, the slab on the foundation, so the top is always + * grade + foundationHeight + thickness and nothing floats or sinks. The top is + * written explicitly, so a plate that followed the automatic top keeps its + * underside on the foundation when its thickness changes. + */ +function groundPatch( + nodes: StructureNodes, + plate: SlabNode, + patch: FloorFoundationPatch, +): Partial { + const { floorHeight, foundationHeight: requestedHeight, ...rest } = patch + if (!touchesGroundConstruction(patch)) return rest as Partial + const current = groundFloorConstruction(nodes, plate) + const thickness = roundFloorElevation( + Math.max(MIN_GROUND_FLOOR_THICKNESS, patch.thickness ?? plate.thickness), + ) + const requested = + requestedHeight ?? + (Object.hasOwn(patch, 'floorHeight') + ? floorHeight == null + ? 0 + : floorHeight - current.grade - thickness + : patch.foundation?.type === 'none' + ? 0 + : patch.foundation?.type === 'solid' && current.foundationHeight <= ON_GROUND + ? DEFAULT_FOUNDATION_HEIGHT + : current.foundationHeight) + const foundationHeight = roundFloorElevation(Math.max(0, requested)) + const solid = foundationHeight > ON_GROUND + const foundation = { ...plate.foundation, ...patch.foundation, type: solid ? 'solid' : 'none' } + if (solid && !foundation.material) foundation.material = DEFAULT_FOUNDATION_MATERIAL + return { + ...rest, + thickness, + floorHeight: roundFloorElevation(current.grade + (solid ? foundationHeight : 0) + thickness), + foundation: foundation as SlabNode['foundation'], + } as Partial +} + +export function setFloorFoundation( + nodes: StructureNodes, + input: { + slabId?: string + slabIds?: string[] + patch: FloorFoundationPatch + sameConstruction?: boolean + }, +): StructurePlan { + if (!!input.slabId === !!input.slabIds?.length) + throw new Error('Supply slabId or a non-empty slabIds array.') + const plates = [...new Set(input.slabIds ?? [input.slabId!])].map((id) => { + const plate = nodes[id] + if (plate?.type !== 'slab' || plate.plateRole !== 'base') + throw new Error(`Base plate not found: ${id}`) + return plate + }) + const requested = FloorFoundationPatch.parse(input.patch) + const primary = plates[0]! + const topOf = (plate: SlabNode) => plate.floorHeight ?? plate.elevation + const primarySupported = floorPlateHoldsUnderside(nodes, primary) + if (primarySupported && (requested.foundationHeight ?? 0) > ON_GROUND) + return { + changes: [], + conflicts: [ + { + code: 'floor-foundation-level', + nodeIds: [primary.id], + message: 'Only a plate at ground contact can have a solid foundation.', + }, + ], + } + // How far the primary plate's top moves: every other plate of a group moves by as much. + const delta = primarySupported + ? Object.hasOwn(requested, 'floorHeight') + ? (requested.floorHeight ?? supportDerivedFloorHeight(nodes, primary)) - topOf(primary) + : requested.thickness === undefined + ? undefined + : requested.thickness - primary.thickness + : touchesGroundConstruction(requested) + ? groundPatch(nodes, primary, requested).floorHeight! - topOf(primary) + : undefined + const thin = plates.find( + (plate) => + floorPlateHoldsUnderside(nodes, plate) && + delta !== undefined && + plate.thickness + delta < MIN_SLAB_THICKNESS - 1e-6, + ) + if (thin) + return { + changes: [], + conflicts: [ + { + code: 'floor-plate-thickness', + nodeIds: [thin.id], + message: `The floor plate ${thin.id} cannot move that far: its thickness must remain at least ${MIN_SLAB_THICKNESS} m.`, + }, + ], + } + const { floorHeight: _top, foundationHeight: _foundation, ...upperRequested } = requested + const changes = plates.map((plate, index) => { + const supported = floorPlateHoldsUnderside(nodes, plate) + const own = index === 0 || input.sameConstruction + let data: Partial + if (supported) { + const patch: FloorFoundationPatch = own ? { ...upperRequested } : {} + if (delta !== undefined) + patch.thickness = upperFloorHeightControl( + nodes, + plate, + roundFloorElevation(topOf(plate) + delta), + )!.write.thickness + data = patch as Partial + } else + data = own + ? groundPatch(nodes, plate, requested) + : delta === undefined + ? {} + : groundPatch(nodes, plate, { + foundationHeight: Math.max( + 0, + groundFloorConstruction(nodes, plate).foundationHeight + delta, + ), + }) + return { + id: plate.id, + data: { + ...data, + ...(data.foundation ? { foundation: { ...plate.foundation, ...data.foundation } } : {}), + ...(data.slots ? { slots: { ...plate.slots, ...data.slots } } : {}), + } as Partial, + } + }) + const updates = expandFloorIntentChanges(nodes, changes) + const conflicts = floorIntentConflicts(nodes, updates) + return { + changes: conflicts.length ? [] : updates.map((update) => ({ op: 'update', ...update })), + conflicts, + } +} diff --git a/packages/core/src/commands/structure/set-room-floor-construction.ts b/packages/core/src/commands/structure/set-room-floor-construction.ts new file mode 100644 index 0000000000..469180f3a6 --- /dev/null +++ b/packages/core/src/commands/structure/set-room-floor-construction.ts @@ -0,0 +1,92 @@ +import { roomDrawnFloor } from '../../lib/room-drawn-floor' +import type { SlabNode } from '../../schema' +import { MIN_SLAB_THICKNESS } from '../../schema/nodes/slab' +import { FloorFoundationPatch, setFloorFoundation } from './set-floor-foundation' +import { conflict, requireZone, type StructureNodes, type StructurePlan } from './shared' + +export function setRoomFloorConstruction( + nodes: StructureNodes, + input: { zoneId: string; slabId?: string; patch: typeof FloorFoundationPatch._output }, +): StructurePlan { + const zone = requireZone(nodes, input.zoneId) + // A drawn-slab floor is edited on the slab the room visibly stands on. + const drawn = roomDrawnFloor(nodes, zone.id) + const options = Object.values(nodes).filter( + (node): node is SlabNode => + node.type === 'slab' && + node.parentId === zone.parentId && + (node.id === zone.floor?.sourceSlabId || + node.id === drawn?.slabId || + (node.plateRole === 'base' && (node.zoneIds ?? []).includes(zone.id))), + ) + const selected = input.slabId + ? options.find((plate) => plate.id === input.slabId) + : (options.find((plate) => plate.id === (drawn?.slabId ?? zone.floor?.sourceSlabId)) ?? + (options.length === 1 ? options[0] : undefined)) + if (!selected) + return conflict( + 'room-floor-owner', + [zone.id, ...options.map((plate) => plate.id)], + options.length + ? `This room spans more than one floor construction. Choose slabId from: ${options.map((plate) => plate.id).join(', ')}.` + : 'This room has no associated floor construction.', + ) + const patch = FloorFoundationPatch.parse(input.patch) + if (selected.plateRole === 'base') { + const key = zone.floor?.footprint + if (!key) return setFloorFoundation(nodes, { slabId: selected.id, patch }) + const plates = Object.values(nodes).filter( + (node): node is SlabNode => + node.type === 'slab' && + node.parentId === zone.parentId && + node.plateRole === 'base' && + !!node.zoneIds?.some((id) => { + const room = nodes[id] + return room?.type === 'zone' && room.floor?.footprint === key + }), + ) + return setFloorFoundation(nodes, { + slabIds: [ + selected.id, + ...plates.filter((plate) => plate.id !== selected.id).map((plate) => plate.id), + ], + patch, + sameConstruction: true, + }) + } + if ( + patch.foundation !== undefined || + patch.foundationHeight !== undefined || + patch.floorHeight === null + ) + return conflict( + 'room-authored-floor-construction', + [zone.id, selected.id], + 'An authored slab has no foundation or automatic height to restore. Supply a numeric floorHeight to move its top, or edit thickness and finishes.', + ) + const elevation = patch.floorHeight === undefined ? undefined : patch.floorHeight + return { + changes: [ + { + op: 'update', + id: selected.id, + data: { + ...(elevation === undefined ? {} : { elevation }), + ...(patch.thickness === undefined + ? {} + : { thickness: Math.max(MIN_SLAB_THICKNESS, patch.thickness) }), + ...(patch.slots === undefined ? {} : { slots: { ...selected.slots, ...patch.slots } }), + }, + }, + ...(elevation !== undefined && zone.floor?.elevation !== undefined + ? [ + { + op: 'update' as const, + id: zone.id, + data: { floor: { ...zone.floor, elevation } }, + }, + ] + : []), + ], + } +} diff --git a/packages/core/src/commands/structure/set-wall-geometry.ts b/packages/core/src/commands/structure/set-wall-geometry.ts new file mode 100644 index 0000000000..2a66fa49bd --- /dev/null +++ b/packages/core/src/commands/structure/set-wall-geometry.ts @@ -0,0 +1,85 @@ +import { type AnyNodeId, WallNode } from '../../schema' +import { planWallJustification } from '../../systems/wall/wall-frame' +import { getPlannedLinkedWallUpdates, planWallMoveJunctions } from '../../systems/wall/wall-move' +import { + applyToScratch, + conflict, + diffStructure, + type Point, + type StructureMintId, + type StructureNodes, + type StructurePlan, +} from './shared' + +export function setWallGeometry( + nodes: StructureNodes, + input: { + wallId: string + start?: Point + end?: Point + thickness?: number + justification?: 'a' | 'b' | null + mintId: StructureMintId + }, +): StructurePlan { + const original = nodes[input.wallId] + if (original?.type !== 'wall') throw Error('Select a wall.') + let scratch = { ...nodes } + if (input.justification !== undefined) + scratch = applyToScratch(scratch, { + create: [], + delete: [], + update: planWallJustification(nodes, original.id, input.justification ?? undefined), + }) + const wall = scratch[original.id] as WallNode + const start = input.start ?? wall.start, + end = input.end ?? wall.end + const next = WallNode.parse({ + ...wall, + start, + end, + ...(input.thickness !== undefined ? { thickness: input.thickness } : {}), + }) + if ( + !( + [...start, ...end].every(Number.isFinite) && + Math.hypot(end[0] - start[0], end[1] - start[1]) >= 0.05 && + (next.thickness ?? 0.1) > 0 + ) + ) + throw Error('Invalid wall geometry.') + if (input.start || input.end) { + const linked = Object.values(scratch).filter( + (n): n is WallNode => n.type === 'wall' && n.parentId === wall.parentId && n.id !== wall.id, + ) + const plan = planWallMoveJunctions(linked, wall.start, wall.end, start, end) + const consumed = plan.wallsToDelete.map((n) => n.id) + const hosted = Object.values(scratch).filter((n) => + consumed.includes(n.parentId as WallNode['id']), + ) + if (hosted.length) + return conflict( + 'hosted-openings', + hosted.map((n) => n.id), + 'Moving this junction would remove a wall with hosted objects.', + ) + scratch = applyToScratch(scratch, { + update: getPlannedLinkedWallUpdates(plan, wall.start, wall.end, start, end).map( + ({ id, ...data }) => ({ id, data }), + ), + delete: consumed, + create: plan.bridgePlans.map((bridge) => ({ + node: WallNode.parse({ + ...bridge.wall, + id: input.mintId('wall'), + children: [], + start: bridge.originalPoint, + end: bridge.movedEndpoint === 'start' ? start : end, + }), + parentId: wall.parentId as AnyNodeId, + })), + }) + } + scratch[wall.id] = next + return { changes: diffStructure(nodes, scratch) } +} diff --git a/packages/core/src/commands/structure/set-zone-edges.ts b/packages/core/src/commands/structure/set-zone-edges.ts new file mode 100644 index 0000000000..6f1642e11b --- /dev/null +++ b/packages/core/src/commands/structure/set-zone-edges.ts @@ -0,0 +1,196 @@ +import { sampleWallPointsForRoomDetection } from '../../lib/room-graph' +import { type AnyNodeId, SeparatorNode, type WallNode } from '../../schema' +import { getWallCurveLength } from '../../systems/wall/wall-curve' +import { planWallDivision } from '../../systems/wall/wall-operations' +import { planWallInsertion } from '../../systems/wall/wall-topology' +import { type MezzanineEdgeInput, resizeMezzanine } from './resize-mezzanine' +import { + applyToScratch, + at, + conflict, + diffStructure, + requireZone, + roomFace, + type SpanRef, + type StructureMintId, + type StructureNodes, + type StructurePlan, + sharedSpan, +} from './shared' + +export function setZoneEdges( + nodes: StructureNodes, + input: + | MezzanineEdgeInput + | { + zoneId: string + edges: Array<{ + spanRef: SpanRef + kind: 'wall' | 'separator' + wall?: Pick, 'thickness' | 'height' | 'justification'> + }> + dropOpenings?: boolean + mintId: StructureMintId + }, +): StructurePlan { + if ('edgeIndex' in input) return resizeMezzanine(nodes, input) + const zone = requireZone(nodes, input.zoneId) + if (zone.floor?.support === 'open') + return conflict( + 'invalid-edge', + [zone.id], + 'Use edgeIndex and distance to push a mezzanine edge.', + ) + const face = roomFace(nodes, zone) + let scratch = { ...nodes } + const edges = [...input.edges].sort( + (a, b) => + a.spanRef.boundaryId.localeCompare(b.spanRef.boundaryId) || b.spanRef.t0 - a.spanRef.t0, + ) + for (let i = 1; i < edges.length; i++) { + const left = edges[i - 1]!.spanRef, + right = edges[i]!.spanRef + if (left.boundaryId === right.boundaryId && right.t1 > left.t0 + 1e-6) + return conflict('overlapping-spans', [left.boundaryId], 'Boundary edits must not overlap.') + } + for (const edge of edges) { + const span = edge.spanRef + if ( + !face?.spans.some( + (s) => + s.boundaryId === span.boundaryId && + s.face === span.face && + span.t0 >= s.t0 - 1e-6 && + span.t1 <= s.t1 + 1e-6 && + span.t1 > span.t0, + ) + ) + return conflict('invalid-span', [span.boundaryId], 'The span is not on this room boundary.') + const boundary = scratch[span.boundaryId] + if (boundary?.type !== 'wall' && boundary?.type !== 'separator') + return conflict('stale-span', [span.boundaryId], 'Replan against the current boundary.') + if (boundary.type === edge.kind) continue + const original = nodes[span.boundaryId] + if (original?.type !== 'wall' && original?.type !== 'separator') + throw Error('Missing boundary.') + const originalLength = + original.type === 'wall' + ? getWallCurveLength(original) + : Math.hypot(original.end[0] - original.start[0], original.end[1] - original.start[1]) + const currentLength = + boundary.type === 'wall' + ? getWallCurveLength(boundary) + : Math.hypot(boundary.end[0] - boundary.start[0], boundary.end[1] - boundary.start[1]) + const t0 = (span.t0 * originalLength) / currentLength, + t1 = (span.t1 * originalLength) / currentLength + if (boundary.type === 'separator') { + const start = at(boundary.start, boundary.end, t0), + end = at(boundary.start, boundary.end, t1) + const inserted = planWallInsertion(scratch, { + levelId: zone.parentId as AnyNodeId, + start, + end, + joinRadius: 0.001, + wallDefaults: edge.wall, + mintId: () => input.mintId('wall'), + }) + if (!inserted.ok) + return conflict( + inserted.reason, + [boundary.id], + 'Cannot replace this separator with a wall.', + ) + scratch = applyToScratch(scratch, inserted.plan.changes) + delete scratch[boundary.id] + for (const [from, to] of [ + [0, t0], + [t1, 1], + ]) + if (to! - from! > 1e-6) { + const remainder = SeparatorNode.parse({ + ...boundary, + id: from === 0 ? boundary.id : input.mintId('separator'), + start: at(boundary.start, boundary.end, from!), + end: at(boundary.start, boundary.end, to!), + }) + scratch[remainder.id] = remainder + } + } else { + if (sharedSpan(nodes, zone, span)) continue + const length = getWallCurveLength(boundary) + const attachments = Object.values(scratch).filter( + (n) => n.parentId === boundary.id || ('wallId' in n && n.wallId === boundary.id), + ) + const removed = attachments.filter( + (n) => + 'position' in n && + Array.isArray(n.position) && + n.position[0] + + ('width' in n && typeof n.width === 'number' + ? n.width / 2 + : n.type === 'item' + ? (n.asset.dimensions[0] * n.scale[0]) / 2 + : 0) >= + t0 * length && + n.position[0] - + ('width' in n && typeof n.width === 'number' + ? n.width / 2 + : n.type === 'item' + ? (n.asset.dimensions[0] * n.scale[0]) / 2 + : 0) <= + t1 * length, + ) + if (removed.length && !input.dropOpenings) + return conflict( + 'hosted-openings', + removed.map((n) => n.id), + 'Removing this wall also removes its hosted openings and objects. Pass dropOpenings to confirm.', + ) + const removedIds = new Set(removed.map((n) => n.id)) + let found = true + while (found) { + found = false + for (const n of Object.values(scratch)) + if (n.parentId && removedIds.has(n.parentId) && !removedIds.has(n.id)) { + removedIds.add(n.id) + found = true + } + } + for (const id of removedIds) delete scratch[id] + scratch[boundary.id] = { + ...boundary, + children: boundary.children.filter((id) => !removed.some((n) => n.id === id)), + } + let targetId = boundary.id + try { + for (const t of [t1, t0]) + if (t > 1e-6 && t < 1 - 1e-6) { + const division = planWallDivision(scratch, boundary.id, t * length, () => + input.mintId('wall'), + ) + scratch = applyToScratch(scratch, division.changes) + if (t === t0) targetId = division.changes.create[0]!.node.id as WallNode['id'] + } + } catch (error) { + return conflict('occupied-split', [boundary.id], String(error)) + } + const target = scratch[targetId] + if (target?.type !== 'wall') + return conflict('invalid-span', [boundary.id], 'Could not isolate the wall span.') + delete scratch[target.id] + const points = sampleWallPointsForRoomDetection(target) + for (let i = 1; i < points.length; i++) { + const start = points[i - 1]!, + end = points[i]! + const separator = SeparatorNode.parse({ + id: input.mintId('separator'), + parentId: zone.parentId, + start: [start.x, start.y], + end: [end.x, end.y], + }) + scratch[separator.id] = separator + } + } + } + return { changes: diffStructure(nodes, scratch) } +} diff --git a/packages/core/src/commands/structure/set-zone-intent.ts b/packages/core/src/commands/structure/set-zone-intent.ts new file mode 100644 index 0000000000..141b9ba43a --- /dev/null +++ b/packages/core/src/commands/structure/set-zone-intent.ts @@ -0,0 +1,129 @@ +import { z } from 'zod' +import { floorIntentConflicts } from '../../lib/floor-intent-changes' +import { ownFloorIntentChanges } from '../../lib/own-floor-intent' +import { drawnFloorElevationConflict } from '../../lib/room-drawn-floor' +import { roundFloorElevation } from '../../lib/room-floor-feasibility' +import { ZoneNode } from '../../schema' +import { mezzanineElevationConflict } from './mezzanine-content' +import { requireZone, type StructureNodes, type StructurePlan } from './shared' + +const floor = ZoneNode.shape.floor.unwrap() +const ceiling = ZoneNode.shape.ceiling.unwrap() +export const ZoneIntentPatch = z.strictObject({ + name: z.string().nullable().optional(), + floor: z + .strictObject({ + footprint: floor.shape.footprint.unwrap().nullable().optional(), + thickness: floor.shape.thickness.unwrap().nullable().optional(), + elevation: floor.shape.elevation.unwrap().nullable().optional(), + finish: floor.shape.finish.unwrap().nullable().optional(), + regions: floor.shape.regions.unwrap().nullable().optional(), + }) + .nullable() + .optional(), + ceiling: z + .strictObject({ + regions: ceiling.shape.regions.unwrap().nullable().optional(), + }) + .nullable() + .optional(), + floorStepFinish: z.string().nullable().optional(), + floorStepOverrides: ZoneNode.shape.floorStepOverrides.unwrap().nullable().optional(), + floorEdgeFinish: z.string().nullable().optional(), + wallMaterial: z.string().nullable().optional(), + hasFloor: z.boolean().nullable().optional(), + hasCeiling: z.boolean().nullable().optional(), +}) +export type ZoneIntentPatch = z.infer + +export function setZoneIntent( + nodes: StructureNodes, + input: { zoneId: string; patch: ZoneIntentPatch }, +): StructurePlan { + const zone = requireZone(nodes, input.zoneId) + const patch = ZoneIntentPatch.parse(input.patch) + const requestedKey = patch.floor?.footprint + if ( + requestedKey && + requestedKey !== 'new' && + requestedKey !== zone.floor?.footprint && + !Object.values(nodes).some( + (node) => + node.type === 'zone' && + node.parentId === zone.parentId && + node.floor?.footprint === requestedKey, + ) + ) + return { + changes: [], + conflicts: [ + { + code: 'room-floor-footprint', + nodeIds: [zone.id], + message: 'Choose an existing floor key on this level, or "new".', + }, + ], + } + const data: Partial = {} + for (const key of ['floorStepFinish', 'floorEdgeFinish'] as const) + if (patch[key] !== undefined) data[key] = patch[key] ?? undefined + if (patch.floorStepOverrides !== undefined) + data.floorStepOverrides = patch.floorStepOverrides?.length + ? patch.floorStepOverrides + : undefined + if (patch.name !== undefined) data.name = patch.name ?? '' + if (patch.wallMaterial !== undefined) data.wallMaterial = patch.wallMaterial ?? undefined + for (const key of ['hasFloor', 'hasCeiling'] as const) + if (patch[key] !== undefined) data[key] = patch[key] === false ? false : undefined + if (patch.floor !== undefined) { + data.floor = patch.floor === null ? undefined : { ...zone.floor } + if (patch.floor) + for (const key of ['elevation', 'finish', 'regions', 'thickness', 'footprint'] as const) { + const value = patch.floor[key] + if (value === null) delete data.floor![key] + else if (value !== undefined) + Object.assign(data.floor!, { + [key]: + key === 'elevation' && typeof value === 'number' ? roundFloorElevation(value) : value, + }) + } + } + if (patch.ceiling !== undefined) { + const regions = patch.ceiling === null ? null : patch.ceiling.regions + if (regions === null) data.ceiling = undefined + else if (regions !== undefined) data.ceiling = { ...zone.ceiling, regions } + } + if (zone.floor?.support === 'open') { + if (patch.floor === null || patch.floor?.elevation === null) + return { + changes: [], + conflicts: [ + { + code: 'mezzanine-intent', + nodeIds: [zone.id], + message: 'A mezzanine must retain its open support and explicit elevation.', + }, + ], + } + const invalid = mezzanineElevationConflict(nodes, { ...zone, ...data }) + if (invalid) return { changes: [], conflicts: [invalid] } + } + // A drawn-slab floor keeps its height on the slab; a room height would move nothing. + if (typeof data.floor?.elevation === 'number' && data.floor.elevation !== zone.floor?.elevation) { + const drawn = drawnFloorElevationConflict(nodes, zone.id) + if (drawn) return { changes: [], conflicts: [drawn] } + } + if ( + zone.floor?.support !== 'open' && + (patch.floor === null || patch.floor?.elevation !== undefined) + ) { + const conflicts = floorIntentConflicts(nodes, [{ id: zone.id, data }]) + if (conflicts.length) return { changes: [], conflicts } + } + ZoneNode.parse({ ...zone, ...data }) + const own = ownFloorIntentChanges(nodes, Object.keys(data).length ? [{ id: zone.id, data }] : []) + return { + changes: own.updates.map((update) => ({ op: 'update', ...update })), + ...(own.conflicts.length ? { conflicts: own.conflicts } : {}), + } +} diff --git a/packages/core/src/commands/structure/shared.ts b/packages/core/src/commands/structure/shared.ts new file mode 100644 index 0000000000..96e7498295 --- /dev/null +++ b/packages/core/src/commands/structure/shared.ts @@ -0,0 +1,157 @@ +import { roomPolygonKey } from '../../lib/floor-room-faces' +import { area, containsPoint, intersection } from '../../lib/polygon-boolean' +import { extractRooms } from '../../lib/room-graph' +import type { BoundaryNode, BoundarySpan } from '../../lib/room-topology-index' +import type { NodePatch, SceneNodes } from '../../lib/structure-kernel' +import type { AnyNode, AnyNodeId, ZoneNode } from '../../schema' +import type { WallTopologyChanges } from '../../systems/wall/wall-topology' +import { omitUndefined } from '../../utils/omit-undefined' + +export type NodeChange = NodePatch +export type StructureNodes = SceneNodes +export type StructureMintId = (kind: 'zone' | 'wall' | 'separator') => string +export type StructureConflict = { code: string; nodeIds: string[]; message: string } +export type StructurePlan = { + changes: NodeChange[] + conflicts?: StructureConflict[] + idMap?: Record +} +export type Point = [number, number] +export type SpanRef = Pick + +export function structureChangeBatch(changes: readonly NodeChange[]): WallTopologyChanges { + return { + create: changes.flatMap((c) => + c.op === 'create' ? [{ node: c.node, parentId: c.node.parentId as AnyNodeId }] : [], + ), + update: changes.flatMap((c) => (c.op === 'update' ? [{ id: c.id, data: c.data }] : [])), + delete: changes.flatMap((c) => (c.op === 'delete' ? [c.id] : [])), + } +} + +export function applyToScratch(nodes: StructureNodes, batch: WallTopologyChanges) { + const next: Record = { ...nodes } + for (const id of batch.delete) delete next[id] + for (const { node, parentId } of batch.create) + next[node.id] = { ...node, parentId: parentId ?? node.parentId } as AnyNode + for (const { id, data } of batch.update) + if (next[id]) next[id] = { ...next[id], ...data } as AnyNode + return next +} + +export function diffStructure(before: StructureNodes, after: StructureNodes): NodeChange[] { + return [ + ...Object.values(after) + .filter((node) => !before[node.id]) + .map((node): NodeChange => ({ op: 'create', node: omitUndefined(node) })), + ...Object.values(after) + .filter((node) => before[node.id] && node !== before[node.id]) + .flatMap((node): NodeChange[] => { + const previous = before[node.id]! + const data = Object.fromEntries( + [...new Set([...Object.keys(previous), ...Object.keys(node)])] + .filter( + (key) => + JSON.stringify(previous[key as keyof typeof previous]) !== + JSON.stringify(node[key as keyof typeof node]), + ) + .map((key) => [key, omitUndefined(node[key as keyof typeof node])]), + ) as Partial + return Object.keys(data).length ? [{ op: 'update', id: node.id, data }] : [] + }), + ...Object.values(before) + .filter((node) => !after[node.id]) + .map((node): NodeChange => ({ op: 'delete', id: node.id })), + ] +} + +export function conflict(code: string, nodeIds: string[], message: string): StructurePlan { + return { changes: [], conflicts: [{ code, nodeIds, message }] } +} + +export function requireZone(nodes: StructureNodes, id: string): ZoneNode { + const zone = nodes[id] + if (zone?.type !== 'zone' || zone.spaceRole !== 'room') throw Error(`Room not found: ${id}`) + return zone +} + +export function boundaries(nodes: StructureNodes, levelId: string): BoundaryNode[] { + return Object.values(nodes).filter( + (n): n is BoundaryNode => + n.parentId === levelId && (n.type === 'wall' || n.type === 'separator'), + ) +} + +const faceMatches = new WeakMap< + object, + Map[number] | undefined> +>() + +export function roomFace( + nodes: StructureNodes, + zone: ZoneNode, + faces = extractRooms(boundaries(nodes, zone.parentId!)), +) { + if (zone.floor?.support === 'open') return undefined + let matches = faceMatches.get(faces) + if (!matches) { + matches = new Map() + faceMatches.set(faces, matches) + } + const key = roomPolygonKey(zone.polygon, zone.holes) + if (matches.has(key)) return matches.get(key) + const exact = faces.find((face) => roomPolygonKey(face.referencePolygon, face.holes) === key) + if (exact) { + matches.set(key, exact) + return exact + } + const scored = faces.map((face) => ({ + face, + overlap: area( + intersection( + { outer: zone.polygon, holes: zone.holes }, + { outer: face.referencePolygon, holes: face.holes }, + ), + ), + })) + const result = scored.sort((a, b) => b.overlap - a.overlap)[0]?.overlap + ? scored[0]!.face + : undefined + matches.set(key, result) + return result +} + +export function sharedSpan(nodes: StructureNodes, zone: ZoneNode, span: SpanRef) { + return Object.values(nodes).some( + (other) => + other.type === 'zone' && + other.id !== zone.id && + other.parentId === zone.parentId && + other.spaceRole === 'room' && + roomFace(nodes, other)?.spans.some( + (s) => + s.boundaryId === span.boundaryId && + s.face !== span.face && + Math.min(s.t1, span.t1) - Math.max(s.t0, span.t0) > 1e-6, + ), + ) +} + +export function at(start: Point, end: Point, t: number): Point { + return [start[0] + (end[0] - start[0]) * t, start[1] + (end[1] - start[1]) * t] +} + +export function project(point: Point, start: Point, end: Point) { + const dx = end[0] - start[0], + dz = end[1] - start[1] + const t = Math.max( + 0, + Math.min(1, ((point[0] - start[0]) * dx + (point[1] - start[1]) * dz) / (dx * dx + dz * dz)), + ) + const result = at(start, end, t) + return { point: result, t, distance: Math.hypot(result[0] - point[0], result[1] - point[1]) } +} + +export function pointInRoom(zone: ZoneNode, point: Point) { + return containsPoint([{ outer: zone.polygon, holes: zone.holes }], point) +} diff --git a/packages/core/src/commands/structure/structure-audit.test.ts b/packages/core/src/commands/structure/structure-audit.test.ts new file mode 100644 index 0000000000..d7bac1ac6a --- /dev/null +++ b/packages/core/src/commands/structure/structure-audit.test.ts @@ -0,0 +1,205 @@ +import { describe, expect, test } from 'bun:test' +import { reconcileLevelStructure } from '../../lib/structure-kernel' +import { ItemNode, SeparatorNode, WallNode } from '../../schema' +import { planZoneRemoval } from './delete-zone' +import { createZone, deleteZone, divideZone, setZoneIntent, snapZoneBoundary } from './index' +import { applyToScratch, diffStructure, structureChangeBatch } from './shared' +import { apply, enclosed, fixture, mint } from './structure.test' + +function row() { + const nodes: Record = fixture() + let i = 0 + const wall = (start: number[], end: number[]) => { + const node = WallNode.parse({ id: `wall_row${++i}`, parentId: 'level_test', start, end }) + nodes[node.id] = node + } + for (const x of [0, 2, 4]) { + wall([x, 0], [x + 2, 0]) + wall([x, 4], [x + 2, 4]) + } + wall([0, 0], [0, 4]) + wall([6, 0], [6, 4]) + for (const x of [2, 4]) { + const separator = SeparatorNode.parse({ + id: `separator_row${x}`, + parentId: 'level_test', + start: [x, 0], + end: [x, 4], + }) + nodes[separator.id] = separator + } + const result = reconcileLevelStructure({ + levelId: 'level_test', + nodes, + mintId: (kind) => `${kind}_row${++i}`, + }) + return applyToScratch(nodes, structureChangeBatch(result.patches)) +} + +describe('structure audit regressions', () => { + test('deleting the middle of three rooms merges it into one neighbour; both neighbours stay', () => { + const nodes = row() + const zones = Object.values(nodes) + .filter((n) => n.type === 'zone') + .sort((a, b) => a.seed![0] - b.seed![0]) + const middle = zones[1]! + const plan = deleteZone(nodes, { zoneId: middle.id, contents: 'delete' }) + expect(plan.payload).toMatchObject({ mode: 'merge', wallIds: [], opensZoneIds: [] }) + expect(plan.payload.separatorIds).toHaveLength(1) + const after = apply(nodes, plan) + expect(after[middle.id]).toBeUndefined() + for (const zone of [zones[0]!, zones[2]!]) { + expect(after[zone.id]).toBeDefined() + expect( + Object.values(after).find((n) => n.type === 'ceiling' && n.zoneId === zone.id), + ).toBeDefined() + } + expect(Object.values(after).filter((n) => n.type === 'zone')).toHaveLength(2) + }) + test('shared-wall protection uses geometry even when mirrors are empty', () => { + const { nodes, zoneId } = enclosed() + const divider = WallNode.parse({ + id: 'wall_shared_audit', + parentId: 'level_test', + start: [2, 0], + end: [2, 4], + }) + let graph = apply(nodes, { changes: [{ op: 'create', node: divider }] }) + graph = Object.fromEntries( + Object.entries(graph).map(([id, n]) => [ + id, + n.type === 'zone' ? { ...n, boundaryWallIds: [] } : n, + ]), + ) + const plan = deleteZone(graph, { zoneId, contents: 'delete' }) + expect(plan.payload.keptSharedWallIds).toContain(divider.id) + expect(plan.changes).not.toContainEqual({ op: 'delete', id: divider.id }) + }) + test('room removal reports other faces it opens while shared separators stay', () => { + const { nodes, zoneId } = enclosed() + const graph = apply( + nodes, + divideZone(nodes, { + zoneId, + cut: [ + [2, 0], + [2, 4], + ], + mintId: mint(), + }), + ) + const other = Object.values(graph).find((n) => n.type === 'zone' && n.id !== zoneId)! + // Wall deletion takes a split half down this way; deleting the room itself merges it. + const plan = planZoneRemoval(graph, { zoneId, contents: 'delete' }) + expect(plan.payload.opensZoneIds).toEqual([other.id]) + expect(plan.payload.separatorIds).toEqual([]) + expect(plan.payload.keptSharedSeparatorIds).toHaveLength(1) + }) + for (const contents of ['keep', 'delete'] as const) + test(`fully shared enclosure is refused (${contents} contents), nothing changes`, () => { + const { nodes, zoneId } = enclosed() + let nextId = 0 + const points: [number, number][] = [ + [-2, -2], + [10, -2], + [10, 6], + [-2, 6], + ] + let graph = apply(nodes, { + changes: points.map((start, i) => ({ + op: 'create', + node: WallNode.parse({ + id: `wall_outer${++nextId}`, + parentId: 'level_test', + start, + end: points[(i + 1) % 4], + }), + })), + }) + expect(Object.values(graph).filter((n) => n.type === 'zone')).toHaveLength(2) + graph = apply( + graph, + setZoneIntent(graph, { + zoneId, + patch: { + name: 'Custom', + floor: { elevation: 0.4, finish: 'wood' }, + wallMaterial: 'paint', + hasFloor: false, + hasCeiling: false, + }, + }), + ) + const item = ItemNode.parse({ + id: 'item_reset', + parentId: 'level_test', + position: [2, 0, 2], + asset: { + id: 'chair', + category: 'chairs', + name: 'Chair', + thumbnail: '', + src: 'https://example.com/chair.glb', + }, + }) + graph = { ...graph, [item.id]: item } + const plan = deleteZone(graph, { zoneId, contents }) + expect(plan.payload).toMatchObject({ + mode: 'blocked', + wallIds: [], + separatorIds: [], + opensZoneIds: [], + itemIds: [], + }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.map((c) => c.code)).toEqual(['shared-walls']) + expect(graph[zoneId]).toMatchObject({ name: 'Custom' }) + expect(graph[item.id]).toBeDefined() + }) + test('diff updates contain only changed keys including explicit clears', () => { + const { nodes, zoneId } = enclosed() + const next = { ...nodes, [zoneId]: { ...nodes[zoneId]!, name: 'New', floor: undefined } } + expect(diffStructure(nodes, next)).toEqual([ + { op: 'update', id: zoneId, data: { name: 'New' } }, + ]) + }) + test('L-room collinear boundary cuts and endpoints more than one metre away are refused', () => { + const initial = fixture() + const made = createZone(initial, { + levelId: 'level_test', + polygon: [ + [0, 0], + [8, 0], + [8, 4], + [4, 4], + [4, 8], + [0, 8], + ], + enclose: true, + mintId: mint(), + }) + const nodes = apply(initial, made) + expect( + divideZone(nodes, { + zoneId: made.zoneId, + cut: [ + [0, 4], + [8, 4], + ], + mintId: mint(), + }).conflicts?.[0]?.code, + ).toBe('boundary-overlap') + expect(snapZoneBoundary(nodes, made.zoneId, [-1, 2])).not.toBeNull() + expect(snapZoneBoundary(nodes, made.zoneId, [-1.001, 2])).toBeNull() + expect( + divideZone(nodes, { + zoneId: made.zoneId, + cut: [ + [-2, 2], + [4, 6], + ], + mintId: mint(), + }).conflicts?.[0]?.code, + ).toBe('snap-distance') + }) +}) diff --git a/packages/core/src/commands/structure/structure-store.test.ts b/packages/core/src/commands/structure/structure-store.test.ts new file mode 100644 index 0000000000..28eb84ec9c --- /dev/null +++ b/packages/core/src/commands/structure/structure-store.test.ts @@ -0,0 +1,304 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { initSpaceDetectionSync } from '../../lib/space-detection' +import { BuildingNode, ItemNode, LevelNode, WallNode, type ZoneNode } from '../../schema' +import { type SceneCommit, subscribeSceneCommits } from '../../store/history-control' +import useScene, { clearSceneHistory } from '../../store/use-scene' +import { + createMezzanine, + createZone, + deleteZone, + divideZone, + mergeZones, + type StructurePlan, + setWallGeometry, + setZoneEdges, + setZoneIntent, + structureChangeBatch, +} from './index' +import { roomFace } from './shared' + +globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} +let stop = () => {} +afterEach(() => { + stop() + useScene.temporal.getState().resume() +}) + +function setup() { + const level = LevelNode.parse({ id: 'level_store', parentId: 'building_store' }) + const building = BuildingNode.parse({ id: 'building_store', children: [level.id] }) + useScene.setState({ + nodes: { [level.id]: level, [building.id]: building }, + rootNodeIds: [building.id], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + useScene.temporal.getState().resume() + clearSceneHistory() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) + let i = 0 + const mintId = (kind: string) => `${kind}_store${++i}` + const created = createZone(useScene.getState().nodes, { + levelId: level.id, + polygon: [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ], + enclose: true, + mintId, + }) + return { created, mintId } +} +function assertCommit( + plan: StructurePlan, + counts: { zone: number; slab: number; ceiling: number }, +) { + expect(plan.conflicts).toBeUndefined() + clearSceneHistory() + const before = useScene.getState().nodes + const commits: SceneCommit[] = [] + const unsubscribe = subscribeSceneCommits((commit) => commits.push(commit)) + try { + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + expect(commits).toHaveLength(1) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + for (const [type, count] of Object.entries(counts)) + expect( + Object.values(commits[0]!.current.nodes).filter((node) => node.type === type), + ).toHaveLength(count) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + } finally { + unsubscribe() + } +} + +describe('structure primitive store commits', () => { + test('createZone: complete construction in one commit and undo', () => { + const { created } = setup() + assertCommit(created, { zone: 1, slab: 1, ceiling: 1 }) + }) + test('delete with kept contents detaches ceiling fixtures before the derived deletion and undoes', () => { + const { created } = setup() + useScene.getState().applyNodeChanges(structureChangeBatch(created.changes)) + const ceiling = Object.values(useScene.getState().nodes).find((n) => n.type === 'ceiling')! + const light = ItemNode.parse({ + id: 'item_retained_light', + parentId: ceiling.id, + position: [2, 0, 2], + asset: { + id: 'light', + category: 'lights', + name: 'Light', + thumbnail: '', + src: 'https://example.com/light.glb', + }, + }) + useScene.getState().createNode(light, ceiling.id) + const before = useScene.getState().nodes + clearSceneHistory() + const plan = deleteZone(before, { zoneId: created.zoneId, contents: 'keep' }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + expect(useScene.getState().nodes[light.id]).toMatchObject({ parentId: 'level_store' }) + expect(useScene.getState().nodes[ceiling.id]).toBeUndefined() + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + }) + test('Divide restores identical zone, separator, plate and ceiling IDs on undo then redo', () => { + const { created, mintId } = setup() + useScene.getState().applyNodeChanges(structureChangeBatch(created.changes)) + const before = useScene.getState().nodes + clearSceneHistory() + const plan = divideZone(before, { + zoneId: created.zoneId, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const after = useScene.getState().nodes + expect(Object.values(after).filter((n) => n.type === 'zone')).toHaveLength(2) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + }) + test('deleting ceiling contents produces no derived update and one reversible commit', () => { + const { created } = setup() + useScene.getState().applyNodeChanges(structureChangeBatch(created.changes)) + const ceiling = Object.values(useScene.getState().nodes).find((n) => n.type === 'ceiling')! + const light = ItemNode.parse({ + id: 'item_removed_light', + parentId: ceiling.id, + position: [2, 0, 2], + asset: { + id: 'light', + category: 'lights', + name: 'Light', + thumbnail: '', + src: 'https://example.com/light.glb', + }, + }) + useScene.getState().createNode(light, ceiling.id) + const plan = deleteZone(useScene.getState().nodes, { + zoneId: created.zoneId, + contents: 'delete', + }) + expect(plan.changes.some((c) => c.op === 'update' && c.id === ceiling.id)).toBe(false) + assertCommit(plan, { zone: 0, slab: 0, ceiling: 0 }) + }) + test('a room inside shared walls is refused: no reset, nothing written', () => { + const { created, mintId } = setup() + useScene.getState().applyNodeChanges(structureChangeBatch(created.changes)) + const points: [number, number][] = [ + [-2, -2], + [10, -2], + [10, 6], + [-2, 6], + ] + useScene.getState().applyNodeChanges({ + create: points.map((start, i) => ({ + node: WallNode.parse({ + id: mintId('wall'), + parentId: 'level_store', + start, + end: points[(i + 1) % 4], + }), + parentId: 'level_store', + })), + }) + useScene.getState().applyNodeChanges( + structureChangeBatch( + setZoneIntent(useScene.getState().nodes, { + zoneId: created.zoneId, + patch: { + name: 'Office', + floor: { elevation: 0.4, finish: 'wood' }, + wallMaterial: 'paint', + hasFloor: false, + hasCeiling: false, + }, + }).changes, + ), + ) + const refused = deleteZone(useScene.getState().nodes, { + zoneId: created.zoneId, + contents: 'keep', + }) + expect(refused.payload.mode).toBe('blocked') + expect(refused.changes).toEqual([]) + expect(refused.conflicts?.map((c) => c.code)).toEqual(['shared-walls']) + expect(useScene.getState().nodes[created.zoneId as ZoneNode['id']]).toMatchObject({ + name: 'Office', + }) + }) + for (const command of ['intent', 'edges', 'divide', 'merge', 'delete', 'geometry'] as const) + test(`${command}: complete construction in one commit and undo`, () => { + const { created, mintId } = setup() + useScene.getState().applyNodeChanges(structureChangeBatch(created.changes)) + let nodes = useScene.getState().nodes + let plan: StructurePlan + const zone = nodes[created.zoneId as ZoneNode['id']] as ZoneNode + let counts = { zone: 1, slab: 1, ceiling: 1 } + if (command === 'intent') { + plan = setZoneIntent(nodes, { + zoneId: zone.id, + patch: { hasCeiling: false, floor: { elevation: 0.2 } }, + }) + counts.ceiling = 0 + counts.slab = 2 + } else if (command === 'edges') + plan = setZoneEdges(nodes, { + zoneId: zone.id, + edges: [ + { + spanRef: { ...roomFace(nodes, zone)!.spans[0]!, t0: 0.25, t1: 0.75 }, + kind: 'separator', + }, + ], + mintId, + }) + else if (command === 'divide') { + plan = divideZone(nodes, { + zoneId: zone.id, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }) + counts = { zone: 2, slab: 1, ceiling: 2 } + } else if (command === 'merge') { + useScene.getState().applyNodeChanges( + structureChangeBatch( + divideZone(nodes, { + zoneId: zone.id, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }).changes, + ), + ) + nodes = useScene.getState().nodes + const ids = Object.values(nodes) + .filter((n) => n.type === 'zone') + .map((n) => n.id) + plan = mergeZones(nodes, { zoneIds: [ids[0]!, ids[1]!] }) + } else if (command === 'delete') { + plan = deleteZone(nodes, { zoneId: zone.id, contents: 'delete' }) + counts = { zone: 0, slab: 0, ceiling: 0 } + } else { + const wall = Object.values(nodes).find((n) => n.type === 'wall')! + plan = setWallGeometry(nodes, { wallId: wall.id, thickness: 0.25, mintId }) + } + assertCommit(plan, counts) + }) +}) + +for (const command of ['create', 'intent', 'delete'] as const) + test(`mezzanine ${command}: one complete commit and undo restores railing and ceiling hole`, () => { + const { created, mintId } = setup() + useScene.getState().applyNodeChanges(structureChangeBatch(created.changes)) + useScene.getState().updateNode('level_store', { height: 5 }) + const mezzanine = createMezzanine(useScene.getState().nodes, { + hostZoneId: created.zoneId, + polygon: [ + [1, 1], + [3, 1], + [3, 3], + [1, 3], + ], + mintId, + }) + if (command === 'create') { + assertCommit(mezzanine, { zone: 2, slab: 2, ceiling: 2 }) + return + } + useScene.getState().applyNodeChanges(structureChangeBatch(mezzanine.changes)) + const nodes = useScene.getState().nodes + const plan = + command === 'intent' + ? setZoneIntent(nodes, { + zoneId: mezzanine.zoneId, + patch: { floor: { elevation: 1.6, finish: 'wood' } }, + }) + : deleteZone(nodes, { zoneId: mezzanine.zoneId, contents: 'keep' }) + assertCommit(plan, { + zone: command === 'delete' ? 1 : 2, + slab: command === 'delete' ? 1 : 2, + ceiling: command === 'delete' ? 1 : 2, + }) + }) diff --git a/packages/core/src/commands/structure/structure.test.ts b/packages/core/src/commands/structure/structure.test.ts new file mode 100644 index 0000000000..d8a2dc6376 --- /dev/null +++ b/packages/core/src/commands/structure/structure.test.ts @@ -0,0 +1,387 @@ +import { describe, expect, test } from 'bun:test' +import { reconcileLevelStructure } from '../../lib/structure-kernel' +import { DoorNode, ItemNode, LevelNode, WallNode } from '../../schema' +import { getWallFaceLine } from '../../systems/wall/wall-frame' +import { + createZone, + deleteZone, + divideZone, + mergeZones, + setWallGeometry, + setZoneEdges, + setZoneIntent, +} from './index' +import { + applyToScratch, + roomFace, + type StructureNodes, + type StructurePlan, + structureChangeBatch, +} from './shared' + +export function fixture() { + const level = LevelNode.parse({ id: 'level_test' }) + return { [level.id]: level } +} +export function mint() { + let i = 0 + return (kind: string) => `${kind}_test${++i}` +} +export const polygon: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +export function apply(nodes: StructureNodes, plan: StructurePlan) { + expect(plan.conflicts).toBeUndefined() + const next = applyToScratch(nodes, structureChangeBatch(plan.changes)) + let i = 0 + const derived = reconcileLevelStructure({ + levelId: 'level_test', + nodes: next, + previousNodes: nodes, + mintId: (kind) => { + let id: string + do { + id = `${kind}_derived${++i}` + } while (next[id]) + return id + }, + }) + return applyToScratch(next, structureChangeBatch(derived.patches)) +} +export function enclosed() { + const initial = fixture() + const result = createZone(initial, { + levelId: 'level_test', + polygon, + enclose: true, + mintId: mint(), + name: 'Kitchen', + }) + return { nodes: apply(initial, result), zoneId: result.zoneId } +} + +describe('structure primitives', () => { + test('create is pure, deterministic with caller IDs; enclosure is opt-in and intent derives surfaces', () => { + const nodes = fixture(), + before = JSON.stringify(nodes) + const run = () => + createZone(nodes, { + levelId: 'level_test', + polygon, + mintId: mint(), + intent: { hasCeiling: false }, + }) + expect(run()).toEqual(run()) + expect(JSON.stringify(nodes)).toBe(before) + const next = apply(nodes, run()) + expect(Object.values(next).filter((n) => n.type === 'separator')).toHaveLength(4) + expect(Object.values(next).filter((n) => n.type === 'wall')).toHaveLength(0) + expect(Object.values(next).filter((n) => n.type === 'zone')).toHaveLength(1) + expect(Object.values(next).filter((n) => n.type === 'slab')).toHaveLength(1) + expect(Object.values(next).filter((n) => n.type === 'ceiling')).toHaveLength(0) + }) + test('intent merges nested fields, clears null, validates and stores names verbatim', () => { + const { nodes, zoneId } = enclosed() + const a = apply( + nodes, + setZoneIntent(nodes, { + zoneId, + patch: { floor: { elevation: 0.4, finish: 'wood' }, name: ' Studio ', hasCeiling: false }, + }), + ) + const b = apply( + a, + setZoneIntent(a, { zoneId, patch: { floor: { finish: null }, hasCeiling: null } }), + ) + expect(b[zoneId]).toMatchObject({ name: ' Studio ', floor: { elevation: 0.4 } }) + expect((b[zoneId] as { floor: object }).floor).not.toHaveProperty('finish') + expect(() => + setZoneIntent(nodes, { zoneId, patch: { floor: { elevation: Number.NaN } } }), + ).toThrow() + }) + test('divide snaps endpoints, retains seed identity, shares plate; merge restores one zone', () => { + const { nodes, zoneId } = enclosed() + const split = divideZone(nodes, { + zoneId, + cut: [ + [2, 0.03], + [2, 3.98], + ], + mintId: mint(), + }) + const next = apply(nodes, split) + expect(next[split.separatorId!]).toMatchObject({ start: [2, 0], end: [2, 4] }) + expect(next[zoneId]).toMatchObject({ name: 'Kitchen', seed: [4, 2] }) + const zones = Object.values(next).filter((n) => n.type === 'zone') + expect(zones).toHaveLength(2) + expect(Object.values(next).filter((n) => n.type === 'slab')).toHaveLength(1) + expect(Object.values(next).filter((n) => n.type === 'ceiling')).toHaveLength(2) + const merged = apply(next, mergeZones(next, { zoneIds: [zones[0]!.id, zones[1]!.id] })) + expect(Object.values(merged).filter((n) => n.type === 'zone')).toHaveLength(1) + expect(Object.values(merged).filter((n) => n.type === 'ceiling')).toHaveLength(1) + }) + test('walls and separators round trip through wall planners', () => { + const { nodes, zoneId } = enclosed() + const zone = nodes[zoneId]! + if (zone.type !== 'zone') throw Error() + const span = roomFace(nodes, zone)!.spans[0]! + const result = setZoneEdges(nodes, { + zoneId, + edges: [{ spanRef: span, kind: 'separator' }], + mintId: mint(), + }) + const next = apply(nodes, result) + const current = next[zoneId]! + if (current.type !== 'zone') throw Error() + const separator = roomFace(next, current)!.spans.find((s) => s.kind === 'separator')! + const restored = apply( + next, + setZoneEdges(next, { + zoneId, + edges: [{ spanRef: separator, kind: 'wall' }], + mintId: (kind) => `${kind}_restored`, + }), + ) + expect(Object.values(restored).filter((n) => n.type === 'wall')).toHaveLength(4) + expect(restored[zoneId]).toBeDefined() + }) + test('delete removes room construction; undo data includes all boundary IDs', () => { + const { nodes, zoneId } = enclosed() + const plan = deleteZone(nodes, { zoneId, contents: 'delete' }) + expect(plan.payload.wallIds).toHaveLength(4) + expect(plan.payload.keptSharedWallIds).toEqual([]) + const next = apply(nodes, plan) + for (const type of ['zone', 'wall', 'slab', 'ceiling']) + expect(Object.values(next).filter((n) => n.type === type)).toHaveLength(0) + }) + test('geometry moves junction neighbours while justification only moves the body', () => { + const { nodes } = enclosed() + const wall = Object.values(nodes).find((n): n is WallNode => n.type === 'wall')! + const result = setWallGeometry(nodes, { + wallId: wall.id, + start: [-1, 0], + end: [8, 0], + mintId: mint(), + }) + expect(applyToScratch(nodes, structureChangeBatch(result.changes))[wall.id]).toMatchObject({ + start: [-1, 0], + end: [8, 0], + }) + const justified = setWallGeometry(nodes, { + wallId: wall.id, + justification: 'a', + mintId: mint(), + }) + const after = applyToScratch(nodes, structureChangeBatch(justified.changes))[ + wall.id + ] as WallNode + expect(justified.changes).toEqual([{ op: 'update', id: wall.id, data: { justification: 'a' } }]) + expect(after.start).toEqual(wall.start) + expect(after.end).toEqual(wall.end) + expect(getWallFaceLine(after, 'b')).toEqual({ + start: { x: wall.start[0], y: wall.start[1] }, + end: { x: wall.end[0], y: wall.end[1] }, + }) + }) + test('create accepts a boundary set and closes explicit curved wall edges without a chord', () => { + const existing = enclosed() + const walls = Object.values(existing.nodes).filter((n) => n.type === 'wall') + const nodes = { ...fixture(), ...Object.fromEntries(walls.map((n) => [n.id, n])) } + const adopted = createZone(nodes, { + levelId: 'level_test', + boundaryIds: walls.map((n) => n.id), + mintId: () => 'zone_adopted', + }) + expect(adopted.changes).toHaveLength(1) + expect(apply(nodes, adopted)['zone_adopted']).toBeDefined() + const wall = WallNode.parse({ + id: 'wall_curve', + parentId: 'level_test', + start: [0, 0], + end: [8, 0], + curveOffset: -1, + }) + const curvedNodes = { ...fixture(), [wall.id]: wall } + const closed = createZone(curvedNodes, { + levelId: 'level_test', + edges: [ + { wallId: wall.id, face: 'a', t0: 0, t1: 1 }, + { + separator: [ + [8, 4], + [0, 4], + ], + }, + ], + mintId: mint(), + }) + expect( + closed.changes.filter((c) => c.op === 'create' && c.node.type === 'separator'), + ).toHaveLength(3) + expect(Object.values(apply(curvedNodes, closed)).filter((n) => n.type === 'zone')).toHaveLength( + 1, + ) + expect(() => + createZone(fixture(), { + levelId: 'level_test', + polygon: [ + [0, 0], + [4, 4], + [0, 4], + [3, 0], + ], + mintId: mint(), + }), + ).toThrow('valid polygon') + }) + test('partial wall conversion reports openings, preserves surviving hosts and supports several spans', () => { + const { nodes, zoneId } = enclosed() + const wall = Object.values(nodes).find( + (n) => n.type === 'wall' && n.start[0] === 0 && n.start[1] === 0 && n.end[0] === 8, + )! + const kept = DoorNode.parse({ + id: 'door_kept', + parentId: wall.id, + wallId: wall.id, + position: [1, 0, 0], + }) + const removed = DoorNode.parse({ + id: 'door_removed', + parentId: wall.id, + wallId: wall.id, + position: [3, 0, 0], + }) + const graph = { + ...nodes, + [kept.id]: kept, + [removed.id]: removed, + [wall.id]: { ...wall, children: [kept.id, removed.id] }, + } + const zone = nodes[zoneId]! + if (zone.type !== 'zone') throw Error() + const span = roomFace(nodes, zone)!.spans.find((s) => s.boundaryId === wall.id)! + let nextId = 0 + const mintId = (kind: string) => `${kind}_conversion${++nextId}` + const input = { + zoneId, + edges: [{ spanRef: { ...span, t0: 0.25, t1: 0.75 }, kind: 'separator' as const }], + mintId, + } + expect(setZoneEdges(graph, input)).toMatchObject({ + changes: [], + conflicts: [{ code: 'hosted-openings', nodeIds: [removed.id] }], + }) + const next = apply(graph, setZoneEdges(graph, { ...input, dropOpenings: true })) + expect(next[removed.id]).toBeUndefined() + expect(next[kept.id]).toMatchObject({ parentId: wall.id, position: [1, 0, 0] }) + expect(next[zoneId]).toBeDefined() + const multiple = apply( + nodes, + setZoneEdges(nodes, { + zoneId, + edges: [ + { spanRef: { ...span, t0: 0.1, t1: 0.2 }, kind: 'separator' }, + { spanRef: { ...span, t0: 0.7, t1: 0.8 }, kind: 'separator' }, + ], + mintId, + }), + ) + expect(Object.values(multiple).filter((n) => n.type === 'separator')).toHaveLength(2) + expect(Object.values(multiple).filter((n) => n.type === 'wall')).toHaveLength(6) + }) + test('shared walls stay on edge conversion and deletion; wall-only merge names the wall', () => { + const { nodes, zoneId } = enclosed() + const divided = apply( + nodes, + divideZone(nodes, { + zoneId, + cut: [ + [2, 0], + [2, 4], + ], + mintId: mint(), + }), + ) + const zone = divided[zoneId]! + if (zone.type !== 'zone') throw Error() + const separator = roomFace(divided, zone)!.spans.find((s) => s.kind === 'separator')! + let nextId = 0 + const walled = apply( + divided, + setZoneEdges(divided, { + zoneId, + edges: [{ spanRef: separator, kind: 'wall' }], + mintId: (kind) => `${kind}_shared${++nextId}`, + }), + ) + const wall = Object.values(walled).find( + (n) => n.type === 'wall' && n.start[0] === 2 && n.end[0] === 2, + )! + const zones = Object.values(walled).filter((n) => n.type === 'zone') + expect(mergeZones(walled, { zoneIds: [zones[0]!.id, zones[1]!.id] })).toMatchObject({ + changes: [], + conflicts: [{ code: 'wall-boundary', nodeIds: [wall.id] }], + }) + const current = walled[zoneId]! + if (current.type !== 'zone') throw Error() + const shared = roomFace(walled, current)!.spans.find((s) => s.boundaryId === wall.id)! + expect( + setZoneEdges(walled, { + zoneId, + edges: [{ spanRef: shared, kind: 'separator' }], + mintId: mint(), + }).changes, + ).toEqual([]) + const deleted = deleteZone(walled, { zoneId, contents: 'delete' }) + expect(deleted.payload.keptSharedWallIds).toContain(wall.id) + expect(apply(walled, deleted)[wall.id]).toBeDefined() + }) + test('keep contents preserves item hierarchy and detaches ceiling fixtures before derivation', () => { + const { nodes, zoneId } = enclosed() + const ceiling = Object.values(nodes).find((n) => n.type === 'ceiling')! + const asset = { + id: 'fixture', + category: 'test', + name: 'Fixture', + thumbnail: '', + src: 'https://example.com/fixture.glb', + } + const table = ItemNode.parse({ + id: 'item_table', + parentId: 'level_test', + position: [2, 0, 2], + children: ['item_child'], + asset, + }) + const child = ItemNode.parse({ + id: 'item_child', + parentId: table.id, + position: [0, 1, 0], + asset, + }) + const light = ItemNode.parse({ + id: 'item_light', + parentId: ceiling.id, + position: [3, 0, 2], + asset, + }) + const graph = { + ...nodes, + [table.id]: table, + [child.id]: child, + [light.id]: light, + [ceiling.id]: { ...ceiling, children: [light.id] }, + } + const kept = deleteZone(graph, { zoneId, contents: 'keep' }) + expect(kept.payload.itemIds).toHaveLength(3) + const result = apply(graph, kept) + expect(result[table.id]).toMatchObject({ parentId: 'level_test', children: [child.id] }) + expect(result[child.id]).toMatchObject({ parentId: table.id, position: [0, 1, 0] }) + expect(result[light.id]).toMatchObject({ parentId: 'level_test' }) + const deleted = apply(graph, deleteZone(graph, { zoneId, contents: 'delete' })) + expect(Object.values(deleted).filter((n) => n.type === 'item')).toHaveLength(0) + }) +}) diff --git a/packages/core/src/commands/structure/transform-zone.ts b/packages/core/src/commands/structure/transform-zone.ts new file mode 100644 index 0000000000..5389653820 --- /dev/null +++ b/packages/core/src/commands/structure/transform-zone.ts @@ -0,0 +1,544 @@ +import { polygonCentroid } from '../../lib/polygon-label' +import { getRoomBaseElevation } from '../../lib/room-floor-feasibility' +import { extractRooms } from '../../lib/room-graph' +import type { AnyNode, WallNode, ZoneNode } from '../../schema' +import { isDerivedNode } from '../../store/derived-node-guard' +import { getWallCurveFrameAt, getWallCurveLength } from '../../systems/wall/wall-curve' +import { planWallDivision } from '../../systems/wall/wall-operations' +import type { CeilingHostAssignment, SupportHostAssignment } from './apply-zone-transform' +import { + applyToScratch, + at, + boundaries, + conflict, + diffStructure, + type Point, + requireZone, + roomFace, + type StructureConflict, + type StructureNodes, + type StructurePlan, +} from './shared' +import { validateMezzanine } from './validate-mezzanine' +import { clearOpeningCuts, dropCrossingCuts } from './zone-crossings' +import { preserveDroppedRoomSeeds, snapDroppedWalls } from './zone-drop' +import { insertDroppedBoundaries } from './zone-insertion' +import { + collectTransformContents, + includeDescendants, + repairTransformChildren, +} from './zone-transform-content' +import { + collinearOverlap, + splitCollinearWalls, + wallAttachments, + wallSlice, +} from './zone-wall-merge' + +export type TransformZoneInput = { + zoneId: string + translate?: Point + /** Radians about Y; rotation precedes translation. Defaults to the room's area centroid. */ + rotate?: { angle: number; pivot?: Point } + force?: boolean + mintId: (kind: AnyNode['type']) => string +} +export type ZoneTransformPlan = StructurePlan & { + zoneId: string + idMap: Record + ceilingHosts?: CeilingHostAssignment[] + supportHosts?: SupportHostAssignment[] +} + +export function transformZone(nodes: StructureNodes, input: TransformZoneInput): ZoneTransformPlan { + return planZoneTransform(nodes, input, false) +} + +export function planZoneTransform( + nodes: StructureNodes, + input: TransformZoneInput, + duplicate: boolean, +): ZoneTransformPlan { + const zone = requireZone(nodes, input.zoneId) + const mezzanine = zone.floor?.support === 'open' + const face = mezzanine + ? { id: zone.id, referencePolygon: zone.polygon, holes: zone.holes, spans: [] } + : roomFace(nodes, zone) + const idMap: Record = {} + const failed = (code: string, ids: string[], message: string): ZoneTransformPlan => ({ + ...conflict(code, ids, message), + zoneId: zone.id, + idMap: {}, + }) + if (!face) + return failed('open-room', [zone.id], 'The room needs an enclosed boundary before it can move.') + const angle = input.rotate?.angle ?? 0, + translate = input.translate ?? [0, 0] + const pivot = + input.rotate?.pivot ?? polygonCentroid({ outer: face.referencePolygon, holes: face.holes }) + if (![angle, ...translate, ...pivot].every(Number.isFinite)) + throw Error('Room transforms must be finite.') + if (!duplicate && angle === 0 && translate.every((v) => v === 0)) + return { changes: [], zoneId: zone.id, idMap: { [zone.id]: [zone.id] } } + const exact = (value: number) => (Math.abs(value) < 1e-12 ? 0 : value) + const cosine = exact(Math.cos(angle)), + sine = exact(Math.sin(angle)) + const transform = ([x, z]: Point): Point => [ + pivot[0] + cosine * (x - pivot[0]) + sine * (z - pivot[1]) + translate[0] + 0, + pivot[1] - sine * (x - pivot[0]) + cosine * (z - pivot[1]) + translate[1] + 0, + ] + if (mezzanine) { + const invalid = validateMezzanine( + nodes, + { + ...zone, + polygon: zone.polygon.map(transform), + holes: zone.holes.map((hole) => hole.map(transform)), + }, + duplicate ? undefined : zone.id, + ) + if (invalid) return { changes: [], conflicts: [invalid], zoneId: zone.id, idMap: {} } + } + const allocated = new Set(Object.keys(nodes)) + const mintId = (kind: AnyNode['type']) => { + const minted = input.mintId(kind) + const id = kind === 'stair-segment' ? minted.replace(/^stair-segment_/, 'sseg_') : minted + if (!id.startsWith(`${kind === 'stair-segment' ? 'sseg' : kind}_`) || allocated.has(id)) + throw Error(`Invalid or reused ${kind} id: ${id}`) + allocated.add(id) + return id + } + let scratch: Record = { ...nodes } + const ceilingHosts: CeilingHostAssignment[] = [] + const supportHosts: SupportHostAssignment[] = [] + const moving = new Set() + const plain = new Set() + const sourceFor = new Map() + const allFaces = extractRooms(boundaries(nodes, zone.parentId!)) + const boundaryIds = [...new Set(face.spans.map((span) => span.boundaryId))] + const materialCopies = new Set() + for (const boundaryId of boundaryIds) { + const original = nodes[boundaryId] + if (!original || (original.type !== 'wall' && original.type !== 'separator')) continue + const spans = face.spans.filter((span) => span.boundaryId === boundaryId) + const opposite = allFaces + .filter((other) => other.id !== face.id) + .flatMap((other) => other.spans) + .filter( + (span) => span.boundaryId === boundaryId && spans.some((own) => own.face !== span.face), + ) + const cuts = [ + ...new Set([ + 0, + 1, + ...spans.flatMap((span) => [span.t0, span.t1]), + ...opposite.flatMap((span) => [span.t0, span.t1]), + ]), + ].sort((a, b) => a - b) + const ranges: Array<{ lo: number; hi: number; shared: boolean }> = [] + for (let i = 1; i < cuts.length; i++) { + const lo = cuts[i - 1]!, + hi = cuts[i]!, + mid = (lo + hi) / 2 + if (hi - lo < 1e-6 || !spans.some((span) => mid >= span.t0 && mid <= span.t1)) continue + const shared = opposite.some((span) => mid >= span.t0 && mid <= span.t1) + const previous = ranges.at(-1) + if (previous && previous.shared === shared && Math.abs(previous.hi - lo) < 1e-6) + previous.hi = hi + else ranges.push({ lo, hi, shared }) + } + const segments = [{ lo: 0, hi: 1, id: original.id as string }] + const needsDivision = + !duplicate && + ranges.some((range) => !range.shared) && + (ranges.length > 1 || ranges[0]!.lo > 1e-6 || ranges[0]!.hi < 1 - 1e-6) + if (needsDivision) { + const splits = [...new Set(ranges.flatMap((range) => [range.lo, range.hi]))] + .filter((t) => t > 1e-6 && t < 1 - 1e-6) + .sort((a, b) => b - a) + if (original.type === 'wall') { + const blocked = clearOpeningCuts(scratch, original, splits, input.force ?? false) + if (blocked) return { changes: [], conflicts: [blocked], idMap: {}, zoneId: zone.id } + } + try { + for (const t of splits) { + const first = segments[0]!, + current = scratch[first.id] as typeof original + let id: string + if (current.type === 'wall') { + const division = planWallDivision( + scratch, + current.id, + t * getWallCurveLength(original as WallNode), + () => mintId('wall'), + ) + scratch = applyToScratch(scratch, division.changes) + id = division.changes.create[0]!.node.id + } else { + id = mintId('separator') + const point = at(original.start, original.end, t) + scratch[id] = { ...current, id: id as typeof current.id, start: point } + scratch[current.id] = { ...current, end: point } + } + segments.push({ lo: t, hi: first.hi, id }) + first.hi = t + } + } catch (error) { + return failed('occupied-split', [boundaryId], String(error)) + } + } + idMap[boundaryId] = [] + for (const { lo, hi, shared } of ranges) { + let boundary = scratch[ + segments.find((segment) => (lo + hi) / 2 >= segment.lo && (lo + hi) / 2 <= segment.hi)!.id + ] as typeof original + if (duplicate || shared) { + const id = mintId(original.type) + const point = (t: number): Point => { + if (original.type === 'separator') return at(original.start, original.end, t) + const frame = getWallCurveFrameAt(original, t) + return [frame.point.x, frame.point.y] + } + boundary = + original.type === 'wall' + ? wallSlice(original, point(lo), point(hi), id, [lo, hi]) + : { ...original, id: id as typeof original.id, start: point(lo), end: point(hi) } + scratch[id] = boundary + sourceFor.set(id, original.id) + if (shared) { + plain.add(id) + materialCopies.add(id) + } else if (original.type === 'wall') { + const length = getWallCurveLength(original) + for (const child of wallAttachments(nodes, original)) { + const t = + 'position' in child && Array.isArray(child.position) + ? child.position[0] / length + : 0.5 + if (t < lo - 1e-6 || t > hi + 1e-6) continue + const childId = mintId(child.type) + scratch[childId] = { + ...child, + id: childId, + parentId: id, + wallId: id, + ...('position' in child && Array.isArray(child.position) + ? { + position: [ + child.position[0] - lo * length, + child.position[1], + child.position[2], + ], + } + : {}), + ...('wallT' in child ? { wallT: (t - lo) / (hi - lo) } : {}), + } as AnyNode + sourceFor.set(childId, child.id) + idMap[child.id] = [childId] + moving.add(childId) + } + } + } + moving.add(boundary.id) + idMap[boundaryId]!.push(boundary.id) + } + } + const contents = collectTransformContents(nodes, zone) + if (duplicate) { + // Copy descendants from the source graph before remapping parents, including nested wall items. + const sources = new Set([ + ...contents, + ...[...sourceFor].filter(([id]) => !plain.has(id)).map(([, source]) => source), + ]) + for (const id of boundaryIds) sources.delete(id) + includeDescendants(nodes, sources) + for (const id of sources) { + if (idMap[id]) continue + const node = nodes[id]! + const copyId = mintId(node.type) + scratch[copyId] = { ...node, id: copyId } as AnyNode + moving.add(copyId) + sourceFor.set(copyId, id) + idMap[id] = [copyId] + } + } else { + for (const id of contents) moving.add(id) + includeDescendants(scratch, moving) + } + const resultZoneId = duplicate ? mintId('zone') : zone.id + idMap[zone.id] = [resultZoneId] + scratch[resultZoneId] = { + ...zone, + id: resultZoneId as ZoneNode['id'], + ...(duplicate ? { name: nextRoomName(nodes, zone.name) } : {}), + } + moving.add(resultZoneId) + sourceFor.set(resultZoneId, zone.id) + for (const id of moving) { + const node = scratch[id]! + let next = { ...node } as AnyNode + const sourceId = sourceFor.get(id) ?? id + const source = nodes[sourceId] ?? node + if (duplicate && source.parentId && idMap[source.parentId]) + next.parentId = idMap[source.parentId]![0] as AnyNode['parentId'] + for (const key of ['supportSlabId', 'deckSlabId', 'wallId', 'hostZoneId'] as const) { + const ref = (source as unknown as Record)[key] + if (typeof ref !== 'string') continue + if (duplicate && idMap[ref]) Object.assign(next, { [key]: idMap[ref]![0] }) + else if (duplicate && nodes[ref] && isDerivedNode(nodes[ref]!)) { + const slab = nodes[ref] + if (slab?.type === 'slab' && (key === 'supportSlabId' || key === 'deckSlabId')) { + const copiedZone = slab.zoneIds?.map((id) => idMap[id]?.[0]).find(Boolean) + if (copiedZone) supportHosts.push({ nodeId: next.id, zoneId: copiedZone, field: key }) + } + Object.assign(next, { [key]: undefined }) + } + } + if (duplicate && next.type === 'floor-opening' && next.ownerId) { + const copiedOwner = idMap[next.ownerId]?.[0] + next.ownerId = copiedOwner + if (!copiedOwner && next.source === 'plugin:pool') next.source = 'manual' + } + if (duplicate && 'collectionIds' in next) next.collectionIds = [] + const parent = next.parentId ? scratch[next.parentId] : undefined + const inheritedPose = + parent && moving.has(parent.id) && ('position' in parent || parent.type === 'wall') + if (next.type === 'wall' || next.type === 'separator') + next = { ...next, start: transform(next.start), end: transform(next.end) } + if ('polygon' in next && Array.isArray(next.polygon)) { + next = { + ...next, + polygon: next.polygon.map(transform), + ...('holes' in next && Array.isArray(next.holes) + ? { holes: next.holes.map((hole) => hole.map(transform)) } + : {}), + } as AnyNode + } + if ('position' in next && Array.isArray(next.position) && !inheritedPose) { + const point = transform([next.position[0], next.position[2]]) + let y = next.position[1] + if (duplicate && parent && isDerivedNode(parent)) { + if (parent.type === 'ceiling') { + ceilingHosts.push({ + nodeId: next.id, + zoneId: idMap[parent.zoneId ?? '']?.[0] ?? resultZoneId, + offsetY: y, + }) + y += parent.height ?? 2.7 + } + next.parentId = zone.parentId + } + next = { + ...next, + position: [point[0], y + 0, point[1]], + ...('rotation' in next + ? { + rotation: Array.isArray(next.rotation) + ? [next.rotation[0] + 0, next.rotation[1] + angle + 0, next.rotation[2] + 0] + : typeof next.rotation === 'number' + ? next.rotation + angle + 0 + : next.rotation, + } + : {}), + } as AnyNode + } + if (next.type === 'zone') + next = { + ...next, + ...(next.floor?.support === 'open' && !mezzanine ? { hostZoneId: resultZoneId } : {}), + seed: transform( + next.seed ?? + polygonCentroid({ + outer: node.type === 'zone' ? node.polygon : zone.polygon, + holes: [], + }), + ), + boundaryWallIds: (next.boundaryWallIds ?? []).flatMap( + (id) => idMap[id] ?? [id], + ) as WallNode['id'][], + boundarySeparatorIds: (next.boundarySeparatorIds ?? []).flatMap((id) => idMap[id] ?? [id]), + ...(next.wallOverrides + ? { + wallOverrides: next.wallOverrides.flatMap((entry) => + (idMap[entry.wallId] ?? [entry.wallId]).map((wallId) => ({ ...entry, wallId })), + ), + } + : {}), + // A copied door carries its step paint to the copy. + ...(next.floorStepOverrides + ? { + floorStepOverrides: next.floorStepOverrides.map((entry) => ({ + ...entry, + key: idMap[entry.key]?.[0] ?? entry.key, + })), + } + : {}), + ...(next.floor + ? { + floor: { + ...next.floor, + ...(duplicate && next.floor.footprint + ? { elevation: next.floor.elevation ?? getRoomBaseElevation(nodes, sourceId) } + : {}), + ...(duplicate && next.floor.sourceSlabId + ? { + sourceSlabId: idMap[next.floor.sourceSlabId]?.[0] as + | `slab_${string}` + | undefined, + } + : {}), + ...(next.floor.regions + ? { + regions: next.floor.regions.map((region) => ({ + ...region, + polygon: region.polygon.map(transform), + })), + } + : {}), + }, + } + : {}), + ...(next.ceiling?.regions + ? { + ceiling: { + ...next.ceiling, + regions: next.ceiling.regions.map((region) => ({ + ...region, + polygon: region.polygon.map(transform), + })), + }, + } + : {}), + } + scratch[id] = next + idMap[sourceId] ??= [id] + } + if (mezzanine) { + repairTransformChildren(scratch, nodes) + return { + changes: diffStructure(nodes, scratch), + zoneId: resultZoneId, + idMap, + ceilingHosts, + supportHosts, + } + } + const stationary = new Set( + boundaries(scratch, zone.parentId!) + .filter((node) => !moving.has(node.id)) + .map((node) => node.id), + ) + snapDroppedWalls(scratch, moving, zone.parentId!) + const preserveFinish = (wallId: string) => { + const current = scratch[resultZoneId] as ZoneNode + const wall = scratch[wallId] + if (wall?.type !== 'wall' || current.wallMaterial) return + const overrides = [...(current.wallOverrides ?? [])] + for (const span of face.spans) { + if (!idMap[span.boundaryId]?.includes(wallId)) continue + const finish = wall.slots?.[span.face] + if (finish && !overrides.some((entry) => entry.wallId === wallId && entry.face === span.face)) + overrides.push({ wallId, face: span.face, finish }) + } + if (overrides.length !== (current.wallOverrides?.length ?? 0)) + scratch[resultZoneId] = { ...current, wallOverrides: overrides } + } + for (const wallId of materialCopies) preserveFinish(wallId) + const conflicts: StructureConflict[] = [] + if (!duplicate) { + const plates = new Set( + Object.values(nodes) + .filter( + (node) => + node.type === 'slab' && + node.parentId === zone.parentId && + (node.zoneIds?.some((id) => moving.has(id)) || moving.has(node.id)), + ) + .map((node) => node.id), + ) + for (const node of Object.values(nodes)) + if ( + node.type === 'stair' && + node.parentId !== zone.parentId && + node.deckSlabId && + plates.has(node.deckSlabId as never) + ) + conflicts.push({ + code: 'deck-reference', + nodeIds: [node.id, node.deckSlabId], + message: 'A stair on another level uses the moving room’s floor as its destination deck.', + }) + } + if (conflicts.length && !input.force) + return { changes: [], conflicts, idMap: {}, zoneId: resultZoneId } + for (const [id, cuts] of dropCrossingCuts(scratch, moving, zone.parentId!)) { + const wall = scratch[id] + if (wall?.type !== 'wall') continue + const blocked = clearOpeningCuts(scratch, wall, cuts, input.force ?? false) + if (blocked) return { changes: [], conflicts: [blocked], idMap: {}, zoneId: resultZoneId } + } + const queue = [...moving].filter((id) => scratch[id]?.type === 'wall') + while (queue.length) { + const id = queue.shift()!, + placed = scratch[id] + if (placed?.type !== 'wall') continue + const destination = Object.values(scratch).find( + (node): node is WallNode => + node.type === 'wall' && + node.parentId === zone.parentId && + !moving.has(node.id) && + collinearOverlap(placed, node), + ) + if (!destination) continue + preserveFinish(placed.id) + const split = splitCollinearWalls(scratch, placed, destination, mintId) + const replacements = split.get(placed)! + moving.add(destination.id) + for (const [sourceWall, targets] of split) { + if (stationary.has(sourceWall.id)) for (const target of targets) stationary.add(target.id) + for (const [sourceId, ids] of Object.entries(idMap)) + idMap[sourceId] = [ + ...new Set( + ids.flatMap((old) => (old === sourceWall.id ? targets.map((wall) => wall.id) : [old])), + ), + ] + idMap[sourceWall.id] ??= targets.map((wall) => wall.id) + } + for (const tail of replacements.slice(1)) { + moving.add(tail.id) + queue.push(tail.id) + } + } + const blocked = insertDroppedBoundaries( + scratch, + moving, + zone.parentId!, + idMap, + mintId, + input.force ?? false, + stationary, + ) + if (blocked) return { changes: [], conflicts: [blocked], idMap: {}, zoneId: resultZoneId } + preserveDroppedRoomSeeds(scratch, resultZoneId) + repairTransformChildren(scratch, nodes) + return { + changes: diffStructure(nodes, scratch), + ...(conflicts.length ? { conflicts } : {}), + idMap, + zoneId: resultZoneId, + ...(ceilingHosts.length ? { ceilingHosts } : {}), + ...(supportHosts.length ? { supportHosts } : {}), + } +} + +function nextRoomName(nodes: StructureNodes, name: string) { + const base = name.replace(/ \d+$/, '') || 'Room' + const used = new Set( + Object.values(nodes) + .filter((node) => node.type === 'zone') + .map((node) => node.name), + ) + let number = 2 + while (used.has(`${base} ${number}`)) number++ + return `${base} ${number}` +} diff --git a/packages/core/src/commands/structure/validate-mezzanine.ts b/packages/core/src/commands/structure/validate-mezzanine.ts new file mode 100644 index 0000000000..b927ac8afc --- /dev/null +++ b/packages/core/src/commands/structure/validate-mezzanine.ts @@ -0,0 +1,91 @@ +import { area, difference, intersection, union } from '../../lib/polygon-boolean' +import { segmentsIntersect } from '../../lib/polygon-relations' +import type { WallNode, ZoneNode } from '../../schema' +import { calculateLevelMiters, getWallPlanFootprint } from '../../systems/wall/wall-footprint' +import { mezzanineElevationConflict } from './mezzanine-content' +import { type Point, roomFace, type StructureConflict, type StructureNodes } from './shared' + +export function mezzanineHostClearance(nodes: StructureNodes, host: ZoneNode) { + const face = roomFace(nodes, host) + if (!face) return [] + const walls = Object.values(nodes).filter( + (node): node is WallNode => node.type === 'wall' && node.parentId === host.parentId, + ) + const miters = calculateLevelMiters(walls) + return difference( + { outer: face.referencePolygon, holes: face.holes }, + union(walls.map((wall) => getWallPlanFootprint(wall, miters).map(({ x, y }): Point => [x, y]))), + ) +} + +export function validateMezzanine( + nodes: StructureNodes, + zone: ZoneNode, + excludeId?: string, +): StructureConflict | undefined { + const fail = (code: string, message: string, nodeIds = [zone.id as string]) => ({ + code, + message, + nodeIds, + }) + const polygon = zone.polygon + if (polygon.length < 3 || !polygon.flat().every(Number.isFinite)) + return fail('too-small', 'A mezzanine needs a finite polygon of at least 1 m².') + if ( + polygon.some((start, i) => + polygon.some( + (other, j) => + j > i + 1 && + !(i === 0 && j === polygon.length - 1) && + segmentsIntersect( + start, + polygon[(i + 1) % polygon.length]!, + other, + polygon[(j + 1) % polygon.length]!, + ), + ), + ) + ) + return fail('self-intersecting', 'Mezzanine edges must not cross.') + if (area([{ outer: polygon, holes: zone.holes }]) < 1) + return fail('too-small', 'A mezzanine must have at least 1 m² of floor.') + // Intent may reach wall reference lines; the structure kernel clips derived plates to wall faces. + const host = nodes[zone.hostZoneId ?? ''] + const face = host?.type === 'zone' ? roomFace(nodes, host) : undefined + if ( + host?.type !== 'zone' || + host.floor?.support === 'open' || + host.parentId !== zone.parentId || + !face || + area( + difference( + { outer: polygon, holes: zone.holes }, + { outer: face.referencePolygon, holes: face.holes }, + ), + ) > 1e-6 + ) + return fail( + 'outside-host', + 'The mezzanine must stay inside its host room’s reference boundary.', + ) + const overlapping = Object.values(nodes).filter( + (node) => + node.type === 'zone' && + node.id !== excludeId && + node.floor?.support === 'open' && + node.parentId === zone.parentId && + area( + intersection( + { outer: polygon, holes: zone.holes }, + { outer: node.polygon, holes: node.holes }, + ), + ) > 1e-6, + ) + if (overlapping.length) + return fail( + 'overlaps-mezzanine', + 'Mezzanines must not overlap.', + overlapping.map((node) => node.id), + ) + return mezzanineElevationConflict(nodes, zone) +} diff --git a/packages/core/src/commands/structure/vertical-model-c.test.ts b/packages/core/src/commands/structure/vertical-model-c.test.ts new file mode 100644 index 0000000000..5aaf391049 --- /dev/null +++ b/packages/core/src/commands/structure/vertical-model-c.test.ts @@ -0,0 +1,440 @@ +import { expect, test } from 'bun:test' +import { + floorFootprintSupportClass, + floorPlateAtGroundContact, + floorPlateGestureMinimum, + floorPlateHoldsUnderside, + upperFloorHeightControl, +} from '../../lib/floor-foundation-datum' +import { changedLevelConstructionDisplacements } from '../../lib/floor-foundation-stack' +import { wallSupportForNodes } from '../../lib/opening-floor-datum' +import { + type AnyNode, + BuildingNode, + DoorNode, + LevelNode, + type SlabNode, + StairNode, + WallNode, + ZoneNode, +} from '../../schema' +import { getCeilingClampBound, getLevelElevations, getWallPlaneTop } from '../../services/storey' +import { resolveStairTotalRise } from '../../systems/stair/stair-rise-query' +import { resolveWallTop } from '../../systems/wall/wall-top' +import { reconcileStructureOnLoad } from '../../utils/reconcile-structure-on-load' +import { setFloorFoundation } from './set-floor-foundation' + +const polygon = (x: number, width = 4): [number, number][] => [ + [x, 0], + [x + width, 0], + [x + width, 4], + [x, 4], +] + +function house(withWing = false) { + const building = BuildingNode.parse({ id: 'building_model_c' }) + const levels = [0, 1, 2].map((ordinal) => + LevelNode.parse({ + id: `level_model_c_${ordinal}`, + parentId: building.id, + level: ordinal, + height: 3, + }), + ) + building.children = levels.map((level) => level.id) + const nodes: Record = Object.fromEntries( + [building, ...levels].map((node) => [node.id, node]), + ) + for (const [ordinal, level] of levels.entries()) { + for (const x of withWing && ordinal < 2 ? [0, 10] : [0]) { + const outline = polygon(x, withWing && ordinal === 2 ? 14 : 4) + const name = x ? 'Garage floor' : 'Shared floor' + const zone = ZoneNode.parse({ + id: `zone_model_c_${ordinal}_${x}`, + parentId: level.id, + polygon: outline, + name, + spaceRole: 'room', + }) + nodes[zone.id] = zone + for (const [index, start] of outline.entries()) { + const wall = WallNode.parse({ + id: `wall_model_c_${ordinal}_${x}_${index}`, + parentId: level.id, + start, + end: outline[(index + 1) % outline.length], + ...(ordinal === 1 && index === 0 ? { height: 2.4 } : {}), + }) + nodes[wall.id] = wall + } + } + } + if (withWing) { + const level = levels[2]! + const zone = nodes.zone_model_c_2_0 as ZoneNode + nodes[zone.id] = { ...zone, polygon: polygon(0, 14) } + } + for (const level of levels) + level.children = Object.values(nodes) + .filter((node) => node.parentId === level.id) + .map((node) => node.id) as LevelNode['children'] + return reconcileStructureOnLoad(nodes).nodes +} + +function base(nodes: Record, ordinal: number, x = 0) { + const zoneId = `zone_model_c_${ordinal}_${x}` + return Object.values(nodes).find( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && !!node.zoneIds?.includes(zoneId), + )! +} + +function apply(nodes: Record, plate: SlabNode, thickness: number) { + const plan = setFloorFoundation(nodes, { slabId: plate.id, patch: { thickness } }) + expect(plan.conflicts).toEqual([]) + const changed = { ...nodes } + for (const change of plan.changes) { + if (change.op === 'update') + changed[change.id] = { ...changed[change.id], ...change.data } as AnyNode + } + return reconcileStructureOnLoad(changed).nodes +} + +test('supported thickness holds the underside, lifts its storey and descendants, and preserves explicit wall height', () => { + const before = house() + const upper = base(before, 1) + expect(floorFootprintSupportClass(before, upper)).toBe('supported') + expect(floorPlateGestureMinimum(before, upper)).toBeCloseTo(0.02) + expect(upperFloorHeightControl(before, upper, 0.35)).toEqual({ + currentTop: 0.05, + minimumTop: 0.02, + write: { thickness: 0.35 }, + }) + expect(upperFloorHeightControl(before, upper, 0.5)?.advice).toBe('thick-floor') + const groundWall = before.wall_model_c_0_0_0 as WallNode + const upperWall = before.wall_model_c_1_0_0 as WallNode + const authored = { ...before, [upperWall.id]: { ...upperWall, height: 2.4 } } + const authoredWall = authored[upperWall.id] as WallNode + const groundTop = getWallPlaneTop(groundWall, groundWall.parentId!, before) + const groundCeiling = getCeilingClampBound(groundWall.parentId!, before, polygon(0)) + const oldUnderside = upper.elevation - upper.thickness + const after = apply(authored, upper, 0.3) + const next = after[upper.id] as SlabNode + expect(next.thickness).toBeCloseTo(0.3) + expect(next.floorHeight).toBeUndefined() + expect(next.elevation - next.thickness).toBeCloseTo(oldUnderside) + expect(getWallPlaneTop(groundWall, groundWall.parentId!, after)).toBeCloseTo(groundTop) + expect(getCeilingClampBound(groundWall.parentId!, after, polygon(0))).toBeCloseTo(groundCeiling) + expect((after[upperWall.id] as WallNode).height).toBeCloseTo(2.4) + const oldSupport = wallSupportForNodes(authoredWall, authored).elevation + const newSupport = wallSupportForNodes(after[upperWall.id] as WallNode, after).elevation + expect(newSupport - oldSupport).toBeCloseTo(0.25) + expect( + resolveWallTop(after[upperWall.id] as WallNode, 3, newSupport) - + resolveWallTop(authoredWall, 3, oldSupport), + ).toBeCloseTo(0.25) + expect(getLevelElevations(after).get('level_model_c_2')!.baseY).toBeCloseTo( + getLevelElevations(before).get('level_model_c_2')!.baseY + 0.25, + ) + for (const ordinal of [0, 1, 2]) + expect(after[`level_model_c_${ordinal}`]).toEqual(before[`level_model_c_${ordinal}`]) + expect(reconcileStructureOnLoad(after).nodes).toEqual(after) +}) + +test('a house and garage wing require the grouped choice before moving their shared upper storey', () => { + const nodes = house(true) + const housePlate = base(nodes, 1) + const garagePlate = base(nodes, 1, 10) + const single = setFloorFoundation(nodes, { slabId: housePlate.id, patch: { thickness: 0.3 } }) + expect(single.changes).toEqual([]) + expect(single.conflicts?.[0]).toMatchObject({ + code: 'floor-foundation-shared-storey', + message: expect.stringContaining('Garage floor'), + }) + const grouped = setFloorFoundation(nodes, { + slabIds: [housePlate.id, garagePlate.id], + patch: { floorHeight: 0.3, thickness: 0.3 }, + }) + expect(grouped.conflicts).toEqual([]) + expect( + grouped.changes.find((change) => change.op === 'update' && change.id === garagePlate.id), + ).toMatchObject({ data: { elevation: 0.3, thickness: 0.3 } }) + const after = { ...nodes } + for (const change of grouped.changes) + if (change.op === 'update') + after[change.id] = { ...after[change.id], ...change.data } as AnyNode + expect((after[garagePlate.id] as SlabNode).thickness).toBeCloseTo(0.3) + expect((after[garagePlate.id] as SlabNode).floorHeight).toBeUndefined() +}) + +test('grouped upper floors refuse when a sibling cannot keep minimum thickness', () => { + const initial = house(true) + const housePlate = base(initial, 1) + const garagePlate = base(initial, 1, 10) + const nodes = { + ...initial, + [housePlate.id]: { ...housePlate, thickness: 0.35, elevation: 0.35 }, + } + const plan = setFloorFoundation(nodes, { + slabIds: [housePlate.id, garagePlate.id], + patch: { floorHeight: 0.05 }, + }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]).toMatchObject({ + code: 'floor-plate-thickness', + nodeIds: [garagePlate.id], + message: expect.stringContaining(garagePlate.id), + }) +}) + +test('upper height request thickens the plate without moving its underside or the storey below', () => { + const before = house() + const upper = base(before, 1) + const groundWall = before.wall_model_c_0_0_0 as WallNode + const oldUnderside = upper.elevation - upper.thickness + const oldBelowTop = getWallPlaneTop(groundWall, groundWall.parentId!, before) + const oldAbove = getLevelElevations(before).get('level_model_c_2')!.baseY + const plan = setFloorFoundation(before, { + slabId: upper.id, + patch: { floorHeight: upper.elevation + 0.3 }, + }) + expect(plan.conflicts).toEqual([]) + const draft = { ...before } + for (const change of plan.changes) + if (change.op === 'update') + draft[change.id] = { ...draft[change.id], ...change.data } as AnyNode + const after = reconcileStructureOnLoad(draft).nodes + const plate = after[upper.id] as SlabNode + expect(plate.floorHeight).toBeUndefined() + expect(plate.thickness).toBeCloseTo(upper.thickness + 0.3) + expect(plate.elevation - plate.thickness).toBeCloseTo(oldUnderside) + expect(getWallPlaneTop(groundWall, groundWall.parentId!, after)).toBeCloseTo(oldBelowTop) + expect(getLevelElevations(after).get('level_model_c_2')!.baseY).toBeCloseTo(oldAbove + 0.3) + expect(reconcileStructureOnLoad(after).nodes).toEqual(after) +}) + +test('legacy upper floorHeight becomes thickness on the first load', () => { + const initial = house() + const upper = base(initial, 1) + const legacy = { + ...initial, + [upper.id]: { ...upper, elevation: 0.35, floorHeight: 0.35 }, + } + const first = reconcileStructureOnLoad(legacy).nodes + const migrated = first[upper.id] as SlabNode + expect(migrated.floorHeight).toBeUndefined() + expect(migrated.elevation).toBeCloseTo(0.35) + expect(migrated.thickness).toBeCloseTo(0.35) + expect(migrated.elevation - migrated.thickness).toBeCloseTo(0) + expect(reconcileStructureOnLoad(first).nodes).toEqual(first) +}) + +test('a grouped choice may equalise previously unequal support lifts', () => { + const initial = house(true) + const housePlate = base(initial, 0) + const garagePlate = base(initial, 0, 10) + const nodes = { + ...initial, + [housePlate.id]: { ...housePlate, floorHeight: housePlate.elevation + 0.4 }, + } + const equalise = setFloorFoundation(nodes, { + slabId: garagePlate.id, + patch: { floorHeight: garagePlate.elevation + 0.4 }, + }) + expect(equalise.conflicts).toEqual([]) +}) + +test('a small overlap does not turn an upper plate into a ground foundation', () => { + const initial = house() + const upper = base(initial, 1) + const plate = { + ...upper, + polygon: [ + [3.2, 3.2], + [5.2, 3.2], + [5.2, 5.2], + [3.2, 5.2], + ] as [number, number][], + } + const nodes = Object.fromEntries( + Object.entries({ ...initial, [plate.id]: plate }).filter( + ([id, node]) => id !== 'level_model_c_2' && node.parentId !== 'level_model_c_2', + ), + ) as Record + expect(floorFootprintSupportClass(nodes, plate)).toBe('ground-bearing') + expect(floorPlateAtGroundContact(nodes, plate)).toBe(false) + expect(floorPlateHoldsUnderside(nodes, plate)).toBe(true) + expect(floorPlateGestureMinimum(nodes, plate)).toBeCloseTo(0.02) + const plan = setFloorFoundation(nodes, { slabId: plate.id, patch: { thickness: 0.3 } }) + expect(plan.conflicts).toEqual([]) + expect( + plan.changes.find((change) => change.op === 'update' && change.id === plate.id), + ).toMatchObject({ data: { elevation: 0.3, thickness: 0.3 } }) + const draft = { ...nodes } + for (const change of plan.changes) + if (change.op === 'update') + draft[change.id] = { ...draft[change.id], ...change.data } as AnyNode + const lower = initial.wall_model_c_0_0_0 as WallNode + expect(getWallPlaneTop(lower, lower.parentId!, draft)).toBeCloseTo( + getWallPlaneTop(lower, lower.parentId!, nodes), + ) + const height = setFloorFoundation(nodes, { + slabId: plate.id, + patch: { floorHeight: 0.35 }, + }) + expect(height.conflicts).toEqual([]) + expect( + height.changes.find((change) => change.op === 'update' && change.id === plate.id), + ).toMatchObject({ + data: { elevation: 0.35, thickness: 0.35, floorHeight: undefined }, + }) +}) + +test('plate paint does not change any storey displacement', () => { + const nodes = house() + const plate = base(nodes, 0) + const painted = { + ...nodes, + [plate.id]: { ...plate, slots: { ...plate.slots, surface: 'library:preset-oak' } }, + } + expect(changedLevelConstructionDisplacements(nodes, painted).size).toBe(0) +}) + +test('a level stair arrives at the upstairs walking surface after its plate lifts', () => { + const nodes = house() + const stair = StairNode.parse({ + id: 'stair_model_c', + parentId: 'level_model_c_0', + position: [2, 0, 2], + }) + nodes[stair.id] = stair + const level = nodes.level_model_c_0 as LevelNode + nodes[level.id] = { ...level, children: [...level.children, stair.id] } + const beforeRise = resolveStairTotalRise(stair, nodes, () => 0.05) + expect(beforeRise).toBeCloseTo(3) + const raised = apply(nodes, base(nodes, 1), 0.3) + const rise = resolveStairTotalRise(stair, raised, () => 0.05) + expect(rise).toBeCloseTo(3.25) + expect(rise + 0.05).toBeCloseTo( + getLevelElevations(raised).get('level_model_c_1')!.baseY - + getLevelElevations(raised).get('level_model_c_0')!.baseY + + (base(raised, 1).elevation ?? 0), + ) + const room = raised.zone_model_c_1_0 as ZoneNode + const withRoomStep = { + ...raised, + [room.id]: { ...room, floor: { ...room.floor, elevation: 0.65 } }, + } + expect(resolveStairTotalRise(stair, withRoomStep, () => 0.05)).toBeCloseTo(3.6) +}) + +test('a mezzanine ceiling keeps its identity when its supported floor lifts', () => { + const initial = house() + const mezzanine = ZoneNode.parse({ + id: 'zone_model_c_mezzanine', + parentId: 'level_model_c_1', + name: 'Mezzanine', + spaceRole: 'room', + hostZoneId: 'zone_model_c_1_0', + polygon: polygon(0.5, 2), + floor: { support: 'open', elevation: 0.7, thickness: 0.2 }, + }) + const level = initial.level_model_c_1 as LevelNode + const before = reconcileStructureOnLoad({ + ...initial, + [mezzanine.id]: mezzanine, + [level.id]: { ...level, children: [...level.children, mezzanine.id] }, + }).nodes + const ceiling = Object.values(before).find( + (node) => node.type === 'ceiling' && node.zoneId === mezzanine.id, + ) + expect(ceiling).toBeDefined() + const after = apply(before, base(before, 1), 0.3) + expect(after[ceiling!.id]).toMatchObject({ type: 'ceiling', zoneId: mezzanine.id }) + expect((after[mezzanine.id] as ZoneNode).floor?.elevation).toBeCloseTo(0.95) +}) + +test('upper height cannot reduce its plate below the minimum thickness', () => { + const nodes = house() + const wall = nodes.wall_model_c_0_0_0 as WallNode + const door = DoorNode.parse({ + id: 'door_model_c_lower', + parentId: wall.id, + wallId: wall.id, + verticalAnchor: 'floor', + position: [2, 1.4, 0], + height: 2.8, + }) + nodes[door.id] = door + nodes[wall.id] = { ...wall, children: [...wall.children, door.id] } + const plate = base(nodes, 1) + const plan = setFloorFoundation(nodes, { slabId: plate.id, patch: { floorHeight: -0.2 } }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.some((conflict) => conflict.code === 'floor-plate-thickness')).toBe(true) +}) + +test('lowering an upper plate keeps the explicit wall below unchanged', () => { + const initial = house() + const upper = base(initial, 1) + const raised = apply(initial, upper, 0.3) + const lowerWall = raised.wall_model_c_0_0_0 as WallNode + const nodes = { ...raised, [lowerWall.id]: { ...lowerWall, height: 2.95 } } + const plan = setFloorFoundation(nodes, { + slabId: upper.id, + patch: { floorHeight: 0.05 }, + }) + expect(plan.conflicts).toEqual([]) + const draft = { ...nodes } + for (const change of plan.changes) + if (change.op === 'update') + draft[change.id] = { ...draft[change.id], ...change.data } as AnyNode + expect(getWallPlaneTop(lowerWall, lowerWall.parentId!, draft)).toBeCloseTo( + getWallPlaneTop(lowerWall, lowerWall.parentId!, nodes), + ) +}) + +test('support follows actual lower plate coverage, including grade over a basement', () => { + const nodes = house(true) + const basement = LevelNode.parse({ + id: 'level_model_c_basement', + parentId: 'building_model_c', + level: -1, + height: 3, + }) + const room = { + ...(nodes.zone_model_c_0_0 as ZoneNode), + id: 'zone_model_c_basement', + parentId: basement.id, + } + const plate = { + ...base(nodes, 0), + id: 'slab_model_c_basement', + parentId: basement.id, + zoneIds: [room.id], + } as SlabNode + const graph = { ...nodes, [basement.id]: basement, [room.id]: room, [plate.id]: plate } + expect(floorFootprintSupportClass(graph, plate)).toBe('ground-bearing') + expect(floorFootprintSupportClass(graph, base(graph, 0))).toBe('supported') + expect(floorFootprintSupportClass(graph, base(graph, 0, 10))).toBe('ground-bearing') +}) + +test('ground and supported lifts add along a three-storey support path', () => { + const initial = house() + const ground = setFloorFoundation(initial, { + slabId: base(initial, 0).id, + patch: { floorHeight: 0.45 }, + }) + expect(ground.conflicts).toEqual([]) + const draft = { ...initial } + for (const change of ground.changes) + if (change.op === 'update') + draft[change.id] = { ...draft[change.id], ...change.data } as AnyNode + const raised = reconcileStructureOnLoad(draft).nodes + const both = apply(raised, base(raised, 1), 0.3) + expect(getLevelElevations(both).get('level_model_c_1')!.baseY).toBeCloseTo( + getLevelElevations(initial).get('level_model_c_1')!.baseY + 0.4, + ) + expect(getLevelElevations(both).get('level_model_c_2')!.baseY).toBeCloseTo( + getLevelElevations(initial).get('level_model_c_2')!.baseY + 0.65, + ) +}) diff --git a/packages/core/src/commands/structure/zone-crossings.ts b/packages/core/src/commands/structure/zone-crossings.ts new file mode 100644 index 0000000000..994eb88888 --- /dev/null +++ b/packages/core/src/commands/structure/zone-crossings.ts @@ -0,0 +1,191 @@ +import type { BoundaryNode } from '../../lib/room-topology-index' +import type { AnyNode, WallNode } from '../../schema' +import { + getWallArcData, + getWallCurveFrameAt, + getWallCurveLength, +} from '../../systems/wall/wall-curve' +import { at, boundaries, type Point, type StructureConflict, type StructureNodes } from './shared' +import { wallAttachments, wallStation } from './zone-wall-merge' + +export function boundaryStation(wall: BoundaryNode, point: Point) { + const arc = wall.type === 'wall' ? getWallArcData(wall) : null + if (!arc) return wallStation(wall, point) + let angle = + (Math.atan2(point[1] - arc.center.y, point[0] - arc.center.x) - arc.startAngle) * arc.direction + while (angle < -1e-8) angle += 2 * Math.PI + return angle / Math.abs(arc.delta) +} + +export function boundaryPoint(wall: BoundaryNode, t: number): Point { + if (wall.type === 'separator') return at(wall.start, wall.end, t) + const { point } = getWallCurveFrameAt(wall, t) + return [point.x, point.y] +} + +function crossings(a: BoundaryNode, b: BoundaryNode): Point[] { + const aa = a.type === 'wall' ? getWallArcData(a) : null + const bb = b.type === 'wall' ? getWallArcData(b) : null + let points: Point[] = [] + if (aa && bb) { + const dx = bb.center.x - aa.center.x, + dz = bb.center.y - aa.center.y, + distance = Math.hypot(dx, dz) + if ( + distance < 1e-8 || + distance > aa.radius + bb.radius + 1e-8 || + distance < Math.abs(aa.radius - bb.radius) - 1e-8 + ) + return [] + const along = (aa.radius ** 2 - bb.radius ** 2 + distance ** 2) / (2 * distance) + const offset = Math.sqrt(Math.max(0, aa.radius ** 2 - along ** 2)) + points = [-1, 1].map((side) => [ + aa.center.x + (along * dx) / distance - (side * offset * dz) / distance, + aa.center.y + (along * dz) / distance + (side * offset * dx) / distance, + ]) + } else if (aa || bb) { + const arc = (aa ?? bb)!, + line = aa ? b : a + const dx = line.end[0] - line.start[0], + dz = line.end[1] - line.start[1] + const x = line.start[0] - arc.center.x, + z = line.start[1] - arc.center.y + const length2 = dx * dx + dz * dz, + dot = x * dx + z * dz + const discriminant = dot * dot - length2 * (x * x + z * z - arc.radius * arc.radius) + if (discriminant < -1e-8 || length2 < 1e-12) return [] + points = [-1, 1].map((side) => + at(line.start, line.end, (-dot + side * Math.sqrt(Math.max(0, discriminant))) / length2), + ) + } else { + const ax = a.end[0] - a.start[0], + az = a.end[1] - a.start[1] + const bx = b.end[0] - b.start[0], + bz = b.end[1] - b.start[1] + const determinant = ax * bz - az * bx + if (Math.abs(determinant) < 1e-9) { + if (Math.abs((b.start[0] - a.start[0]) * az - (b.start[1] - a.start[1]) * ax) < 1e-8) + points = [a.start, a.end, b.start, b.end] + } else { + const t = ((b.start[0] - a.start[0]) * bz - (b.start[1] - a.start[1]) * bx) / determinant + points = [at(a.start, a.end, t)] + } + } + return points.filter((point) => + [a, b].every((wall) => { + const t = boundaryStation(wall, point) + return t >= -1e-6 && t <= 1 + 1e-6 + }), + ) +} + +export function dropCrossingCuts(nodes: StructureNodes, moving: Set, levelId: string) { + const walls = boundaries(nodes, levelId) + const cuts = new Map() + for (let i = 0; i < walls.length; i++) + for (let j = i + 1; j < walls.length; j++) { + const a = walls[i]!, + b = walls[j]! + if (!moving.has(a.id) && !moving.has(b.id)) continue + for (const point of crossings(a, b)) + for (const wall of [a, b]) { + const t = boundaryStation(wall, point) + if (t <= 1e-6 || t >= 1 - 1e-6) continue + const values = cuts.get(wall.id) ?? [] + if (!values.some((value) => Math.abs(value - t) < 1e-6)) values.push(t) + cuts.set( + wall.id, + values.sort((a, b) => a - b), + ) + } + } + return cuts +} + +export function clearOpeningCuts( + nodes: Record, + wall: WallNode, + cuts: number[], + force: boolean, +): StructureConflict | undefined { + const length = getWallCurveLength(wall) + const stations = cuts + .filter((t) => t > 1e-6 && t < 1 - 1e-6) + .map((t) => { + const point = boundaryPoint(wall, t) + const tangent = getWallCurveFrameAt(wall, t).tangent + const padding = boundaries(nodes, wall.parentId!).reduce((pad, other) => { + if (other.type !== 'wall' || other.id === wall.id) return pad + const station = boundaryStation(other, point) + if (station < -1e-6 || station > 1 + 1e-6) return pad + const frame = getWallCurveFrameAt(other, station) + if ( + Math.hypot(frame.point.x - point[0], frame.point.y - point[1]) > 1e-6 || + Math.abs(tangent.x * frame.tangent.y - tangent.y * frame.tangent.x) < 1e-6 + ) + return pad + return Math.max(pad, (other.thickness ?? 0.1) / 2) + }, 0) + return [t * length - padding, t * length + padding] as Point + }) + .sort((a, b) => a[0] - b[0]) + const openings = wallAttachments(nodes, wall).filter( + (node) => node.type === 'door' || node.type === 'window', + ) + const occupied = openings.filter((node) => + stations.some( + ([lo, hi]) => + hi > node.position[0] - node.width / 2 + 1e-5 && + lo < node.position[0] + node.width / 2 - 1e-5, + ), + ) + if (!occupied.length) return + const refused = (): StructureConflict => ({ + code: 'occupied-split', + nodeIds: [wall.id, ...occupied.map((node) => node.id)], + message: force + ? 'No space on the wall fits the opening clear of every crossing.' + : 'A crossing falls inside a door or window. Force moves the opening along its wall if it fits.', + }) + if (!force) return refused() + const fixed = openings + .filter((node) => !occupied.includes(node)) + .map((node) => [node.position[0] - node.width / 2, node.position[0] + node.width / 2] as Point) + occupied.sort((a, b) => b.width - a.width || a.id.localeCompare(b.id)) + const arrange = (index: number, placed: Point[]): number[] | undefined => { + const node = occupied[index] + if (!node) return [] + const half = node.width / 2 + const candidates = new Set() + let ranges: Point[] = [[half, length - half]] + for (const [lo, hi] of [...stations, ...placed]) + ranges = ranges.flatMap(([a, b]) => { + const left = lo - half, + right = hi + half + if (right <= a || left >= b) return [[a, b]] + return [ + [a, Math.min(b, left)], + [Math.max(a, right), b], + ].filter(([a, b]) => b! >= a! - 1e-8) as Point[] + }) + for (const [lo, hi] of ranges) + if (hi >= lo - 1e-8) { + candidates.add(Math.max(lo, Math.min(hi, node.position[0]))) + candidates.add(lo) + candidates.add(Math.max(lo, hi)) + } + // Trying interval edges as well as the nearest pose avoids rejecting a fit + // just because an earlier opening occupied the only space for another. + for (const station of [...candidates].sort( + (a, b) => Math.abs(a - node.position[0]) - Math.abs(b - node.position[0]) || a - b, + )) { + const rest = arrange(index + 1, [...placed, [station - half, station + half]]) + if (rest) return [station, ...rest] + } + } + const relocated = arrange(0, fixed) + if (!relocated) return refused() + occupied.forEach((node, i) => { + nodes[node.id] = { ...node, position: [relocated[i]!, node.position[1], node.position[2]] } + }) +} diff --git a/packages/core/src/commands/structure/zone-drop.ts b/packages/core/src/commands/structure/zone-drop.ts new file mode 100644 index 0000000000..55d10804fd --- /dev/null +++ b/packages/core/src/commands/structure/zone-drop.ts @@ -0,0 +1,77 @@ +import { area, containsPoint, difference, intersection } from '../../lib/polygon-boolean' +import { polygonInteriorPoint } from '../../lib/polygon-label' +import { extractRooms } from '../../lib/room-graph' +import type { AnyNode, WallNode, ZoneNode } from '../../schema' +import { at, boundaries, type Point, project } from './shared' +import { collinearOverlap, wallStation } from './zone-wall-merge' + +export function snapDroppedWalls( + nodes: Record, + moving: Set, + levelId: string, +) { + for (const id of moving) { + const wall = nodes[id] + if (wall?.type !== 'wall') continue + const destination = Object.values(nodes) + .filter( + (node): node is WallNode => + node.type === 'wall' && + node.parentId === levelId && + !moving.has(node.id) && + collinearOverlap(wall, node), + ) + .sort( + (a, b) => + project(wall.start, a.start, a.end).distance - + project(wall.start, b.start, b.end).distance || a.id.localeCompare(b.id), + )[0] + if (!destination) continue + const snap = (point: Point): Point => { + const onWall = project(point, wall.start, wall.end) + if (onWall.distance > 1e-6) return point + return at(destination.start, destination.end, wallStation(destination, point)) + } + for (const movingId of moving) { + const node = nodes[movingId]! + if (node.type === 'wall' || node.type === 'separator') + nodes[movingId] = { ...node, start: snap(node.start), end: snap(node.end) } + } + } +} + +export function preserveDroppedRoomSeeds(nodes: Record, placedZoneId: string) { + const placed = nodes[placedZoneId] as ZoneNode + const dropped = [{ outer: placed.polygon, holes: placed.holes ?? [] }] + const faces = extractRooms(boundaries(nodes, placed.parentId!)).map((face) => ({ + face, + polygon: [{ outer: face.referencePolygon, holes: face.holes }], + })) + for (const zone of Object.values(nodes)) { + if (zone.type !== 'zone' || zone.parentId !== placed.parentId) continue + const moving = zone.id === placedZoneId + if (!moving && zone.seed && !containsPoint(dropped, zone.seed)) continue + const old = [{ outer: zone.polygon, holes: zone.holes ?? [] }] + const candidates = faces + .map(({ face, polygon }) => ({ + face, + overlap: area(intersection(polygon, old)), + outside: area(intersection(polygon, difference(old, dropped))), + size: area(polygon), + })) + .filter(({ overlap }) => overlap > 1e-6) + // Prefer whole resulting faces inside the owner's intent; snapped boundaries + // may protrude slightly, so overlap supplies a fallback when none fit exactly. + const owned = candidates.filter(({ overlap, size }) => overlap >= size - 1e-5) + const available = owned.length ? owned : candidates + const outside = moving ? [] : available.filter(({ outside, size }) => outside >= size - 1e-5) + const target = (outside.length ? outside : available).sort( + (a, b) => b.overlap - a.overlap || a.face.id.localeCompare(b.face.id), + )[0] + if (!target) continue + const polygon = { polygon: target.face.referencePolygon, holes: target.face.holes } + if (zone.seed && containsPoint([{ outer: polygon.polygon, holes: polygon.holes }], zone.seed)) + continue + nodes[zone.id] = { ...zone, seed: polygonInteriorPoint(polygon) } + } +} diff --git a/packages/core/src/commands/structure/zone-insertion.ts b/packages/core/src/commands/structure/zone-insertion.ts new file mode 100644 index 0000000000..b47c085846 --- /dev/null +++ b/packages/core/src/commands/structure/zone-insertion.ts @@ -0,0 +1,243 @@ +import type { BoundaryNode } from '../../lib/room-topology-index' +import type { AnyNode, AnyNodeId, WallNode } from '../../schema' +import { getWallArcData, getWallCurveLength } from '../../systems/wall/wall-curve' +import { planWallInsertion } from '../../systems/wall/wall-topology' +import { boundaries, type StructureConflict, type StructureMintId } from './shared' +import { + boundaryPoint, + boundaryStation, + clearOpeningCuts, + dropCrossingCuts, +} from './zone-crossings' +import { + remapWallReferences, + splitCollinearWalls, + wallAttachments, + wallSlice, +} from './zone-wall-merge' + +export function insertDroppedBoundaries( + nodes: Record, + moving: Set, + levelId: string, + idMap: Record, + mintId: StructureMintId, + force: boolean, + stationary: Set, +): StructureConflict | undefined { + const replace = ( + source: BoundaryNode, + pieces: Array<{ start: [number, number]; end: [number, number]; id: string }>, + ) => { + const ordered = pieces.sort( + (a, b) => boundaryStation(source, a.start) - boundaryStation(source, b.start), + ) + const ranges = ordered.map( + (piece) => + [boundaryStation(source, piece.start), boundaryStation(source, piece.end)] as const, + ) + if (source.type === 'wall') { + const conflict = clearOpeningCuts(nodes, source, ranges.flat(), force) + if (conflict) return conflict + } + const targets = ordered.map((piece, i): BoundaryNode => { + const id = i === 0 ? source.id : source.type === 'wall' ? piece.id : mintId('separator') + const [lo, hi] = ranges[i]! + return source.type === 'wall' + ? wallSlice(source, piece.start, piece.end, id, [lo, hi]) + : { ...source, id: id as typeof source.id, start: piece.start, end: piece.end } + }) + const children = source.type === 'wall' ? wallAttachments(nodes, source) : [] + for (const child of children) { + const position = + 'position' in child && Array.isArray(child.position) ? child.position : undefined + const length = getWallCurveLength(source as WallNode) + const t = position ? position[0] / length : 0.5 + const index = Math.max( + 0, + ranges.findIndex(([lo, hi]) => t >= lo - 1e-6 && t <= hi + 1e-6), + ) + const host = targets[index]! + nodes[child.id] = { + ...child, + parentId: host.id, + ...('wallId' in child ? { wallId: host.id } : {}), + ...(position + ? { position: [position[0] - ranges[index]![0] * length, position[1], position[2]] } + : {}), + ...('wallT' in child + ? { wallT: (t - ranges[index]![0]) / (ranges[index]![1] - ranges[index]![0]) } + : {}), + } as AnyNode + } + if (source.type === 'wall') remapWallReferences(nodes, source, targets as WallNode[]) + else + for (const zone of Object.values(nodes)) + if (zone.type === 'zone' && zone.boundarySeparatorIds.includes(source.id)) + nodes[zone.id] = { + ...zone, + boundarySeparatorIds: zone.boundarySeparatorIds.flatMap((id) => + id === source.id ? targets.map((node) => node.id) : [id], + ), + } + for (const [key, values] of Object.entries(idMap)) + idMap[key] = [ + ...new Set( + values.flatMap((id) => (id === source.id ? targets.map((node) => node.id) : [id])), + ), + ] + idMap[source.id] ??= targets.map((node) => node.id) + delete nodes[source.id] + for (const target of targets) nodes[target.id] = target + if (moving.has(source.id)) for (const target of targets) moving.add(target.id) + if (stationary.has(source.id)) for (const target of targets) stationary.add(target.id) + } + const bounds = (wall: BoundaryNode) => { + const points = [wall.start, wall.end] + const arc = wall.type === 'wall' ? getWallArcData(wall) : null + if (arc) + for (const angle of [0, Math.PI / 2, Math.PI, -Math.PI / 2]) { + const point: [number, number] = [ + arc.center.x + arc.radius * Math.cos(angle), + arc.center.y + arc.radius * Math.sin(angle), + ] + const t = boundaryStation(wall, point) + if (t >= 0 && t <= 1) points.push(point) + } + return [ + Math.min(...points.map((p) => p[0])), + Math.min(...points.map((p) => p[1])), + Math.max(...points.map((p) => p[0])), + Math.max(...points.map((p) => p[1])), + ] as const + } + const curves = boundaries(nodes, levelId) + .filter((node) => moving.has(node.id) && node.type === 'wall' && node.curveOffset) + .map(bounds) + const queue: string[] = boundaries(nodes, levelId) + .filter((node) => { + if (moving.has(node.id)) return true + const box = bounds(node) + return curves.some( + (curve) => + box[0] <= curve[2] + 1e-6 && + box[2] >= curve[0] - 1e-6 && + box[1] <= curve[3] + 1e-6 && + box[3] >= curve[1] - 1e-6, + ) + }) + .map((node) => node.id) + while (queue.length) { + const source = nodes[queue.shift()!] + if ( + !source || + (source.type !== 'wall' && source.type !== 'separator') || + (source.type === 'wall' && source.curveOffset) + ) + continue + const others = boundaries(nodes, levelId).filter( + (node) => node.id !== source.id && (moving.has(source.id) || moving.has(node.id)), + ) + // Opening clearance is checked before geometry planning. Virtual boundaries use + // the same crossing planner; their split pieces are restored as separators. + const geometry = Object.fromEntries( + others.map((node) => [node.id, { ...node, type: 'wall', children: [] }]), + ) as Record + const inserted = planWallInsertion(geometry, { + levelId: source.parentId! as AnyNodeId, + start: source.start, + end: source.end, + joinRadius: 1e-7, + wallDefaults: { ...source, type: 'wall' } as Partial, + mintId: () => mintId('wall'), + }) + if (!inserted.ok) continue + const { plan } = inserted + if (!plan.changes.delete.length && plan.insertedWalls.length === 1) continue + const replacements = plan.changes.create + .map(({ node }) => node as WallNode) + .filter((node) => !plan.insertedWalls.some((inserted) => inserted.id === node.id)) + for (const id of plan.changes.delete) { + const original = nodes[id] as BoundaryNode + const pieces = replacements.filter((piece) => + [piece.start, piece.end].every((point) => { + const t = boundaryStation(original, point), + onLine = boundaryPoint(original, t) + return ( + t >= -1e-6 && + t <= 1 + 1e-6 && + Math.hypot(point[0] - onLine[0], point[1] - onLine[1]) < 1e-5 + ) + }), + ) + if (!pieces.length) throw Error(`Missing crossing replacements for ${id}`) + const conflict = replace(original, pieces) + if (conflict) return conflict + if (moving.has(id)) queue.push(...(idMap[id] ?? [])) + } + const conflict = replace(source, plan.insertedWalls) + if (conflict) return conflict + if (moving.has(source.id)) queue.push(...(idMap[source.id] ?? [])) + } + // The insertion primitive draws straight segments. Arc/arc crossings and + // sub-centimetre remnants still need exact cuts on their original curves. + for (const [id, cuts] of dropCrossingCuts(nodes, moving, levelId)) { + const source = nodes[id] as BoundaryNode + const parameters = [0, ...cuts, 1] + const conflict = replace( + source, + parameters.slice(1).map((hi, i) => ({ + id: mintId('wall'), + start: boundaryPoint(source, parameters[i]!), + end: boundaryPoint(source, hi), + })), + ) + if (conflict) return conflict + } + const samePoint = (a: [number, number], b: [number, number]) => + Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-6 + const segments = boundaries(nodes, levelId) + for (let i = 0; i < segments.length; i++) + for (let j = i + 1; j < segments.length; j++) { + let a = nodes[segments[i]!.id] as BoundaryNode | undefined + let b = nodes[segments[j]!.id] as BoundaryNode | undefined + if ( + !a || + !b || + (!moving.has(a.id) && !moving.has(b.id)) || + (a.type === 'wall' && a.curveOffset) || + (b.type === 'wall' && b.curveOffset) + ) + continue + if ( + !( + (samePoint(a.start, b.start) && samePoint(a.end, b.end)) || + (samePoint(a.start, b.end) && samePoint(a.end, b.start)) + ) + ) + continue + if (a.type === 'wall' && b.type === 'wall') { + if (stationary.has(b.id) && !stationary.has(a.id)) [a, b] = [b, a] + splitCollinearWalls(nodes, b as WallNode, a as WallNode, mintId) + } else { + if (b.type === 'wall' || (a.type === 'separator' && stationary.has(b.id))) [a, b] = [b, a] + for (const zone of Object.values(nodes)) + if (zone.type === 'zone' && zone.boundarySeparatorIds.includes(b.id)) + nodes[zone.id] = { + ...zone, + boundarySeparatorIds: zone.boundarySeparatorIds.flatMap((id) => + id === b!.id ? (a!.type === 'separator' ? [a!.id] : []) : [id], + ), + boundaryWallIds: + a.type === 'wall' + ? [...new Set([...zone.boundaryWallIds, a.id])] + : zone.boundaryWallIds, + } + delete nodes[b.id] + } + for (const [id, targets] of Object.entries(idMap)) + idMap[id] = [...new Set(targets.map((target) => (target === b!.id ? a!.id : target)))] + idMap[b.id] ??= [a.id] + if (moving.has(b.id)) moving.add(a.id) + } +} diff --git a/packages/core/src/commands/structure/zone-legacy-transform.test.ts b/packages/core/src/commands/structure/zone-legacy-transform.test.ts new file mode 100644 index 0000000000..edaaa2a0fb --- /dev/null +++ b/packages/core/src/commands/structure/zone-legacy-transform.test.ts @@ -0,0 +1,36 @@ +import { afterEach, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import useScene from '../../store/use-scene' +import { transformZone } from './transform-zone' + +afterEach(() => useScene.getState().unloadScene()) + +test('moving a room in a legacy house tolerates another zone without boundary lists', () => { + const source = JSON.parse( + readFileSync( + new URL('../../utils/__fixtures__/project_hrY3qVVq16yo5Out.json', import.meta.url), + 'utf8', + ), + ) + useScene.getState().setScene(source, []) + const nodes = { ...useScene.getState().nodes } + const pool = Object.values(nodes).find( + (node) => node.type === 'zone' && node.name === 'Swimming Pool', + ) + const room = Object.values(nodes).find( + (node) => node.type === 'zone' && node.name === 'Living Room', + ) + // Loading fills the default lists; a graph from another writer may still omit them. + expect(pool?.type).toBe('zone') + const { boundaryWallIds: _walls, ...bare } = pool as Record + nodes[pool!.id] = bare as never + expect(room?.type).toBe('zone') + let serial = 0 + const plan = transformZone(nodes, { + zoneId: room!.id, + translate: [0.1, 0], + mintId: (kind) => `${kind}_legacy_move_${serial++}`, + }) + expect(plan.conflicts).toBeUndefined() + expect(plan.changes.length).toBeGreaterThan(0) +}) diff --git a/packages/core/src/commands/structure/zone-transform-content.ts b/packages/core/src/commands/structure/zone-transform-content.ts new file mode 100644 index 0000000000..65306793e7 --- /dev/null +++ b/packages/core/src/commands/structure/zone-transform-content.ts @@ -0,0 +1,139 @@ +import { containsPoint, difference, distanceToBoundary, union } from '../../lib/polygon-boolean' +import type { AnyNode, WallNode, ZoneNode } from '../../schema' +import { isDerivedNode } from '../../store/derived-node-guard' +import { calculateLevelMiters, getWallPlanFootprint } from '../../systems/wall/wall-footprint' +import { containedMezzanines, electedIntentPlate, isFloorPlacedIntent } from './mezzanine-content' +import { type Point, project, roomFace, type StructureNodes } from './shared' + +const isIntent = (node: AnyNode): boolean => !isDerivedNode(node) + +export function collectTransformContents(nodes: StructureNodes, zone: ZoneNode) { + if (zone.floor?.support === 'open') { + return new Set( + Object.values(nodes) + .filter((node) => { + if (!isIntent(node)) return false + if (node.type === 'floor-opening' && node.hostZoneId === zone.id) return true + const parent = nodes[node.parentId ?? ''] + if (parent?.type === 'ceiling' && parent.zoneId === zone.id) return true + return ( + node.parentId === zone.parentId && + isFloorPlacedIntent(node) && + !!electedIntentPlate(nodes, node)?.zoneIds?.includes(zone.id) + ) + }) + .map((node) => node.id), + ) + } + const ids = new Set(containedMezzanines(nodes, zone).map((node) => node.id as string)) + const face = roomFace(nodes, zone) + const footprint = [ + { outer: face?.referencePolygon ?? zone.polygon, holes: face?.holes ?? zone.holes }, + ] + const walls = Object.values(nodes).filter( + (node): node is WallNode => node.type === 'wall' && node.parentId === zone.parentId, + ) + const boundaryWalls = walls.filter((wall) => + face?.spans.some((span) => span.boundaryId === wall.id), + ) + const miters = calculateLevelMiters(walls) + const clear = difference( + footprint, + union( + boundaryWalls.map((wall) => + getWallPlanFootprint(wall, miters).map(({ x, y }): Point => [x, y]), + ), + ), + ) + const inside = (point: Point) => { + if (!containsPoint(footprint, point)) return false + if (containsPoint(clear, point)) return true + const nearest = boundaryWalls + .map((wall) => ({ wall, distance: project(point, wall.start, wall.end).distance })) + .sort((a, b) => a.distance - b.distance)[0] + return ( + !!nearest && distanceToBoundary(clear, point) <= (nearest.wall.thickness ?? 0.1) / 2 + 1e-6 + ) + } + const furnishingKinds = new Set(['item', 'procedural-item', 'cabinet', 'shelf', 'stair']) + for (const node of Object.values(nodes)) { + if (node.parentId === zone.parentId && isIntent(node)) { + if ( + node.type === 'floor-opening' && + !node.hostZoneId && + node.polygon.every((point) => containsPoint(clear, point)) + ) + ids.add(node.id) + if ( + furnishingKinds.has(node.type) && + 'position' in node && + Array.isArray(node.position) && + !('wallId' in node && node.wallId) && + inside([node.position[0], node.position[2]]) + ) + ids.add(node.id) + if ( + (node.type === 'slab' || node.type === 'ceiling') && + node.polygon.length >= 3 && + node.polygon.every((p) => containsPoint(footprint, p)) + ) + ids.add(node.id) + } + const parent = node.parentId ? nodes[node.parentId] : undefined + if ( + parent && + isDerivedNode(parent) && + furnishingKinds.has(node.type) && + 'position' in node && + Array.isArray(node.position) && + parent.parentId === zone.parentId && + inside([node.position[0], node.position[2]]) + ) + ids.add(node.id) + } + return ids +} + +export function includeDescendants(nodes: StructureNodes, ids: Set) { + let changed = true + while (changed) { + changed = false + for (const node of Object.values(nodes)) + if (!isDerivedNode(node) && node.parentId && ids.has(node.parentId) && !ids.has(node.id)) { + ids.add(node.id) + changed = true + } + } +} + +export function repairTransformChildren(nodes: Record, before: StructureNodes) { + const affected = new Set() + const byParent = new Map() + for (const node of Object.values(nodes)) { + if (node.parentId) { + const children = byParent.get(node.parentId) ?? [] + children.push(node.id) + byParent.set(node.parentId, children) + } + if (node !== before[node.id]) { + affected.add(node.id) + if (node.parentId) affected.add(node.parentId) + const previousParent = before[node.id]?.parentId + if (previousParent) affected.add(previousParent) + } + } + for (const node of Object.values(before)) + if (!nodes[node.id] && node.parentId) affected.add(node.parentId) + for (const id of affected) { + const node = nodes[id] + if (!node || isDerivedNode(node) || !('children' in node) || !Array.isArray(node.children)) + continue + const children = new Set(byParent.get(id) ?? []) + const ordered = [ + ...node.children.filter((id) => children.has(id)), + ...[...children].filter((id) => !node.children.includes(id as never)), + ] + if (JSON.stringify(ordered) !== JSON.stringify(node.children)) + nodes[node.id] = { ...node, children: ordered } as AnyNode + } +} diff --git a/packages/core/src/commands/structure/zone-transform.test.ts b/packages/core/src/commands/structure/zone-transform.test.ts new file mode 100644 index 0000000000..af605894f4 --- /dev/null +++ b/packages/core/src/commands/structure/zone-transform.test.ts @@ -0,0 +1,1536 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { area, containsPoint } from '../../lib/polygon-boolean' +import { initSpaceDetectionSync } from '../../lib/space-detection' +import { reconcileLevelStructure } from '../../lib/structure-kernel' +import { shelfRecipe } from '../../procedural-items/fixtures' +import { ProceduralItemNode } from '../../procedural-items/node' +import { + BuildingNode, + CabinetNode, + ConstructionDimensionNode, + DoorNode, + GuideNode, + ItemNode, + LevelNode, + MeasurementNode, + RoofNode, + RoofSegmentNode, + ScanNode, + SeparatorNode, + ShelfNode, + SlabNode, + SpawnNode, + StairNode, + WallNode, + WindowNode, + type ZoneNode, +} from '../../schema' +import { isDerivedNode } from '../../store/derived-node-guard' +import { subscribeSceneCommits } from '../../store/history-control' +import useScene, { clearSceneHistory } from '../../store/use-scene' +import { getWallFaceLine } from '../../systems/wall/wall-frame' +import { + applyZoneTransformPlan, + createZone, + divideZone, + duplicateZone, + lockOutsideFaces, + resolveZoneTransformHosts, + rotateZone, + setWallGeometry, + transformZone, +} from './index' +import { + applyToScratch, + roomFace, + type StructureNodes, + type StructurePlan, + structureChangeBatch, +} from './shared' + +const levelId = 'level_transform' +function mint() { + let i = 0 + return (kind: string) => `${kind}_transform${++i}` +} +const rectangle = (x = 0, z = 0, w = 4, h = 4): [number, number][] => [ + [x, z], + [x + w, z], + [x + w, z + h], + [x, z + h], +] +function reconcile(before: StructureNodes, plan: StructurePlan) { + expect(plan.conflicts).toBeUndefined() + const scratch = applyToScratch(before, structureChangeBatch(plan.changes)) + let i = 0 + const result = reconcileLevelStructure({ + nodes: scratch, + previousNodes: before, + levelId, + mintId: (kind) => { + let id: string + do { + id = `${kind}_derived${++i}` + } while (scratch[id]) + return id + }, + }) + const derived = applyToScratch(scratch, structureChangeBatch(result.patches)) + return applyToScratch(derived, structureChangeBatch(resolveZoneTransformHosts(derived, plan))) +} +function fixture() { + const mintId = mint() + const level = LevelNode.parse({ id: levelId, parentId: 'building_transform' }) + const building = BuildingNode.parse({ id: 'building_transform', children: [levelId] }) + const initial = { [level.id]: level, [building.id]: building } + const created = createZone(initial, { + levelId, + polygon: rectangle(), + enclose: true, + name: 'Kitchen', + mintId, + }) + return { nodes: reconcile(initial, created), zoneId: created.zoneId, mintId } +} +function addRoom( + nodes: StructureNodes, + mintId: ReturnType, + polygon: [number, number][], +) { + const created = createZone(nodes, { levelId, polygon, enclose: true, mintId }) + return { nodes: reconcile(nodes, created), zoneId: created.zoneId } +} +const asset = { + id: 'chair', + category: 'furniture', + name: 'Chair', + thumbnail: '', + src: 'https://example.com/chair.glb', +} +function door(nodes: StructureNodes, wall: WallNode, id: string, station = 2) { + const node = DoorNode.parse({ id, parentId: wall.id, wallId: wall.id, position: [station, 0, 0] }) + return { ...nodes, [wall.id]: { ...wall, children: [...wall.children, node.id] }, [id]: node } +} +function rooms(nodes: StructureNodes) { + return Object.values(nodes).filter((n): n is ZoneNode => n.type === 'zone') +} +function walls(nodes: StructureNodes) { + return Object.values(nodes).filter((n): n is WallNode => n.type === 'wall') +} +function assertEnclosed(nodes: StructureNodes, count: number) { + expect(rooms(nodes)).toHaveLength(count) + for (const zone of rooms(nodes)) expect(roomFace(nodes, zone)).toBeDefined() +} +function expectNoDuplicateBoundaries(nodes: StructureNodes) { + const keys = Object.values(nodes) + .filter((node) => node.type === 'wall' || node.type === 'separator') + .map((node) => + [node.start, node.end] + .map((point) => point.map((value) => value.toFixed(6)).join(',')) + .sort() + .join('|'), + ) + expect(new Set(keys).size).toBe(keys.length) +} +let stop = () => {} +afterEach(() => { + stop() + useScene.temporal.getState().resume() +}) +globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} + +function mount(nodes: StructureNodes) { + useScene.setState({ + nodes, + rootNodeIds: ['building_transform'], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) + clearSceneHistory() +} + +describe('room transforms', () => { + test('move isolated room keeps identity, moves contents and re-derives plate and ceiling in one undo step', () => { + const { nodes, zoneId, mintId } = fixture() + const wall = walls(nodes)[0]! + const withDoor = door(nodes, wall, 'door_moving') + const item = ItemNode.parse({ + id: 'item_moving', + parentId: levelId, + position: [1, 0, 2], + children: ['item_nested'], + asset, + }) + const nested = ItemNode.parse({ + id: 'item_nested', + parentId: item.id, + position: [0, 1, 0], + asset, + }) + useScene.setState({ + nodes: { ...withDoor, [item.id]: item, [nested.id]: nested }, + rootNodeIds: ['building_transform'], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + stop = initSpaceDetectionSync(useScene, { + getState: () => ({ spaces: {}, setSpaces: () => {} }), + }) + clearSceneHistory() + const before = useScene.getState().nodes + const plan = transformZone(before, { zoneId, translate: [10, 3], mintId }) + expect( + plan.changes.every((change) => + change.op === 'create' ? !isDerivedNode(change.node) : !isDerivedNode(before[change.id]!), + ), + ).toBe(true) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const after = useScene.getState().nodes + expect(after[zoneId]).toMatchObject({ name: 'Kitchen', seed: [12, 5] }) + expect(after[item.id]).toMatchObject({ position: [11, 0, 5] }) + expect(after[nested.id]).toMatchObject({ position: nested.position, parentId: item.id }) + expect(after['door_moving']).toMatchObject({ parentId: wall.id, position: [2, 0, 0] }) + for (const node of Object.values(after)) + if (isDerivedNode(node) && 'polygon' in node) + expect(Math.min(...node.polygon.map((p) => p[0]))).toBeGreaterThan(9) + assertEnclosed(after, 1) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + }) + test('move shared wall leaves neighbour and door intact and takes a plain enclosed copy', () => { + const { nodes, zoneId, mintId } = fixture() + const adjacent = addRoom(nodes, mintId, rectangle(4)) + const shared = walls(adjacent.nodes).find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! + const graph = door(adjacent.nodes, shared, 'door_neighbour') + const plan = transformZone(graph, { zoneId, translate: [-10, 0], mintId }) + const after = reconcile(graph, plan) + expect(after[shared.id]).toMatchObject({ + start: shared.start, + end: shared.end, + children: ['door_neighbour'], + }) + expect(after['door_neighbour']).toEqual(graph['door_neighbour']) + const copy = after[plan.idMap[shared.id]![0]!] as WallNode + expect(copy.id).not.toBe(shared.id) + expect(copy.children).toEqual([]) + expect(copy.start[0]).toBe(-6) + expect(after[adjacent.zoneId]).toMatchObject({ + polygon: (graph[adjacent.zoneId] as ZoneNode).polygon, + }) + assertEnclosed(after, 2) + }) + test('drop collinear walls preserves destination ID and hosted children on both sides, including reversed frames', () => { + const { nodes, zoneId, mintId } = fixture() + const adjacent = addRoom(nodes, mintId, rectangle(10)) + const placed = walls(adjacent.nodes).find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! + const destination = walls(adjacent.nodes).find( + (wall) => wall.start[0] === 10 && wall.end[0] === 10, + )! + let graph = door(adjacent.nodes, placed, 'door_placed', 1) + graph = door(graph, destination, 'door_destination', 1) + const plan = transformZone(graph, { zoneId, translate: [6, 0], mintId }) + const after = reconcile(graph, plan) + expect(after[placed.id]).toBeUndefined() + expect(after[destination.id]).toMatchObject({ start: destination.start, end: destination.end }) + expect((after[destination.id] as WallNode).children.sort()).toEqual([ + 'door_destination', + 'door_placed', + ]) + expect(after['door_destination']).toMatchObject({ position: [1, 0, 0] }) + expect(after['door_placed']).toMatchObject({ + parentId: destination.id, + wallId: destination.id, + position: [3, 0, -0], + }) + assertEnclosed(after, 2) + useScene.setState({ + nodes: graph, + rootNodeIds: ['building_transform'], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + stop = initSpaceDetectionSync(useScene, { + getState: () => ({ spaces: {}, setSpaces: () => {} }), + }) + clearSceneHistory() + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const committed = useScene.getState().nodes + expect(committed['door_placed']).toMatchObject({ parentId: destination.id }) + expect(committed['door_destination']).toBeDefined() + assertEnclosed(committed, 2) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(graph) + }) + test('partial collinear drop retains destination on overlap and children on both leftover spans', () => { + const { nodes, zoneId, mintId } = fixture() + const adjacent = addRoom(nodes, mintId, rectangle(10, 2, 4, 4)) + const placed = walls(adjacent.nodes).find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! + const destination = walls(adjacent.nodes).find( + (wall) => wall.start[0] === 10 && wall.end[0] === 10, + )! + let graph = door(adjacent.nodes, placed, 'door_placed_tail', 1) + graph = door(graph, placed, 'door_placed_shared', 3) + graph = door(graph, destination, 'door_destination_tail', 1) + const after = reconcile(graph, transformZone(graph, { zoneId, translate: [6, 0], mintId })) + expect(after[destination.id]).toMatchObject({ start: [10, 4], end: [10, 2] }) + for (const id of ['door_placed_tail', 'door_placed_shared', 'door_destination_tail']) { + const child = after[id]! + expect(child).toBeDefined() + expect((after[child.parentId!] as WallNode).children).toContain(id) + } + expect(after['door_placed_shared']!.parentId).toBe(destination.id) + assertEnclosed(after, 2) + }) + test('rotate 90 degrees about room centre rotates regions and free items while keeping hosted local poses', () => { + const { nodes, zoneId, mintId } = fixture() + const zone = nodes[zoneId] as ZoneNode + const item = ItemNode.parse({ + id: 'item_rotated', + parentId: levelId, + position: [1, 0, 1], + asset, + }) + const graph = { + ...nodes, + [zoneId]: { + ...zone, + floor: { + finish: 'wood', + regions: [{ id: 'region_one', polygon: rectangle(0, 0, 1, 1), finish: 'tile' }], + }, + }, + [item.id]: item, + } + const after = reconcile( + graph, + transformZone(graph, { zoneId, rotate: { angle: Math.PI / 2 }, mintId }), + ) + expect(after[item.id]).toMatchObject({ rotation: [0, Math.PI / 2, 0] }) + const position = (after[item.id] as ItemNode).position + expect(position[0]).toBeCloseTo(1) + expect(position[2]).toBeCloseTo(3) + const region = (after[zoneId] as ZoneNode).floor!.regions![0]! + expect(region.polygon).toEqual( + expect.arrayContaining([ + [0, 4], + [1, 4], + [1, 3], + [0, 3], + ]), + ) + assertEnclosed(after, 1) + }) + test('duplicate next to source remaps manual support and deck IDs and never authors derived nodes', () => { + const { nodes, zoneId, mintId } = fixture() + const slab = SlabNode.parse({ + id: 'slab_manual', + parentId: levelId, + polygon: rectangle(1, 1, 1, 1), + elevation: 0.5, + }) + const item = ItemNode.parse({ + id: 'item_copy', + parentId: levelId, + position: [1.5, 0, 1.5], + supportSlabId: slab.id, + children: ['item_child'], + asset, + }) + const child = ItemNode.parse({ + id: 'item_child', + parentId: item.id, + position: [0, 1, 0], + asset, + }) + const stair = StairNode.parse({ + id: 'stair_copy', + parentId: levelId, + position: [2, 0, 2], + deckSlabId: slab.id, + supportSlabId: slab.id, + }) + const graph = { + ...nodes, + [slab.id]: slab, + [item.id]: item, + [child.id]: child, + [stair.id]: stair, + } + const before = JSON.stringify(graph) + const plan = duplicateZone(graph, { zoneId, translate: [6, 0], mintId }) + expect(JSON.stringify(graph)).toBe(before) + expect( + plan.changes.some((change) => change.op === 'create' && isDerivedNode(change.node)), + ).toBe(false) + const after = reconcile(graph, plan) + expect(after[zoneId]).toEqual(graph[zoneId]) + for (const wall of walls(graph)) expect(after[wall.id]).toEqual(wall) + const copied = after[plan.idMap[item.id]![0]!] as ItemNode + expect(copied.supportSlabId).toBe(plan.idMap[slab.id]![0]) + expect(after[plan.idMap[stair.id]![0]!]).toMatchObject({ + deckSlabId: plan.idMap[slab.id]![0], + supportSlabId: plan.idMap[slab.id]![0], + }) + expect(after[plan.idMap[child.id]![0]!]).toMatchObject({ + parentId: copied.id, + position: child.position, + }) + assertEnclosed(after, 2) + }) + test('crossing a neighbour splits both walls and re-derives rooms without overlap conflicts', () => { + const { nodes, zoneId, mintId } = fixture() + const neighbour = addRoom(nodes, mintId, rectangle(8)) + const graph = { + ...neighbour.nodes, + [neighbour.zoneId]: { ...neighbour.nodes[neighbour.zoneId], name: 'Bedroom' }, + } as StructureNodes + mount(graph) + const plan = transformZone(graph, { zoneId, translate: [9, 1], mintId }) + expect(plan.conflicts).toBeUndefined() + applyZoneTransformPlan(plan) + const after = useScene.getState().nodes + expect(walls(after)).toHaveLength(12) + assertEnclosed(after, 3) + expect(after[zoneId]).toMatchObject({ name: 'Kitchen' }) + expect(after[neighbour.zoneId]).toMatchObject({ name: 'Bedroom' }) + expect(area([{ outer: (after[zoneId] as ZoneNode).polygon, holes: [] }])).toBeCloseTo(9) + expect(area([{ outer: (after[neighbour.zoneId] as ZoneNode).polygon, holes: [] }])).toBeCloseTo( + 7, + ) + for (const point of [ + [12, 1], + [9, 4], + ]) + expect( + walls(after).filter((wall) => + [wall.start, wall.end].some((end) => JSON.stringify(end) === JSON.stringify(point)), + ), + ).toHaveLength(4) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(graph) + }) + test('lock outside faces then change thickness preserves the four outer dimensions', () => { + const { nodes, mintId } = fixture() + const before = walls(nodes).map((wall) => ({ + start: { x: wall.start[0], y: wall.start[1] }, + end: { x: wall.end[0], y: wall.end[1] }, + })) + const plan = lockOutsideFaces(nodes, { levelId }) + let after = reconcile(nodes, plan) + expect(walls(after).every((wall) => wall.justification === 'a')).toBe(true) + for (const wall of walls(after)) + after = reconcile(after, setWallGeometry(after, { wallId: wall.id, thickness: 0.5, mintId })) + for (const [i, wall] of walls(after).entries()) { + const line = getWallFaceLine(wall, 'b'), + original = before[i]! + if (Math.abs(original.start.x - original.end.x) < 1e-6) + expect(line.start.x).toBeCloseTo(original.start.x) + else expect(line.start.y).toBeCloseTo(original.start.y) + } + assertEnclosed(after, 1) + expect(lockOutsideFaces(after, { levelId }).changes).toEqual([]) + }) + test('moving a sub-room copies its shared separator and preserves both enclosed room IDs', () => { + const { nodes, zoneId, mintId } = fixture() + const divided = reconcile( + nodes, + divideZone(nodes, { + zoneId, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }), + ) + const room = rooms(divided).find((room) => Math.max(...room.polygon.map((p) => p[0])) <= 2)! + const separator = Object.values(divided).find((node) => node.type === 'separator')! + const plan = transformZone(divided, { zoneId: room.id, translate: [-6, 0], mintId }) + const after = reconcile(divided, plan) + expect(after[separator.id]).toEqual(divided[separator.id]) + expect(after[plan.idMap[separator.id]![0]!]).toMatchObject({ start: [-4, 0], end: [-4, 4] }) + expect( + rooms(after) + .map((room) => room.id) + .sort(), + ).toEqual( + rooms(divided) + .map((room) => room.id) + .sort(), + ) + assertEnclosed(after, 2) + expect(roomFace(after, after[room.id] as ZoneNode)).toBeDefined() + expect(walls(after).some((wall) => wall.start[0] >= 2 && wall.end[0] >= 2)).toBe(true) + }) + test('duplicate copies openings, nested wall items and ceiling fixtures without copying derived hosts', () => { + const { nodes, zoneId, mintId } = fixture() + const wall = walls(nodes)[0]! + const ceiling = Object.values(nodes).find((node) => node.type === 'ceiling')! + const mounted = ItemNode.parse({ + id: 'item_mounted', + parentId: wall.id, + wallId: wall.id, + wallT: 0.25, + position: [1, 1, 0.2], + children: ['item_mounted_child'], + asset, + }) + const child = ItemNode.parse({ + id: 'item_mounted_child', + parentId: mounted.id, + position: [0, 0.5, 0], + asset, + }) + const light = ItemNode.parse({ + id: 'item_light', + parentId: ceiling.id, + position: [2, -0.1, 2], + asset, + }) + const withDoor = door(nodes, wall, 'door_copy') + const graph = { ...withDoor, [mounted.id]: mounted, [child.id]: child, [light.id]: light } + const plan = duplicateZone(graph, { zoneId, translate: [6, 0], mintId }) + const after = reconcile(graph, plan) + expect(plan.idMap[ceiling.id]).toBeUndefined() + const copiedWall = plan.idMap[wall.id]![0]! + expect(after[plan.idMap['door_copy']![0]!]).toMatchObject({ + parentId: copiedWall, + wallId: copiedWall, + position: [2, 0, 0], + }) + expect(after[plan.idMap[mounted.id]![0]!]).toMatchObject({ + parentId: copiedWall, + wallId: copiedWall, + position: mounted.position, + }) + expect(after[plan.idMap[child.id]![0]!]).toMatchObject({ + parentId: plan.idMap[mounted.id]![0], + position: child.position, + }) + expect(after[plan.idMap[light.id]![0]!]).toMatchObject({ + parentId: Object.values(after).find( + (node) => node.type === 'ceiling' && node.zoneId === plan.zoneId, + )!.id, + position: [8, -0.1, 2], + }) + }) + test('drop preserves the moving face finish and remaps overrides when the destination runs backwards', () => { + const { nodes, zoneId, mintId } = fixture() + const adjacent = addRoom(nodes, mintId, rectangle(10)) + const placed = walls(adjacent.nodes).find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! + const destination = walls(adjacent.nodes).find( + (wall) => wall.start[0] === 10 && wall.end[0] === 10, + )! + const graph = { + ...adjacent.nodes, + [placed.id]: { ...placed, slots: { a: 'scene:red' } }, + [destination.id]: { ...destination, slots: { a: 'scene:blue' } }, + } + const after = reconcile(graph, transformZone(graph, { zoneId, translate: [6, 0], mintId })) + expect(after[destination.id]).toMatchObject({ slots: { a: 'scene:blue' } }) + expect((after[zoneId] as ZoneNode).wallOverrides).toContainEqual({ + wallId: destination.id, + face: 'b', + finish: 'scene:red', + }) + }) + test('a room dropped inside another creates a ring and preserves the containing room ID', () => { + const { nodes, zoneId, mintId } = fixture() + const outside = addRoom(nodes, mintId, rectangle(10, -2, 10, 10)) + const plan = transformZone(outside.nodes, { zoneId, translate: [12, 0], mintId }) + expect(plan.conflicts).toBeUndefined() + const after = reconcile(outside.nodes, plan) + assertEnclosed(after, 2) + expect((after[outside.zoneId] as ZoneNode).holes).toHaveLength(1) + expect(after[zoneId]).toMatchObject({ seed: [14, 2] }) + }) + test('rotating curved boundaries keeps their arc and hosted stations', () => { + const { nodes, zoneId, mintId } = fixture() + const wall = walls(nodes)[0]! + const curved = reconcile(nodes, { + changes: [{ op: 'update', id: wall.id, data: { curveOffset: -1 } }], + }) + const graph = door(curved, curved[wall.id] as WallNode, 'door_curved', 1.2) + const plan = duplicateZone(graph, { + zoneId, + translate: [8, 0], + rotate: { angle: Math.PI / 2 }, + mintId, + }) + const after = reconcile(graph, plan) + expect((after[plan.idMap[wall.id]![0]!] as WallNode).curveOffset).toBeCloseTo(-1) + expect(after[plan.idMap['door_curved']![0]!]).toMatchObject({ position: [1.2, 0, 0] }) + assertEnclosed(after, 2) + }) + test('invalid transforms and colliding minted IDs fail before producing a plan', () => { + const { nodes, zoneId, mintId } = fixture() + const before = JSON.stringify(nodes) + expect(() => transformZone(nodes, { zoneId, translate: [Number.NaN, 0], mintId })).toThrow( + 'finite', + ) + expect(() => + duplicateZone(nodes, { zoneId, translate: [6, 0], mintId: () => walls(nodes)[0]!.id }), + ).toThrow('reused') + expect(JSON.stringify(nodes)).toBe(before) + }) + test('duplicate touching the source keeps its enclosure and merges the common wall', () => { + const { nodes, zoneId, mintId } = fixture() + const sourceWall = walls(nodes).find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! + const graph = door(nodes, sourceWall, 'door_source') + const plan = duplicateZone(graph, { zoneId, translate: [4, 0], mintId }) + const after = reconcile(graph, plan) + expect(after[zoneId]).toMatchObject({ polygon: (graph[zoneId] as ZoneNode).polygon }) + expect(after[sourceWall.id]).toMatchObject({ start: sourceWall.start, end: sourceWall.end }) + expect(after['door_source']).toEqual(graph['door_source']) + expect(walls(after)).toHaveLength(7) + assertEnclosed(after, 2) + }) +}) + +describe('room transform adversarial regressions', () => { + test('fixed reference locking preserves curved separator junctions without conflicts', () => { + const { nodes, zoneId, mintId } = fixture() + const bottom = walls(nodes).find((wall) => wall.start[1] === 0 && wall.end[1] === 0)! + const curved = reconcile(nodes, { + changes: [{ op: 'update', id: bottom.id, data: { curveOffset: 1 } }], + }) + const graph = reconcile( + curved, + divideZone(curved, { + zoneId, + cut: [ + [2, -1], + [2, 4], + ], + startBoundaryId: bottom.id, + mintId, + }), + ) + expect(rooms(graph)).toHaveLength(2) + mount(graph) + const plan = lockOutsideFaces(graph, { levelId }) + expect(plan.conflicts).toBeUndefined() + expect(plan.wallIds).toHaveLength(4) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const after = useScene.getState().nodes + expect( + rooms(after) + .map((zone) => zone.id) + .sort(), + ).toEqual( + rooms(graph) + .map((zone) => zone.id) + .sort(), + ) + for (const node of Object.values(graph)) + if (node.type === 'wall' || node.type === 'separator') + expect(after[node.id]).toMatchObject({ start: node.start, end: node.end }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + }) + + for (const withWall of [false, true]) + test(`H1 outside-face locking preserves divided house IDs and intent (T wall=${withWall})`, () => { + const { nodes, zoneId, mintId } = fixture() + let graph = reconcile( + nodes, + divideZone(nodes, { + zoneId, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }), + ) + if (withWall) { + const wall = WallNode.parse({ + id: 'wall_tstem', + parentId: levelId, + start: [3, 0], + end: [3, 4], + thickness: 0.2, + }) + graph = reconcile(graph, { changes: [{ op: 'create', node: wall }] }) + } + for (const zone of rooms(graph)) + graph[zone.id] = { + ...zone, + name: `Saved ${zone.id}`, + floor: { finish: `scene:${zone.id}` }, + } + mount(graph) + const before = useScene.getState().nodes + const plan = lockOutsideFaces(before, { levelId }) + expect(plan.conflicts).toBeUndefined() + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const after = useScene.getState().nodes + assertEnclosed(after, withWall ? 3 : 2) + expect( + rooms(after) + .map((zone) => zone.id) + .sort(), + ).toEqual( + rooms(before) + .map((zone) => zone.id) + .sort(), + ) + for (const zone of rooms(before)) + expect(after[zone.id]).toMatchObject({ name: zone.name, floor: zone.floor }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + }) + + test('H2 shared separator move preserves both rooms in one store history step', () => { + const { nodes, zoneId, mintId } = fixture() + const graph = reconcile( + nodes, + divideZone(nodes, { + zoneId, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }), + ) + const left = rooms(graph).find((zone) => Math.max(...zone.polygon.map((p) => p[0])) <= 2)! + mount(graph) + applyZoneTransformPlan(transformZone(graph, { zoneId: left.id, translate: [-6, 0], mintId })) + const after = useScene.getState().nodes + assertEnclosed(after, 2) + expect( + rooms(after) + .map((zone) => zone.id) + .sort(), + ).toEqual( + rooms(graph) + .map((zone) => zone.id) + .sort(), + ) + expect(Object.values(after).filter((node) => node.type === 'separator')).toHaveLength(2) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + }) + + test('H3 pickup includes furnishings within the wall envelope and excludes exterior items and non-furnishing kinds', () => { + const { nodes, zoneId, mintId } = fixture() + const furnishings = [ + ItemNode.parse({ id: 'item_inside', parentId: levelId, position: [1, 0, 1], asset }), + ItemNode.parse({ id: 'item_boundary', parentId: levelId, position: [0.01, 0, 2], asset }), + CabinetNode.parse({ id: 'cabinet_inside', parentId: levelId, position: [2, 0, 2] }), + ShelfNode.parse({ id: 'shelf_inside', parentId: levelId, position: [3, 0, 2] }), + StairNode.parse({ id: 'stair_inside', parentId: levelId, position: [3, 0, 3] }), + ] + const excluded = [ + ItemNode.parse({ id: 'item_outside', parentId: levelId, position: [-0.4, 0, 2], asset }), + RoofNode.parse({ id: 'roof_unchanged', parentId: levelId, position: [2, 0, 2] }), + RoofSegmentNode.parse({ id: 'rseg_unchanged', parentId: levelId, position: [2, 0, 2] }), + GuideNode.parse({ + id: 'guide_unchanged', + parentId: levelId, + position: [2, 0, 2], + url: 'https://example.com/guide.png', + }), + ScanNode.parse({ id: 'scan_unchanged', parentId: levelId, position: [2, 0, 2] }), + SpawnNode.parse({ id: 'spawn_unchanged', parentId: levelId, position: [2, 0, 2] }), + MeasurementNode.parse({ + id: 'measurement_unchanged', + parentId: levelId, + measurement: { + kind: 'distance', + points: [ + [1, 0, 1], + [2, 0, 1], + ], + }, + }), + ConstructionDimensionNode.parse({ + id: 'construction-dimension_unchanged', + parentId: levelId, + }), + ] + const graph = { + ...nodes, + ...Object.fromEntries([...furnishings, ...excluded].map((node) => [node.id, node])), + } + const plan = transformZone(graph, { zoneId, translate: [10, 0], mintId }) + mount(graph) + applyZoneTransformPlan(plan) + const after = useScene.getState().nodes + for (const node of excluded) expect(after[node.id]).toEqual(node) + for (const node of furnishings) + expect(after[node.id]).toMatchObject({ + position: [node.position[0] + 10, node.position[1], node.position[2]], + }) + }) + + test('M4 an unsplit partly shared T wall keeps the shared door and moves its unshared door', () => { + const { mintId } = fixture() + const initial = { + [levelId]: LevelNode.parse({ id: levelId, parentId: 'building_transform' }), + building_transform: BuildingNode.parse({ id: 'building_transform', children: [levelId] }), + } + const segments: Array<[[number, number], [number, number]]> = [ + [ + [0, 0], + [4, 0], + ], + [ + [4, 0], + [4, 4], + ], + [ + [4, 4], + [0, 4], + ], + [ + [0, 4], + [0, 0], + ], + [ + [4, 0], + [8, 0], + ], + [ + [8, 0], + [8, 2], + ], + [ + [8, 2], + [4, 2], + ], + ] + let graph = reconcile(initial, { + changes: segments.map(([start, end], i) => ({ + op: 'create', + node: WallNode.parse({ id: `wall_partial${i}`, parentId: levelId, start, end }), + })), + }) + const room = rooms(graph).find((zone) => zone.polygon.some((p) => p[0] < 1))! + const wall = graph.wall_partial1 as WallNode + graph = door(graph, wall, 'door_shared_lower', 1) + graph = door(graph, graph[wall.id] as WallNode, 'door_unshared_upper', 3) + mount(graph) + const plan = transformZone(graph, { zoneId: room.id, translate: [-10, 0], mintId }) + expect(plan.conflicts).toBeUndefined() + applyZoneTransformPlan(plan) + const after = useScene.getState().nodes + const childPosition = (id: string) => { + const child = after[id] as ReturnType + const host = after[child.parentId!] as WallNode + const t = + child.position[0] / Math.hypot(host.end[0] - host.start[0], host.end[1] - host.start[1]) + return [ + host.start[0] + t * (host.end[0] - host.start[0]), + host.start[1] + t * (host.end[1] - host.start[1]), + ] + } + expect(childPosition('door_shared_lower')).toEqual([4, 1]) + expect(childPosition('door_unshared_upper')).toEqual([-6, 3]) + expect(after[wall.id]).toMatchObject({ start: [4, 0], end: [4, 2] }) + assertEnclosed(after, 2) + expect( + rooms(after) + .map((zone) => zone.id) + .sort(), + ).toEqual( + rooms(graph) + .map((zone) => zone.id) + .sort(), + ) + }) + + for (const offset of [0.001, -0.05, 0.099]) + test(`M5 drop snaps a ${offset} m offset onto the destination line and keeps rooms enclosed`, () => { + const { nodes, zoneId, mintId } = fixture() + const other = addRoom(nodes, mintId, rectangle(10)) + const destination = walls(other.nodes).find( + (wall) => wall.start[0] === 10 && wall.end[0] === 10, + )! + const plan = transformZone(other.nodes, { zoneId, translate: [6 + offset, 0], mintId }) + const after = reconcile(other.nodes, plan) + expect(walls(after)).toHaveLength(7) + expect(after[destination.id]).toMatchObject({ + start: destination.start, + end: destination.end, + }) + assertEnclosed(after, 2) + }) + + test('close parallel wall bodies outside merge tolerance remain valid separate walls', () => { + const { nodes, zoneId, mintId } = fixture() + const long = WallNode.parse({ + id: 'wall_parallel', + parentId: levelId, + start: [10.15, 0], + end: [10.15, 4], + thickness: 0.4, + }) + const graph = { ...nodes, [long.id]: long } + const blocked = transformZone(graph, { zoneId, translate: [6, 0], mintId }) + expect(blocked.conflicts).toBeUndefined() + expect(blocked.changes.length).toBeGreaterThan(0) + const forced = transformZone(graph, { zoneId, translate: [6, 0], force: true, mintId }) + expect(forced.changes.length).toBeGreaterThan(0) + const short = { + ...long, + start: [10, 3.95] as [number, number], + end: [10, 5] as [number, number], + } + const partial = transformZone( + { ...nodes, [short.id]: short }, + { zoneId, translate: [6, 0], mintId }, + ) + expect(partial.conflicts).toBeUndefined() + expect(partial.changes.length).toBeGreaterThan(0) + const after = reconcile({ ...nodes, [short.id]: short }, partial) + expectNoDuplicateBoundaries(after) + expect(after[short.id]).toBeDefined() + }) + + test('M6 moving or copying an intact painted wall does not freeze its finish in room overrides', () => { + const { nodes, zoneId, mintId } = fixture() + const wall = walls(nodes)[0]! + const graph = { ...nodes, [wall.id]: { ...wall, slots: { a: 'scene:red' } } } + for (const planner of [transformZone, duplicateZone]) { + const plan = planner(graph, { zoneId, translate: [10, 0], mintId }) + const after = reconcile(graph, plan) + expect((after[plan.zoneId] as ZoneNode).wallOverrides).toBeUndefined() + expect(after[plan.idMap[wall.id]![0]!]).toMatchObject({ slots: { a: 'scene:red' } }) + } + }) + + test('L7 duplicates take the next free numbered name without renaming their source', () => { + const { nodes, zoneId, mintId } = fixture() + const first = duplicateZone(nodes, { zoneId, translate: [6, 0], mintId }) + const graph = reconcile(nodes, first) + expect(graph[first.zoneId]).toMatchObject({ name: 'Kitchen 2' }) + const second = duplicateZone(graph, { zoneId: first.zoneId, translate: [6, 0], mintId }) + expect(reconcile(graph, second)[second.zoneId]).toMatchObject({ name: 'Kitchen 3' }) + expect(graph[zoneId]).toMatchObject({ name: 'Kitchen' }) + }) + + test('L8 copied ceiling fixtures are rehosted to the derived copy ceiling in one undoable commit', () => { + const { nodes, zoneId, mintId } = fixture() + const ceiling = Object.values(nodes).find((node) => node.type === 'ceiling')! + const light = ItemNode.parse({ + id: 'item_hosted_copy', + parentId: ceiling.id, + position: [2, -0.1, 2], + asset, + }) + const graph = { + ...nodes, + [light.id]: light, + [ceiling.id]: { ...ceiling, children: [light.id] }, + } + mount(graph) + const plan = duplicateZone(graph, { zoneId, translate: [6, 0], mintId }) + expect( + plan.changes.some((change) => change.op === 'create' && isDerivedNode(change.node)), + ).toBe(false) + const commits: string[] = [] + const unsubscribe = subscribeSceneCommits((commit) => commits.push(commit.origin)) + try { + applyZoneTransformPlan(plan) + } finally { + unsubscribe() + } + expect(commits).toHaveLength(1) + const after = useScene.getState().nodes + const newCeiling = Object.values(after).find( + (node) => node.type === 'ceiling' && node.zoneId === plan.zoneId, + )! + const copiedId = plan.idMap[light.id]![0]! + expect(after[copiedId]).toMatchObject({ parentId: newCeiling.id, position: [8, -0.1, 2] }) + expect(newCeiling.children).toContain(copiedId) + expect(after[light.id]).toEqual(light) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(graph) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + }) + + for (const movingSeparator of [false, true]) + test(`L9 boundary crossing includes separators (moving=${movingSeparator})`, () => { + const { nodes, zoneId, mintId } = fixture() + let graph = nodes + if (movingSeparator) { + const wall = walls(nodes)[0]! + const separator = SeparatorNode.parse({ + id: 'separator_moving', + parentId: levelId, + start: wall.start, + end: wall.end, + }) + graph = reconcile(nodes, { + changes: [ + { op: 'delete', id: wall.id }, + { op: 'create', node: separator }, + ], + }) + } + const obstruction = movingSeparator + ? WallNode.parse({ id: 'wall_crossing', parentId: levelId, start: [8, -1], end: [8, 1] }) + : SeparatorNode.parse({ + id: 'separator_crossing', + parentId: levelId, + start: [8, -1], + end: [8, 1], + }) + const plan = transformZone( + { ...graph, [obstruction.id]: obstruction }, + { zoneId, translate: [6, 0], mintId }, + ) + expect(plan.conflicts).toBeUndefined() + const after = reconcile({ ...graph, [obstruction.id]: obstruction }, plan) + assertEnclosed(after, 1) + expect( + Object.values(after).filter( + (node) => + (node.type === 'wall' || node.type === 'separator') && + [node.start, node.end].some((point) => point[0] === 8 && point[1] === 0), + ), + ).toHaveLength(4) + }) + + test('L10 a stair on another level using the moved deck conflicts unless forced', () => { + const { nodes, zoneId, mintId } = fixture() + const plate = Object.values(nodes).find((node) => node.type === 'slab')! + const lower = LevelNode.parse({ id: 'level_lower', parentId: 'building_transform', level: -1 }) + const stair = StairNode.parse({ + id: 'stair_lower', + parentId: lower.id, + position: [1, 0, 1], + deckSlabId: plate.id, + }) + const graph = { ...nodes, [lower.id]: lower, [stair.id]: stair } + const plan = transformZone(graph, { zoneId, translate: [6, 0], mintId }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts).toEqual( + expect.arrayContaining([ + expect.objectContaining({ code: 'deck-reference', nodeIds: [stair.id, plate.id] }), + ]), + ) + const forced = transformZone(graph, { zoneId, translate: [6, 0], force: true, mintId }) + expect(forced.changes.length).toBeGreaterThan(0) + expect(forced.conflicts?.map((entry) => entry.code)).toContain('deck-reference') + expect(duplicateZone(graph, { zoneId, translate: [6, 0], mintId }).conflicts).toBeUndefined() + }) + + test('H3 procedural furnishings move and duplicate using the same room containment', () => { + const { nodes, zoneId, mintId } = fixture() + const inside = ProceduralItemNode.parse({ + id: 'procedural-item_inside', + parentId: levelId, + position: [1, 0, 1], + recipe: shelfRecipe, + }) + const outside = ProceduralItemNode.parse({ + id: 'procedural-item_outside', + parentId: levelId, + position: [-0.4, 0, 1], + recipe: shelfRecipe, + }) + const graph = { + ...nodes, + [inside.id]: inside, + [outside.id]: outside, + } as unknown as StructureNodes + for (const planner of [transformZone, duplicateZone]) { + const plan = planner(graph, { zoneId, translate: [6, 0], mintId }) + expect(plan.conflicts).toBeUndefined() + const after = applyToScratch(graph, structureChangeBatch(plan.changes)) + expect(after[plan.idMap[inside.id]![0]!]).toMatchObject({ position: [7, 0, 1] }) + expect(after[outside.id]).toEqual(outside as never) + expect(plan.idMap[outside.id]).toBeUndefined() + } + }) +}) + +describe('Sims room placement', () => { + test('quarter-turn beside a neighbour merges collinear walls in one undo step', () => { + const base = fixture() + const source = reconcile( + base.nodes, + transformZone(base.nodes, { zoneId: base.zoneId, translate: [-20, 0], mintId: base.mintId }), + ) + const room = addRoom(source, base.mintId, rectangle(0, 0, 2, 4)) + const neighbour = addRoom(room.nodes, base.mintId, rectangle(3, 1, 4, 2)) + const destination = walls(neighbour.nodes).find( + (wall) => wall.start[0] === 3 && wall.end[0] === 3, + )! + mount(neighbour.nodes) + const plan = rotateZone(neighbour.nodes, { + zoneId: room.zoneId, + quarterTurns: 1, + mintId: base.mintId, + }) + expect(plan.conflicts).toBeUndefined() + applyZoneTransformPlan(plan) + const after = useScene.getState().nodes + assertEnclosed(after, 3) + expect(walls(after)).toHaveLength(11) + expect(after[destination.id]).toBeDefined() + expect(after[room.zoneId]).toBeDefined() + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(neighbour.nodes) + }) + + for (const quarterTurns of [-1, 1] as const) + for (const gridStep of [0.5, 0.25]) + test(`quarter-turn snaps the first reference vertex and keeps all grid vertices (${quarterTurns}, ${gridStep})`, () => { + const { nodes, mintId } = fixture() + const room = addRoom(nodes, mintId, rectangle(10, 0, 5 * gridStep, 8 * gridStep)) + const plan = rotateZone(room.nodes, { + zoneId: room.zoneId, + quarterTurns, + ...(gridStep === 0.25 ? { gridStep } : {}), + mintId, + }) + const after = reconcile(room.nodes, plan) + const zone = after[room.zoneId] as ZoneNode + for (const id of zone.boundaryWallIds) { + const wall = after[id] as WallNode + for (const point of [wall.start, wall.end]) + for (const value of point) expect(value / gridStep).toBe(Math.round(value / gridStep)) + } + assertEnclosed(after, 2) + }) + + test('coincident enclosures merge and the larger overlap retains its zone ID', () => { + const { nodes, zoneId, mintId } = fixture() + const source = addRoom(nodes, mintId, rectangle(8, 0, 3.9, 3.9)) + mount(source.nodes) + const plan = transformZone(source.nodes, { + zoneId: source.zoneId, + translate: [-7.95, 0.05], + mintId, + }) + expect(plan.conflicts).toBeUndefined() + applyZoneTransformPlan(plan) + const after = useScene.getState().nodes + assertEnclosed(after, 1) + expect(rooms(after).map((zone) => zone.id)).toEqual([zoneId]) + expect(walls(after)).toHaveLength(4) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + }) + + for (const sourceOpening of [false, true]) + for (const kind of ['door', 'window'] as const) + test(`crossing inside an opening refuses; force relocates it on its wall (moving=${sourceOpening}, ${kind})`, () => { + const { nodes, zoneId, mintId } = fixture() + const neighbour = addRoom(nodes, mintId, rectangle(8)) + const host = sourceOpening + ? walls(neighbour.nodes).find( + (wall) => wall.start[1] === 0 && wall.end[1] === 0 && wall.start[0] === 0, + )! + : walls(neighbour.nodes).find((wall) => wall.start[0] === 12 && wall.end[0] === 12)! + const attached = (kind === 'door' ? DoorNode : WindowNode).parse({ + id: `${kind}_crossing`, + parentId: host.id, + wallId: host.id, + position: [sourceOpening ? 3 : 1, 0, 0], + }) + const graph = { + ...neighbour.nodes, + [host.id]: { ...host, children: [attached.id] }, + [attached.id]: attached, + } + const before = JSON.stringify(graph) + const blocked = transformZone(graph, { zoneId, translate: [9, 1], mintId }) + expect(blocked.changes).toEqual([]) + expect(blocked.conflicts?.map((entry) => entry.code)).toEqual(['occupied-split']) + const forced = transformZone(graph, { zoneId, translate: [9, 1], force: true, mintId }) + expect(forced.conflicts).toBeUndefined() + const after = reconcile(graph, forced) + const opening = after[attached.id] as DoorNode | WindowNode + const wall = after[opening.parentId!] as WallNode + expect(opening.position[0]).toBeGreaterThanOrEqual(opening.width / 2) + expect(opening.position[0] + opening.width / 2).toBeLessThanOrEqual( + Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + 1e-6, + ) + expect(JSON.stringify(graph)).toBe(before) + assertEnclosed(after, 3) + }) + + test('force still refuses an opening that cannot fit between crossings', () => { + const { nodes, zoneId, mintId } = fixture() + const neighbour = addRoom(nodes, mintId, rectangle(8)) + const host = walls(neighbour.nodes).find( + (wall) => wall.start[1] === 0 && wall.end[1] === 0 && wall.start[0] === 0, + )! + const opening = DoorNode.parse({ + id: 'door_too_wide', + parentId: host.id, + wallId: host.id, + position: [2, 0, 0], + width: 3.5, + }) + const graph = { + ...neighbour.nodes, + [opening.id]: opening, + [host.id]: { ...host, children: [opening.id] }, + } + const plan = transformZone(graph, { zoneId, translate: [9, 1], force: true, mintId }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.map((entry) => entry.code)).toEqual(['occupied-split']) + }) + + test('force relocation clears every crossing and avoids an existing opening', () => { + const { nodes, zoneId, mintId } = fixture() + const host = walls(nodes)[0]! + let graph = door(nodes, host, 'door_moved', 2) + graph = door(graph, graph[host.id] as WallNode, 'door_fixed', 0.5) + const blockers = [1.8, 2.2].map((x, i) => + WallNode.parse({ + id: `wall_obstruction${i}`, + parentId: levelId, + start: [x + 10, -1], + end: [x + 10, 1], + }), + ) + graph = { ...graph, ...Object.fromEntries(blockers.map((wall) => [wall.id, wall])) } + const plan = transformZone(graph, { zoneId, translate: [10, 0], force: true, mintId }) + expect(plan.conflicts).toBeUndefined() + const after = reconcile(graph, plan) + const moved = after['door_moved'] as DoorNode, + fixed = after['door_fixed'] as DoorNode + expect(fixed.position).toEqual([0.5, 0, 0]) + expect(moved.parentId).not.toBe(fixed.parentId) + const parent = after[moved.parentId!] as WallNode + expect(parent.start[0] + moved.position[0] - moved.width / 2).toBeGreaterThanOrEqual(12.2) + }) + + test('duplicating onto another enclosure keeps both sets of openings and rehosts ceiling fixtures', () => { + const { nodes, zoneId, mintId } = fixture() + const destination = addRoom(nodes, mintId, rectangle(6)) + const sourceWall = walls(destination.nodes).find( + (wall) => wall.start[0] === 0 && wall.start[1] === 0 && wall.end[1] === 0, + )! + const destinationWall = walls(destination.nodes).find( + (wall) => wall.start[0] === 6 && wall.start[1] === 0 && wall.end[1] === 0, + )! + const withSourceDoor = door(destination.nodes, sourceWall, 'door_copy_source', 1) + const withDoors = door(withSourceDoor, destinationWall, 'door_copy_destination', 3) + const ceiling = Object.values(destination.nodes).find( + (node) => node.type === 'ceiling' && node.zoneId === zoneId, + )! + const light = ItemNode.parse({ + id: 'item_merge_light', + parentId: ceiling.id, + position: [2, -0.1, 2], + asset, + }) + const graph = { + ...withDoors, + [light.id]: light, + [ceiling.id]: { ...ceiling, children: [light.id] }, + } + const plan = duplicateZone(graph, { zoneId, translate: [6, 0], mintId }) + expect(plan.conflicts).toBeUndefined() + const after = reconcile(graph, plan) + assertEnclosed(after, 2) + const copied = after[plan.idMap[light.id]![0]!]! + expect(after[copied.parentId!]?.type).toBe('ceiling') + expect(copied).toMatchObject({ position: [8, -0.1, 2] }) + expect(after[light.id]).toEqual(light) + expect(after[plan.idMap.door_copy_source![0]!]).toMatchObject({ + parentId: destinationWall.id, + position: [1, 0, 0], + }) + expect(after.door_copy_destination).toMatchObject({ + parentId: destinationWall.id, + position: [3, 0, 0], + }) + expect(after.door_copy_source).toEqual(graph.door_copy_source) + }) +}) + +for (const curvedDestination of [false, true]) + test(`dropping curved boundaries splits exact crossings (curved destination=${curvedDestination})`, () => { + const { nodes, zoneId, mintId } = fixture() + const bottom = walls(nodes).find((wall) => wall.start[1] === 0 && wall.end[1] === 0)! + const source = reconcile(nodes, { + changes: [{ op: 'update', id: bottom.id, data: { curveOffset: 1 } }], + }) + const obstacle = WallNode.parse({ + id: 'wall_arc_crossing', + parentId: levelId, + start: curvedDestination ? [10, -1] : [12, -2], + end: curvedDestination ? [14, -1] : [12, 1], + ...(curvedDestination ? { curveOffset: -1 } : {}), + }) + const graph = { ...source, [obstacle.id]: obstacle } + const plan = transformZone(graph, { zoneId, translate: [10, 0], mintId }) + expect(plan.conflicts).toBeUndefined() + const after = reconcile(graph, plan) + expect(walls(after).filter((wall) => wall.curveOffset)).toHaveLength(curvedDestination ? 6 : 2) + expect(after[zoneId]).toBeDefined() + expect(rooms(after).every((zone) => zone.enclosureStatus === 'enclosed')).toBe(true) + const cuts = new Map() + for (const wall of walls(after)) + for (const [x, z] of [wall.start, wall.end]) { + const key = `${x.toFixed(6)},${z.toFixed(6)}` + cuts.set(key, (cuts.get(key) ?? 0) + 1) + } + expect([...cuts.values()].filter((count) => count === 4)).toHaveLength( + curvedDestination ? 2 : 1, + ) + }) + +describe('Sims audit regressions', () => { + for (const dx of [9, 11]) + test(`partial duplicate retains Kitchen 2 and Bedroom on their largest owned faces (${dx})`, () => { + const { nodes, zoneId, mintId } = fixture() + const neighbour = addRoom(nodes, mintId, rectangle(8)) + const graph = { + ...neighbour.nodes, + [neighbour.zoneId]: { + ...neighbour.nodes[neighbour.zoneId], + name: 'Bedroom', + floor: { finish: 'tile' }, + }, + [zoneId]: { ...neighbour.nodes[zoneId], floor: { finish: 'wood' } }, + } as StructureNodes + mount(graph) + const plan = duplicateZone(graph, { zoneId, translate: [dx, 1], mintId }) + applyZoneTransformPlan(plan) + const after = useScene.getState().nodes + assertEnclosed(after, 4) + expect(after[zoneId]).toEqual(graph[zoneId]) + expect(after[plan.zoneId]).toMatchObject({ name: 'Kitchen 2', floor: { finish: 'wood' } }) + expect(after[neighbour.zoneId]).toMatchObject({ name: 'Bedroom', floor: { finish: 'tile' } }) + const copy = after[plan.zoneId] as ZoneNode + expect(area([{ outer: copy.polygon, holes: copy.holes }])).toBeCloseTo(dx === 9 ? 9 : 13) + const bedroom = after[neighbour.zoneId] as ZoneNode + expect(containsPoint([{ outer: rectangle(dx, 1), holes: [] }], bedroom.seed!)).toBe(false) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(graph) + }) + + for (const overlap of [0.05, 0.005]) + test(`short collinear overlaps merge duplicate pieces and keep children on both sides (${overlap})`, () => { + const { nodes, zoneId, mintId } = fixture() + const source = walls(nodes).find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! + const destination = WallNode.parse({ + id: 'wall_short_destination', + parentId: levelId, + start: [10, 4 - overlap], + end: [10, 5], + }) + const child = ItemNode.parse({ + id: 'item_short_source', + parentId: source.id, + position: [4 - overlap / 2, 1, 0], + asset, + }) + const other = ItemNode.parse({ + id: 'item_short_destination', + parentId: destination.id, + position: [overlap / 2, 1, 0], + asset, + }) + const graph = { + ...nodes, + [source.id]: { ...source, children: [child.id] }, + [destination.id]: { ...destination, children: [other.id] }, + [child.id]: child, + [other.id]: other, + } + const plan = transformZone(graph, { zoneId, translate: [6, 0], mintId }) + const after = reconcile(graph, plan) + expectNoDuplicateBoundaries(after) + expect(after[destination.id]).toBeDefined() + expect(after[child.id]).toMatchObject({ parentId: destination.id }) + expect(after[other.id]).toMatchObject({ parentId: destination.id }) + expect((after[child.id] as ItemNode).position[0]).toBeCloseTo(overlap / 2) + expect((after[other.id] as ItemNode).position[0]).toBeCloseTo(overlap / 2) + assertEnclosed(after, 1) + }) + + test('merging the first short piece retains the full source ID map', () => { + const { nodes, zoneId, mintId } = fixture() + const source = walls(nodes).find((wall) => wall.start[0] === 4 && wall.end[0] === 4)! + const destination = WallNode.parse({ + id: 'wall_short_start', + parentId: levelId, + start: [10, 0.05], + end: [10, -1], + }) + const graph = { ...nodes, [destination.id]: destination } + const plan = transformZone(graph, { zoneId, translate: [6, 0], mintId }) + const after = reconcile(graph, plan) + expectNoDuplicateBoundaries(after) + const mapped = plan.idMap[source.id]! + expect(mapped).toHaveLength(2) + expect(mapped).toContain(destination.id) + const length = mapped.reduce((sum, id) => { + const wall = after[id] as WallNode + return sum + Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + }, 0) + expect(length).toBeCloseTo(4) + }) + + test('a stationary wall replaces the covered middle of a moving separator', () => { + const { nodes, zoneId, mintId } = fixture() + const bottom = walls(nodes)[0]! + const separator = SeparatorNode.parse({ + id: 'separator_covered', + parentId: levelId, + start: bottom.start, + end: bottom.end, + }) + const source = reconcile(nodes, { + changes: [ + { op: 'delete', id: bottom.id }, + { op: 'create', node: separator }, + ], + }) + const wall = WallNode.parse({ + id: 'wall_covering_separator', + parentId: levelId, + start: [11, 0], + end: [13, 0], + }) + const graph = { ...source, [wall.id]: wall } + const plan = transformZone(graph, { zoneId, translate: [10, 0], mintId }) + const after = reconcile(graph, plan) + expectNoDuplicateBoundaries(after) + const tails = Object.values(after).filter((node) => node.type === 'separator') + expect(tails).toHaveLength(2) + expect(tails.map((node) => [node.start, node.end])).toEqual( + expect.arrayContaining([ + [ + [10, 0], + [11, 0], + ], + [ + [13, 0], + [14, 0], + ], + ]), + ) + expect(after[wall.id]).toMatchObject({ start: [11, 0], end: [13, 0] }) + expect((after[zoneId] as ZoneNode).boundaryWallIds).toContain(wall.id) + assertEnclosed(after, 1) + }) + + test('curved room drops leave distant crossing walls byte-identical', () => { + const { nodes, zoneId, mintId } = fixture() + const bottom = walls(nodes)[0]! + const curved = reconcile(nodes, { + changes: [{ op: 'update', id: bottom.id, data: { curveOffset: 1 } }], + }) + const distant = [ + WallNode.parse({ + id: 'wall_distant_horizontal', + parentId: levelId, + start: [40, 0], + end: [44, 0], + }), + WallNode.parse({ + id: 'wall_distant_vertical', + parentId: levelId, + start: [42, -1], + end: [42, 1], + }), + ] + const graph = { ...curved, ...Object.fromEntries(distant.map((node) => [node.id, node])) } + const plan = transformZone(graph, { zoneId, translate: [10, 0], mintId }) + const after = reconcile(graph, plan) + for (const wall of distant) { + expect(after[wall.id]).toEqual(wall) + expect(plan.changes.some((change) => change.op !== 'create' && change.id === wall.id)).toBe( + false, + ) + } + expect(walls(after)).toHaveLength(6) + }) + + for (const station of [2, 1.45]) + test(`opening clearance includes half the crossing wall thickness (${station})`, () => { + const { nodes, zoneId, mintId } = fixture() + const host = walls(nodes)[0]! + let graph = door(nodes, host, 'door_padded', station) + const crossing = WallNode.parse({ + id: 'wall_thick_crossing', + parentId: levelId, + start: [12, -1], + end: [12, 1], + thickness: 0.4, + }) + graph = { ...graph, [crossing.id]: crossing } + const blocked = transformZone(graph, { zoneId, translate: [10, 0], mintId }) + expect(blocked.changes).toEqual([]) + expect(blocked.conflicts?.map((conflict) => conflict.code)).toEqual(['occupied-split']) + const forced = transformZone(graph, { zoneId, translate: [10, 0], force: true, mintId }) + const after = reconcile(graph, forced) + const opening = after.door_padded as DoorNode + const parent = after[opening.parentId!] as WallNode + const x = parent.start[0] + opening.position[0] + expect(Math.abs(x - 12) - opening.width / 2).toBeGreaterThanOrEqual(0.2 - 1e-6) + }) + + test('force refuses when crossing wall thickness consumes the remaining opening space', () => { + const { nodes, zoneId, mintId } = fixture() + const host = walls(nodes)[0]! + const opening = DoorNode.parse({ + id: 'door_padding_no_fit', + parentId: host.id, + wallId: host.id, + position: [2, 0, 0], + width: 1.9, + }) + const crossing = WallNode.parse({ + id: 'wall_padding_no_fit', + parentId: levelId, + start: [12, -1], + end: [12, 1], + thickness: 0.4, + }) + const graph = { + ...nodes, + [host.id]: { ...host, children: [opening.id] }, + [opening.id]: opening, + [crossing.id]: crossing, + } + const plan = transformZone(graph, { zoneId, translate: [10, 0], force: true, mintId }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.map((conflict) => conflict.code)).toEqual(['occupied-split']) + }) + + test('an open room returns a structured conflict for move, duplicate and rotate', () => { + const { nodes, zoneId, mintId } = fixture() + const graph = { ...nodes } + delete graph[walls(nodes)[0]!.id] + for (const plan of [ + transformZone(graph, { zoneId, translate: [2, 0], mintId }), + duplicateZone(graph, { zoneId, translate: [2, 0], mintId }), + rotateZone(graph, { zoneId, quarterTurns: 1, mintId }), + ]) { + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.map((conflict) => conflict.code)).toEqual(['open-room']) + expect(plan.idMap).toEqual({}) + } + }) +}) diff --git a/packages/core/src/commands/structure/zone-wall-merge.ts b/packages/core/src/commands/structure/zone-wall-merge.ts new file mode 100644 index 0000000000..89adc6f39d --- /dev/null +++ b/packages/core/src/commands/structure/zone-wall-merge.ts @@ -0,0 +1,196 @@ +import type { AnyNode, WallNode } from '../../schema' +import { getWallArcData, getWallCurveLength } from '../../systems/wall/wall-curve' +import { buildMergedWallAttachmentUpdates } from '../../systems/wall/wall-merge' +import { at, type Point, type StructureMintId, type StructureNodes } from './shared' + +export function wallStation(wall: Pick, point: Point) { + const dx = wall.end[0] - wall.start[0], + dz = wall.end[1] - wall.start[1] + return ((point[0] - wall.start[0]) * dx + (point[1] - wall.start[1]) * dz) / (dx * dx + dz * dz) +} + +export function collinearOverlap(a: WallNode, b: WallNode) { + if (a.curveOffset || b.curveOffset) return false + const length = Math.hypot(b.end[0] - b.start[0], b.end[1] - b.start[1]) + if (length < 1e-8) return false + const distance = (p: Point) => + Math.abs( + (p[0] - b.start[0]) * (b.end[1] - b.start[1]) - (p[1] - b.start[1]) * (b.end[0] - b.start[0]), + ) / length + const ts = [wallStation(b, a.start), wallStation(b, a.end)] + return ( + distance(a.start) < 0.1 && + distance(a.end) < 0.1 && + (Math.min(1, Math.max(...ts)) - Math.max(0, Math.min(...ts))) * length >= 0.1 + ) +} + +export function wallAttachments(nodes: StructureNodes, wall: WallNode) { + return Object.values(nodes).filter( + (node) => node.parentId === wall.id || ('wallId' in node && node.wallId === wall.id), + ) +} + +export function wallSlice( + wall: WallNode, + start: Point, + end: Point, + id: string, + range?: [number, number], +): WallNode { + const length = getWallCurveLength(wall) + const offset = (range?.[0] ?? wallStation(wall, start)) * length + const sliceLength = range + ? (range[1] - range[0]) * length + : Math.hypot(end[0] - start[0], end[1] - start[1]) + const arc = range ? getWallArcData(wall) : null + // Region stations are metres from the source start, so a trimmed wall needs a new origin. + const faceRegions = wall.faceRegions?.flatMap((region) => { + const lo = Math.max(0, (region.u0 ?? 0) - offset) + const hi = Math.min(sliceLength, (region.u1 ?? length) - offset) + return hi > lo + ? [ + { + ...region, + ...(region.u0 === undefined && lo === 0 ? {} : { u0: lo }), + ...(region.u1 === undefined && hi === sliceLength ? {} : { u1: hi }), + }, + ] + : [] + }) + return { + ...wall, + id: id as WallNode['id'], + start, + end, + children: [], + ...(arc && range + ? { + curveOffset: + arc.direction * + arc.radius * + (1 - Math.cos((Math.abs(arc.delta) * (range[1] - range[0])) / 2)), + } + : {}), + ...(faceRegions ? { faceRegions } : {}), + } +} + +export function rehostWallChild( + nodes: Record, + child: AnyNode, + source: WallNode, + target: WallNode, +) { + const host = { ...source, children: [child.id] as WallNode['children'] } + const empty = { ...source, children: [] } + const update = buildMergedWallAttachmentUpdates( + host, + empty, + target.id, + target.start, + target.end, + nodes, + )[0] + if (update) nodes[child.id] = { ...child, ...update.data } as AnyNode +} + +export function remapWallReferences( + nodes: Record, + source: WallNode, + targets: WallNode[], +) { + for (const zone of Object.values(nodes)) { + if (zone.type !== 'zone') continue + const overrides = zone.wallOverrides?.flatMap((entry) => + entry.wallId !== source.id + ? [entry] + : targets.map((target) => { + const reversed = + (source.end[0] - source.start[0]) * (target.end[0] - target.start[0]) + + (source.end[1] - source.start[1]) * (target.end[1] - target.start[1]) < + 0 + return { + ...entry, + wallId: target.id, + face: reversed ? ((entry.face === 'a' ? 'b' : 'a') as 'a' | 'b') : entry.face, + } + }), + ) + if ( + (zone.boundaryWallIds ?? []).includes(source.id) || + zone.wallOverrides?.some((entry) => entry.wallId === source.id) + ) + nodes[zone.id] = { + ...zone, + boundaryWallIds: [ + ...new Set( + (zone.boundaryWallIds ?? []).flatMap((id) => + id === source.id ? targets.map((wall) => wall.id) : [id], + ), + ), + ], + ...(overrides ? { wallOverrides: overrides } : {}), + } + } +} + +export function splitCollinearWalls( + nodes: Record, + placed: WallNode, + destination: WallNode, + mintId: StructureMintId, +) { + const ts = [wallStation(destination, placed.start), wallStation(destination, placed.end)] + const lo = Math.max(0, Math.min(...ts)), + hi = Math.min(1, Math.max(...ts)) + const shared = wallSlice( + destination, + at(destination.start, destination.end, lo), + at(destination.start, destination.end, hi), + destination.id, + ) + const targets = [shared] + const bySource = new Map() + for (const source of [destination, placed]) { + const cut0 = wallStation(source, shared.start), + cut1 = wallStation(source, shared.end) + const own = [shared] + for (const [a, b] of [ + [0, Math.min(cut0, cut1)], + [Math.max(cut0, cut1), 1], + ]) { + if (b! - a! <= 1e-6) continue + const tail = wallSlice( + source, + at(source.start, source.end, a!), + at(source.start, source.end, b!), + mintId('wall'), + ) + own.push(tail) + targets.push(tail) + } + bySource.set(source, own) + } + for (const source of [destination, placed]) { + const own = bySource.get(source)! + for (const child of wallAttachments(nodes, source)) { + const t = + 'position' in child && Array.isArray(child.position) + ? child.position[0] / + Math.hypot(source.end[0] - source.start[0], source.end[1] - source.start[1]) + : 0.5 + const point = at(source.start, source.end, t) + const target = + own.find((wall) => { + const station = wallStation(wall, point) + return station >= -1e-6 && station <= 1 + 1e-6 + }) ?? shared + rehostWallChild(nodes, child, source, target) + } + remapWallReferences(nodes, source, own) + } + delete nodes[placed.id] + for (const wall of targets) nodes[wall.id] = wall + return bySource +} diff --git a/packages/core/src/contracts/assembly.test.ts b/packages/core/src/contracts/assembly.test.ts index dc481d7886..545440cdcc 100644 --- a/packages/core/src/contracts/assembly.test.ts +++ b/packages/core/src/contracts/assembly.test.ts @@ -97,8 +97,8 @@ describe('a stucco exterior wall (2×6 frame)', () => { close(at({})['stucco']!.back, -0.09285) // Rooms re-detected with the exterior on the front: the stucco follows it. close(at({ frontSide: 'exterior', backSide: 'interior' })['stucco']!.front, 0.09285) - // Undetermined sides fall back to the front face. - close(at({ frontSide: 'unknown', backSide: 'unknown' })['stucco']!.front, 0.09285) + // Undetermined sides fall back to side B, where the 3D cladding goes. + close(at({ frontSide: 'unknown', backSide: 'unknown' })['stucco']!.back, -0.09285) }) test('a stored thickness that is not the layer sum is reported, and draws no bands', () => { diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 280ed9ffdf..4b8ae26851 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -157,8 +157,8 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ kind: 'procedural-item', path: 'attachments.@key', ...policy('node', 'hierarchy', 'drop', 'keep'), - remaps: ['clone-nodes-into'], - note: 'Record key: a hosted child id. Only cloneNodesInto remaps it; the other clones keep the old key.', + remaps: ['clone-scene-graph', 'clone-nodes-into'], + note: 'Record key: a hosted child id. The level-subtree clone keeps the old key.', }), row({ kind: 'procedural-item', @@ -198,8 +198,8 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ ...policy('node', 'host', 'cascade', 'strip'), targetKinds: ['dormer'], dependents: ['dormerFace'], - - note: 'Clone remaps the window `parentId` but not `dormerId`.', + remaps: ['clone-scene-graph'], + note: 'Only the whole-graph clone remaps `dormerId`.', }), row({ kind: 'item', @@ -253,6 +253,7 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ ...policy('node', 'host', 'drop', 'strip'), targetKinds: ['slab'], dependents: ['hostSlabEdgeIndex', 'hostSlabEdgeT', 'hostKind', 'hostHeightOffset'], + remaps: ['clone-scene-graph'], }), row({ kind: '*', @@ -265,6 +266,7 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ 'wallAttachment.endUV', 'wallAttachment.offset', ], + remaps: ['clone-scene-graph'], note: 'Duct and pipe runs drafted on a wall; the level-local path is the frozen pose.', }), row({ @@ -272,6 +274,7 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ path: 'hangerOverrides.*.hostId', ...policy('node', 'host', 'drop', 'strip'), targetKinds: ['wall', 'ceiling'], + remaps: ['clone-scene-graph'], note: 'Pinned hanger host; absent re-elects the nearest wall or ceiling.', }), row({ @@ -279,6 +282,23 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ path: 'gutterId', ...policy('node', 'host', 'drop', 'strip'), targetKinds: ['gutter'], + remaps: ['clone-scene-graph'], + }), + row({ + kind: 'zone', + path: 'hostZoneId', + ...policy('node', 'host', 'drop', 'strip'), + targetKinds: ['zone'], + remaps: CLONES, + note: 'A mezzanine room: the room whose volume it stands in.', + }), + row({ + kind: 'floor-opening', + path: 'hostZoneId', + ...policy('node', 'host', 'drop', 'strip'), + targetKinds: ['zone'], + remaps: CLONES, + note: 'A hosted mezzanine opening cuts only that room’s plate.', }), row({ kind: 'downspout', @@ -347,8 +367,40 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ path: 'boundaryWallIds[]', ...policy('node', 'membership', 'drop', 'strip'), targetKinds: ['wall'], - remaps: WALL_TOPOLOGY, - note: 'Clone copies the old wall ids into the cloned zone.', + remaps: ['clone-scene-graph', ...WALL_TOPOLOGY], + note: 'The level-subtree and subtree clones copy the old wall ids into the cloned zone.', + }), + row({ + kind: 'zone', + path: 'boundarySeparatorIds[]', + ...policy('node', 'membership', 'drop', 'strip'), + targetKinds: ['separator'], + remaps: ['clone-scene-graph'], + note: 'Derived by the structure reconciler, which rewrites it on the next pass.', + }), + row({ + kind: 'slab', + path: 'zoneIds[]', + ...policy('node', 'membership', 'drop', 'strip'), + targetKinds: ['zone'], + remaps: ['clone-scene-graph'], + note: 'Rooms a derived plate carries; rewritten by the structure reconciler.', + }), + row({ + kind: 'slab', + path: 'associatedZoneIds[]', + ...policy('node', 'membership', 'drop', 'strip'), + targetKinds: ['zone'], + remaps: ['clone-scene-graph'], + note: 'Rooms whose construction overlaps a manual slab, resolved once by the legacy migration.', + }), + row({ + kind: 'ceiling', + path: 'zoneId', + ...policy('node', 'membership', 'drop', 'strip'), + targetKinds: ['zone'], + remaps: ['clone-scene-graph'], + note: 'The room a derived ceiling covers; rewritten by the structure reconciler.', }), row({ kind: 'unit', @@ -375,7 +427,7 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ path, ...policy('node', 'membership', 'drop', 'strip'), targetKinds: ['level'], - remaps: ['scene-clipboard'], + remaps: ['clone-scene-graph', 'scene-clipboard'], note: 'Pasting a stair re-derives both from the target level.', }), ), @@ -394,6 +446,7 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ path, ...policy('node', 'membership', 'drop', 'strip'), targetKinds: ['level'], + remaps: ['clone-scene-graph'], }), ), row({ @@ -418,15 +471,72 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ targetKinds: ['construction-dimension'], remaps: [...CLONES, 'clone-nodes-into'], }), - ...(['stairId', 'elevatorId'] as const).map((field) => + ...(['stairId', 'elevatorId', 'openingId'] as const).map((field) => row({ kind: '*', path: `holeMetadata[].${field}`, ...policy('node', 'control', 'drop', 'strip'), - targetKinds: [field === 'stairId' ? 'stair' : 'elevator'], + targetKinds: [ + field === 'stairId' ? 'stair' : field === 'elevatorId' ? 'elevator' : 'floor-opening', + ], + remaps: field === 'openingId' ? CLONES : ['clone-scene-graph'], note: 'The cutter that owns this auto hole; its sync replaces only its own holes.', }), ), + row({ + kind: 'ceiling', + path: 'openingIds[]', + ...policy('node', 'control', 'drop', 'strip'), + targetKinds: ['floor-opening'], + remaps: ['clone-scene-graph'], + note: 'Openings that cut a derived ceiling; rewritten by the structure reconciler.', + }), + row({ + kind: 'floor-opening', + path: 'ownerId', + ...policy('node', 'control', 'cascade', 'strip'), + remaps: CLONES, + note: 'The stair, elevator or plugin node that owns this opening and moves it with its pose.', + }), + row({ + kind: 'floor-opening', + path: 'surfaceId', + ...policy('node', 'internal', 'drop', 'strip'), + targetKinds: ['slab', 'ceiling'], + remaps: ['clone-scene-graph'], + note: 'The surface an owned opening was migrated from; merge tie-break only.', + }), + ...( + [ + ['legacyPlateCuts.@key', 'slab'], + ['legacyCeilingCuts.@key', 'ceiling'], + ] as const + ).map(([path, target]) => + row({ + kind: 'floor-opening', + path, + ...policy('node', 'internal', 'drop', 'strip'), + targetKinds: [target], + remaps: target === 'slab' ? CLONES : ['clone-scene-graph'], + note: 'Record key: the legacy surface whose exact cut rings this opening keeps.', + }), + ), + row({ + kind: 'zone', + path: 'floor.sourceSlabId', + ...policy('node', 'internal', 'drop', 'strip'), + targetKinds: ['slab'], + remaps: ['clone-scene-graph'], + note: 'The drawn slab this room’s floor was adopted from.', + }), + row({ + kind: 'zone', + path: 'wallOverrides[].wallId', + ...policy('node', 'internal', 'drop', 'strip'), + targetKinds: ['wall'], + remaps: ['clone-scene-graph'], + note: 'A per-wall-face finish over the room’s wall material.', + }), // ─── Measurements and dimensions ────────────────────────────────── ...measurementAnchorRows('measurement', 'measurement.points[]', [ @@ -460,6 +570,37 @@ export const EXISTING_REFERENCES: readonly ExistingReference[] = [ note: 'Library material; `#rrggbb` values are literal colours.', }), ...materialRows, + ...(['legacyFaceMaterials.a', 'legacyFaceMaterials.b', 'foundation'] as const).map((prefix) => + row({ + kind: '*', + path: `${prefix}.material.texture.url`, + ...policy('asset', 'content', 'freeze', 'keep'), + note: 'Texture by URL; a dangling URL renders the untextured material.', + }), + ), + ...(['legacyFaceMaterials.a', 'legacyFaceMaterials.b'] as const).map((prefix) => + row({ + kind: 'wall', + path: `${prefix}.materialPreset`, + ...policy('material', 'content', 'freeze', 'keep'), + note: 'Library material preset name of the legacy per-face finish.', + }), + ), + ...( + [ + ['zone', 'floor.finish.*'], + ['zone', 'floor.regions[].finish.*'], + ['zone', 'ceiling.regions[].finish.*'], + ['ceiling', 'regions[].finish.*'], + ] as const + ).map(([kind, path]) => + row({ + kind, + path, + ...policy('material', 'content', 'freeze', 'keep'), + note: 'A paint finish: a MaterialRef string, or this inline material record.', + }), + ), ...(['asset.id', 'asset.src', 'asset.thumbnail', 'asset.floorPlanUrl'] as const).map((path) => row({ kind: 'item', @@ -534,11 +675,32 @@ export const NON_REFERENCES: readonly { kind: string; path: string; reason: stri { kind: '*', path: 'slots.@key', reason: 'Slot id declared by the kind or its asset.' }, { kind: 'block', path: 'slotNames.@key', reason: 'Slot id declared by the block.' }, { kind: 'block', path: 'slotNames.*', reason: 'Display name.' }, - ...MATERIAL_FIELDS.map((field) => ({ + ...[ + ...MATERIAL_FIELDS, + 'legacyFaceMaterials.a.material', + 'legacyFaceMaterials.b.material', + 'foundation.material', + ].map((field) => ({ kind: '*', path: `${field}.id`, reason: 'Optional label of an inline material; no reader dereferences it.', })), + ...( + [ + ['zone', 'floor.finish.@key'], + ['zone', 'floor.regions[].finish.@key'], + ['zone', 'ceiling.regions[].finish.@key'], + ['ceiling', 'regions[].finish.@key'], + ] as const + ).map(([kind, path]) => ({ kind, path, reason: 'Field name of an inline material record.' })), + ...( + [ + ['zone', 'floor.regions[].id'], + ['zone', 'ceiling.regions[].id'], + ['ceiling', 'regions[].id'], + ['wall', 'faceRegions[].id'], + ] as const + ).map(([kind, path]) => ({ kind, path, reason: 'Defines a paint region key.' })), { kind: 'block', path: 'topology.vertices[].id', reason: 'Defines a topology key.' }, { kind: 'block', path: 'topology.edges[].id', reason: 'Defines a topology key.' }, { kind: 'block', path: 'topology.faces[].id', reason: 'Defines a topology key.' }, @@ -681,6 +843,15 @@ export const METADATA_REFERENCES: readonly ExistingReference[] = [ note: 'IFC provenance written by the IFC converter.', }), ), + meta('poolManagedOpenings[].poolId', { + ...policy('node', 'control', 'drop', 'strip'), + note: 'Pool plugin cuts on a slab: the pool item that owns each opening.', + }), + meta('plateHoleAuthoring', { + ...policy('node', 'internal', 'drop', 'strip'), + targetKinds: ['slab'], + note: 'The plate whose manual hole a floor opening was converted from.', + }), meta('sourceIds[]', { ...policy('source', 'content', 'freeze', 'strip'), note: 'Import provenance: the source element ids an importer recorded (the /next converter writes them); find_nodes filters on them.', @@ -704,6 +875,8 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'deferParentRebuild', 'drawingCoordinationLocked', 'floor', + 'floorOwnershipMigrated', + 'floorReassignmentHeight', 'footprintApproximated', 'generatedBy', 'isFloorplanPreview', @@ -717,9 +890,14 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'leanToPostSide', 'leanToRole', 'leanToRoofPlane', + 'legacyAutoOpeningsMigrated', + 'legacyRoomMigrationPending', 'locked', 'openingManaged', + 'ownerOpeningTarget', 'placementAdjusted', + 'plateMigration', + 'plateMigration.demoted', 'porch', 'renderPass', 'role', @@ -727,14 +905,24 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'storyShell', 'suppressedDimensionSegmentIndexes', ]), - ...described('Read as a truthy flag only; no editor writer.', ['arrayModifier', 'linkedArray']), + ...described('Read as a truthy flag only; no editor writer.', [ + 'arrayModifier', + 'curvedWindowMaster', + 'linkedArray', + ]), + ...described('The owner pose an owned floor opening last followed: values, not ids.', [ + 'ownerPose', + 'ownerPose.position', + 'ownerPose.rotation', + 'ownerPose.runLength', + 'ownerPose.width', + ]), ...described('Display or authoring label written by the MCP tools.', [ 'label', 'name', 'roomName', 'roomType', 'mcpTool', - 'edgeIndex', ]), ...described('IFC attribute copy: a value or IFC label, not an id.', [ 'elevation', @@ -754,8 +942,11 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ ...described('MCP template descriptor metadata, not scene-node metadata.', ['id', 'description']), ...described( 'A `holeMetadata` entry held in a local named `metadata`; inventoried as holeMetadata[].', - ['stairId', 'elevatorId', 'source', 'metadata'], + ['stairId', 'elevatorId', 'openingId', 'source', 'metadata'], ), + ...described('A `holeMetadata` array held in a local named `metadata`: an array method.', [ + 'flatMap', + ]), ...described('Print-export artifact metadata, not scene-node metadata.', ['status']), ...described('Derived floorplan drawing metadata, not scene-node metadata.', [ 'at', diff --git a/packages/core/src/events/bus.ts b/packages/core/src/events/bus.ts index 4a69c5741f..cd6bcfb69c 100644 --- a/packages/core/src/events/bus.ts +++ b/packages/core/src/events/bus.ts @@ -1,7 +1,6 @@ import type { ThreeEvent } from '@react-three/fiber' import mitt from 'mitt' import type { Object3D } from 'three' -import type { ProceduralItemNode } from '../procedural-items/node' import type { BlockNode, BoxVentNode, @@ -39,6 +38,7 @@ import type { RoofNode, RoofSegmentNode, ScanNode, + SeparatorNode, ShelfNode, SiteNode, SkylightNode, @@ -165,6 +165,7 @@ export type PipeTrapEvent = NodeEvent export type LinesetEvent = NodeEvent export type LiquidLineEvent = NodeEvent export type MeasurementEvent = NodeEvent +export type SeparatorEvent = NodeEvent // Event suffixes - exported for use in hooks export const eventSuffixes = [ @@ -180,8 +181,8 @@ export const eventSuffixes = [ export type EventSuffix = (typeof eventSuffixes)[number] -type NodeEvents = { - [K in `${T}:${EventSuffix}`]: E +type NodeEvents = { + [N in AnyNode as `${N['type']}:${EventSuffix}`]: NodeEvent } type GridEvents = { @@ -372,57 +373,7 @@ type SelectionEvents = { type EditorEvents = GridEvents & GenericNodeEvents & - NodeEvents<'procedural-item', NodeEvent> & - NodeEvents<'wall', WallEvent> & - NodeEvents<'fence', FenceEvent> & - NodeEvents<'cabinet', CabinetEvent> & - NodeEvents<'cabinet-module', CabinetModuleEvent> & - NodeEvents<'item', ItemEvent> & - NodeEvents<'imported-mesh', ImportedMeshEvent> & - NodeEvents<'site', SiteEvent> & - NodeEvents<'building', BuildingEvent> & - NodeEvents<'elevator', ElevatorEvent> & - NodeEvents<'unit', UnitEvent> & - NodeEvents<'level', LevelEvent> & - NodeEvents<'lean-to-extension', LeanToExtensionEvent> & - NodeEvents<'zone', ZoneEvent> & - NodeEvents<'slab', SlabEvent> & - NodeEvents<'shelf', ShelfEvent> & - NodeEvents<'spawn', SpawnEvent> & - NodeEvents<'ceiling', CeilingEvent> & - NodeEvents<'column', ColumnEvent> & - NodeEvents<'construction-dimension', ConstructionDimensionEvent> & - NodeEvents<'block', BlockEvent> & - NodeEvents<'roof', RoofEvent> & - NodeEvents<'roof-segment', RoofSegmentEvent> & - NodeEvents<'stair', StairEvent> & - NodeEvents<'stair-segment', StairSegmentEvent> & - NodeEvents<'structural-grid', StructuralGridEvent> & - NodeEvents<'window', WindowEvent> & - NodeEvents<'door', DoorEvent> & - NodeEvents<'scan', ScanEvent> & - NodeEvents<'guide', GuideEvent> & - NodeEvents<'box-vent', BoxVentEvent> & - NodeEvents<'ridge-vent', RidgeVentEvent> & - NodeEvents<'turbine-vent', TurbineVentEvent> & - NodeEvents<'cupola', CupolaEvent> & - NodeEvents<'eyebrow-vent', EyebrowVentEvent> & - NodeEvents<'gutter', GutterEvent> & - NodeEvents<'chimney', ChimneyEvent> & - NodeEvents<'solar-panel', SolarPanelEvent> & - NodeEvents<'skylight', SkylightEvent> & - NodeEvents<'dormer', DormerEvent> & - NodeEvents<'downspout', DownspoutEvent> & - NodeEvents<'duct-segment', DuctSegmentEvent> & - NodeEvents<'duct-fitting', DuctFittingEvent> & - NodeEvents<'duct-terminal', DuctTerminalEvent> & - NodeEvents<'hvac-equipment', HvacEquipmentEvent> & - NodeEvents<'pipe-segment', PipeSegmentEvent> & - NodeEvents<'pipe-fitting', PipeFittingEvent> & - NodeEvents<'pipe-trap', PipeTrapEvent> & - NodeEvents<'lineset', LinesetEvent> & - NodeEvents<'liquid-line', LiquidLineEvent> & - NodeEvents<'measurement', MeasurementEvent> & + NodeEvents & CameraControlEvents & ToolEvents & GuideEvents & diff --git a/packages/core/src/hooks/spatial-grid/floor-placed-elevation.test.ts b/packages/core/src/hooks/spatial-grid/floor-placed-elevation.test.ts index 21c9eb5a64..62740214e7 100644 --- a/packages/core/src/hooks/spatial-grid/floor-placed-elevation.test.ts +++ b/packages/core/src/hooks/spatial-grid/floor-placed-elevation.test.ts @@ -143,6 +143,54 @@ describe('floor-placed elevation resolver', () => { ).toBe(0) }) + test('items pinned to the base follow solid platforms while ignoring an open mezzanine above', () => { + registerNode( + makeDefinition('item', { + floorPlaced: { footprint: () => ({ dimensions: [1, 1, 1], rotation: [0, 0, 0] }) }, + }), + ) + const polygon: [number, number][] = [ + [-2, -2], + [2, -2], + [2, 2], + [-2, 2], + ] + const level = makeLevel() + const base = { + id: 'slab_base', + type: 'slab', + parentId: LEVEL_ID, + polygon, + holes: [], + elevation: 0.05, + thickness: 0.05, + plateRole: 'base', + } as SlabNode + const platform = { + ...base, + id: 'slab_platform', + elevation: 0.55, + thickness: 0.5, + plateRole: 'platform', + } as SlabNode + const mezzanine = { + ...base, + id: 'slab_mezzanine', + elevation: 2, + thickness: 0.2, + plateRole: undefined, + support: 'open', + } as SlabNode + const item = makeFloorNode({ supportSlabId: base.id } as Partial) + for (const slab of [base, platform, mezzanine]) + spatialGridManager.handleNodeCreated(slab, LEVEL_ID) + const nodes = nodesFor(level, base, platform, mezzanine, item) + expect(getFloorPlacedElevation({ node: item, nodes, position: [0, 0, 0] })).toBe(0.55) + expect( + getFloorPlacedElevation({ node: item, nodes, position: [0, 0, 0], maxElevation: 0.1 }), + ).toBe(0.05) + }) + test('canPlaceOnFloorFootprints accepts an L-shaped draft in the open corner gap', () => { const baseAsset = (makeFloorNode() as { asset: Record }).asset registerNode( diff --git a/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts b/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts index 3a8deea1b6..f1c68c2bb3 100644 --- a/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts +++ b/packages/core/src/hooks/spatial-grid/floor-placed-elevation.ts @@ -1,3 +1,4 @@ +import { floorConstructionLift } from '../../lib/floor-construction-lift' import { levelBaseElevationAt } from '../../lib/terrain-support' import { nodeRegistry } from '../../registry' import type { @@ -5,7 +6,7 @@ import type { FloorPlacedFootprintContext, FloorPlacedFootprintsResolver, } from '../../registry/types' -import type { AnyNode, AnyNodeId } from '../../schema' +import type { AnyNode, AnyNodeId, SlabNode } from '../../schema' import { getFloorPlacedFootprints } from './floor-placed-footprints' export { getFloorPlacedFootprints } from './floor-placed-footprints' @@ -99,7 +100,9 @@ export function getFloorPlacedElevation({ */ let groundLiftCache: number | null = null const groundLift = (): number => { - groundLiftCache ??= levelBaseElevationAt(nodes, resolvedLevelId, position[0], position[2]) + groundLiftCache ??= + levelBaseElevationAt(nodes, resolvedLevelId, position[0], position[2]) + + floorConstructionLift(nodes, effectiveNode) return groundLiftCache } @@ -112,7 +115,25 @@ export function getFloorPlacedElevation({ const supportSlabId = (effectiveNode as { supportSlabId?: string | null }).supportSlabId if (maxElevation == null && supportSlabId) { if (supportSlabId === GROUND_SUPPORT_ID) return groundLift() + const host = nodes[supportSlabId] for (const footprint of footprints) { + if (host?.type === 'slab' && host.plateRole === 'base') { + const coverings = spatialGridManager + .getSupportCandidatesForFootprint( + resolvedLevelId, + footprint.position ?? position, + footprint.dimensions, + footprint.rotation, + ) + .map((candidate) => nodes[candidate.slabId]) + .filter( + (candidate): candidate is SlabNode => + candidate?.type === 'slab' && candidate.plateRole === 'platform', + ) + .sort((a, b) => b.elevation - a.elevation) + const covering = coverings[0] + if (covering) return finiteSlabElevation(covering.elevation) + } const hosted = spatialGridManager.getHostSlabElevationForFootprint( resolvedLevelId, supportSlabId, diff --git a/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts b/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts index f642f85bfa..47fae8d9ed 100644 --- a/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts +++ b/packages/core/src/hooks/spatial-grid/spatial-grid-manager.ts @@ -1,3 +1,4 @@ +import { liftedManualSlab } from '../../lib/floor-construction-lift' import { itemOverlapsPolygon } from '../../lib/item-polygon-overlap' import { type PlanAabb, planFootprintAABB, planFootprintCorners } from '../../lib/plan-footprint' import { getRenderableSlabPolygon } from '../../lib/slab-polygon' @@ -7,6 +8,7 @@ import type { AnyNode, AnyNodeId, CeilingNode, ItemNode, SlabNode, WallNode } fr import { getScaledDimensions, isLowProfileItemSurface } from '../../schema' import { getWallPlaneTop } from '../../services/storey' import useLiveNodeOverrides, { getEffectiveNode } from '../../store/use-live-node-overrides' +import useLiveTerrain from '../../store/use-live-terrain' import useLiveTransforms from '../../store/use-live-transforms' import useScene from '../../store/use-scene' import { @@ -14,12 +16,13 @@ import { pointInPolygon, SUPPORT_ELEVATION_EPSILON, type WallSlabSupport, + wallOverlapsPolygon, } from '../../systems/slab/slab-support' import { DEFAULT_WALL_THICKNESS } from '../../systems/wall/wall-footprint' +import type { WallJustification } from '../../systems/wall/wall-frame' import { resolveWallEffectiveHeight } from '../../systems/wall/wall-top' import { getFloorPlacedFootprints } from './floor-placed-elevation' import { SpatialGrid } from './spatial-grid' -import { GROUND_SUPPORT_ID } from './support-host-id' import { WallSpatialGrid } from './wall-spatial-grid' export { itemOverlapsPolygon } from '../../lib/item-polygon-overlap' @@ -238,7 +241,6 @@ export class SpatialGridManager { private getWallHeight(wallId: string): number { const wall = this.walls.get(wallId) if (!wall) return 0 - if (wall.height != null) return wall.height const nodes = useScene.getState().nodes const levelId = resolveNodeLevelId(wall, nodes) @@ -251,6 +253,7 @@ export class SpatialGridManager { wall.supportSlabId ?? null, undefined, wall.supportOffset, + wall.justification, ) return resolveWallEffectiveHeight( wall, @@ -342,7 +345,7 @@ export class SpatialGridManager { } } } - return effective + return liftedManualSlab(useScene.getState().nodes, effective) } private getRenderedSlabPolygon(levelId: string, slab: SlabNode): Array<[number, number]> { @@ -918,9 +921,19 @@ export class SpatialGridManager { curveOffset = 0, thickness = DEFAULT_WALL_THICKNESS, preferredSlabId?: string | null, + justification?: WallJustification, ): number { - return this.getSlabSupportForWall(levelId, start, end, curveOffset, thickness, preferredSlabId) - .elevation + return this.getSlabSupportForWall( + levelId, + start, + end, + curveOffset, + thickness, + preferredSlabId, + undefined, + 0, + justification, + ).elevation } getSlabSupportForWall( @@ -932,22 +945,13 @@ export class SpatialGridManager { preferredSlabId?: string | null, maxElevation?: number | null, supportOffset = 0, + justification?: WallJustification, ): WallSlabSupport { // Sampled at the wall's own start point — the same anchor the mesh is // positioned at, so the resolver and the renderer cannot disagree about // where the ground is under this wall. const levelBase = levelBaseElevationAt(useScene.getState().nodes, levelId, start[0], start[1]) - if (preferredSlabId === GROUND_SUPPORT_ID) { - const elevation = levelBase + supportOffset - return { - elevation, - electedSlabId: null, - baseElevation: elevation, - baseSegments: [{ start: 0, end: 1, elevation }], - } - } - const slabMap = this.slabsByLevel.get(levelId) if (!slabMap) { const elevation = levelBase + supportOffset @@ -956,29 +960,29 @@ export class SpatialGridManager { electedSlabId: null, baseElevation: elevation, baseSegments: [{ start: 0, end: 1, elevation }], + faceDatum: { a: [{ start: 0, end: 1, elevation }], b: [{ start: 0, end: 1, elevation }] }, + faceBottom: { a: [{ start: 0, end: 1, elevation }], b: [{ start: 0, end: 1, elevation }] }, } } const inputs = this.getSupportInputs(levelId, slabMap) const support = computeWallSlabSupport( - { start, end, curveOffset, thickness }, + { start, end, curveOffset, thickness, justification, supportOffset }, inputs.slabs, inputs.walls, preferredSlabId, maxElevation, levelBase, + inputs.supportNodes, + inputs.baseAt, + inputs.terrainPlates.some((slab) => + wallOverlapsPolygon({ start, end, curveOffset, thickness, justification }, slab.polygon), + ) + ? useLiveTerrain.getState() + : undefined, ) - if (supportOffset === 0) return support - return { - ...support, - elevation: support.elevation + supportOffset, - baseElevation: support.baseElevation + supportOffset, - baseSegments: support.baseSegments.map((segment) => ({ - ...segment, - elevation: segment.elevation + supportOffset, - })), - } + return support } /** @@ -998,8 +1002,11 @@ export class SpatialGridManager { nodes: object overrides: object transforms: object + terrainPlates: SlabNode[] + baseAt: (x: number, z: number) => number slabs: SlabNode[] walls: WallNode[] + supportNodes: Record } >() @@ -1018,12 +1025,43 @@ export class SpatialGridManager { return cached } + const slabs = [...slabMap.values()].map((slab) => { + const effective = this.effectiveSlabRecord(slab) + const lifted = liftedManualSlab(nodes, slab) + return lifted === slab + ? effective + : { ...effective, elevation: effective.elevation - (lifted.elevation - slab.elevation) } + }) + const supportNodes: Record = slabs.some( + (slab) => slab.plateRole === 'base' && slab.floorHeight !== undefined, + ) + ? { ...nodes } + : {} + for (const slab of slabs) + for (const id of slab.zoneIds ?? []) { + const zone = nodes[id as AnyNodeId] + if (zone?.type === 'zone') supportNodes[id] = getEffectiveNode(zone) + } + for (const node of Object.values(nodes)) + if (node.parentId === levelId && (node.type === 'separator' || node.type === 'zone')) + supportNodes[node.id] = getEffectiveNode(node) + for (const node of Object.values(nodes)) + if (node.type === 'site' || node.type === 'building' || node.type === 'level') + supportNodes[node.id] = node const next = { revision: this.supportInputsRevision, nodes, overrides, transforms, - slabs: [...slabMap.values()].map((slab) => this.effectiveSlabRecord(slab)), + terrainPlates: slabs.filter( + (slab) => + slab.boundary === 'auto' && + !slab.recessed && + (slab.elevation - slab.thickness > 1e-4 || slab.elevation < -1e-4), + ), + baseAt: (x: number, z: number) => levelBaseElevationAt(nodes, levelId, x, z), + slabs, + supportNodes, walls: this.getLevelWallNodes(levelId).map((wall) => getEffectiveNode(wall)), } this.supportInputs.set(levelId, next) @@ -1173,6 +1211,7 @@ export function getWallBaseElevationForNodes( wall.supportSlabId ?? null, undefined, wall.supportOffset, + wall.justification, ).elevation } @@ -1189,6 +1228,16 @@ export function getWallEffectiveHeightForNodes( nodes: Record, ): number { const levelId = resolveNodeLevelId(wall, nodes) - const baseElevation = getWallBaseElevationForNodes(wall, nodes) - return resolveWallEffectiveHeight(wall, getWallPlaneTop(wall, levelId, nodes), baseElevation) + const support = spatialGridManager.getSlabSupportForWall( + levelId, + wall.start, + wall.end, + wall.curveOffset ?? 0, + wall.thickness, + wall.supportSlabId ?? null, + undefined, + wall.supportOffset, + wall.justification, + ) + return resolveWallEffectiveHeight(wall, getWallPlaneTop(wall, levelId, nodes), support.elevation) } diff --git a/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts b/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts index 0d173b6149..969377cb7e 100644 --- a/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts +++ b/packages/core/src/hooks/spatial-grid/spatial-grid-sync.ts @@ -1,6 +1,12 @@ +import { resolveLevelId } from '../../lib/node-ancestry' +import { isFloorPlate } from '../../lib/plate-surface' import { subtractPolygonsFromPolygon } from '../../lib/polygon-union' import { getRenderableSlabPolygon } from '../../lib/slab-polygon' -import { isLevelAtSiteDatum, isLevelBaseConsumer } from '../../lib/terrain-support' +import { + isLevelAtSiteDatum, + isLevelBaseConsumer, + levelBaseElevationAt, +} from '../../lib/terrain-support' import { nodeRegistry } from '../../registry' import type { AnyNode, AnyNodeId, LevelNode, SiteNode, SlabNode, WallNode } from '../../schema' import { getLevelBelow } from '../../services/storey' @@ -14,86 +20,11 @@ import { } from './spatial-grid-manager' import { GROUND_SUPPORT_ID } from './support-host-id' -export function resolveLevelId(node: AnyNode, nodes: Record): string { - // If the node itself is a level - if (node.type === 'level') return node.id - - // Walk up parent chain to find level - // This assumes you track parentId or can derive it - let current: AnyNode | undefined = node - - while (current) { - if (current.type === 'level') return current.id - // Find parent (you might need to add parentId to your schema or derive it) - if (current.parentId) { - current = nodes[current.parentId] - } else { - current = undefined - } - } - - return 'default' // fallback for orphaned items -} - -/** - * Walks the parent chain of `nodeId` and returns the id of the first ancestor - * whose `type` is `'level'`, or `null` when no level ancestor exists (orphaned - * node, top-level building node, etc.). Unlike `resolveLevelId`, this variant: - * - * - accepts a node **id** rather than a resolved node, saving the caller a - * `nodes[id]` lookup when only the id is at hand. - * - returns `null` instead of the `'default'` fallback, which lets callers - * distinguish "genuinely has no level" from "is a level". - * - has a loop guard (16 iterations) so a corrupt parent-chain cycle cannot - * hang the frame loop. - */ -export function findLevelAncestorId( - nodeId: AnyNodeId, - nodes: Record, -): string | null { - let current: AnyNode | undefined = nodes[nodeId] - let guard = 0 - while (current && guard < 16) { - if (current.type === 'level') return current.id - current = current.parentId ? nodes[current.parentId] : undefined - guard += 1 - } - return null -} - -/** - * Returns the building id that contains the given level, or `null` if - * the level is unparented or no enclosing building exists. - * - * Most scenes record the relationship via `level.parentId → - * building.id`, but older serialisations occasionally drop `parentId` - * even though the building's `children` array still references the - * level. The fallback scan covers that case. - * - * Used by `FloorplanRegistryLayer` to discover building-scoped kinds - * (`def.floorplanScope === 'building'`) without hardcoding any kind - * name in the editor layer. - */ -export function resolveBuildingForLevel( - levelId: AnyNodeId, - nodes: Record, -): AnyNodeId | null { - const level = nodes[levelId] as AnyNode | undefined - if (!level) return null - const directParent = (level as { parentId?: AnyNodeId | null }).parentId ?? null - if (directParent) { - const candidate = nodes[directParent] - if (candidate?.type === 'building') return candidate.id as AnyNodeId - } - for (const candidate of Object.values(nodes)) { - if (candidate?.type !== 'building') continue - const children = (candidate as { children?: AnyNodeId[] }).children - if (Array.isArray(children) && children.includes(levelId)) { - return candidate.id as AnyNodeId - } - } - return null -} +export { + findLevelAncestorId, + resolveBuildingForLevel, + resolveLevelId, +} from '../../lib/node-ancestry' // Call this once at app initialization. Returns an unsubscribe function that // detaches the scene-store listener (useful when the editor is unmounted so @@ -121,6 +52,7 @@ export function initSpatialGridSync(): () => void { countBulkSlabChanges(state.nodes, prevState.nodes) >= BULK_SLAB_CHANGE_THRESHOLD if (bulkSlabs) markAllSlabDependents(state.nodes, markDirty) const changedSlabContextLevels = new Set() + const changedRoomSupportLevels = new Set() const checkSlabContext = (id: string) => { const previous = prevState.nodes[id as AnyNodeId] const next = state.nodes[id as AnyNodeId] @@ -133,6 +65,7 @@ export function initSpatialGridSync(): () => void { previous.start !== next.start || previous.end !== next.end || previous.thickness !== next.thickness || + previous.justification !== next.justification || previous.curveOffset !== next.curveOffset) const slabChanged = (previous?.type === 'slab' || next?.type === 'slab') && @@ -141,16 +74,47 @@ export function initSpatialGridSync(): () => void { previous.parentId !== next.parentId || previous.polygon !== next.polygon || previous.elevation !== next.elevation) + const roomChanged = + (previous?.type === 'zone' || next?.type === 'zone') && + (previous?.type !== 'zone' || + next?.type !== 'zone' || + previous.parentId !== next.parentId || + previous.polygon !== next.polygon || + previous.holes !== next.holes || + previous.boundarySeparatorIds !== next.boundarySeparatorIds || + previous.boundaryWallIds !== next.boundaryWallIds || + previous.spaceRole !== next.spaceRole || + previous.floor?.elevation !== next.floor?.elevation || + previous.hasFloor !== next.hasFloor) + const separatorChanged = + (previous?.type === 'separator' || next?.type === 'separator') && + (previous?.type !== 'separator' || + next?.type !== 'separator' || + previous.parentId !== next.parentId || + previous.start !== next.start || + previous.end !== next.end) + if (roomChanged || separatorChanged) { + if (previous) changedRoomSupportLevels.add(resolveLevelId(previous, prevState.nodes)) + if (next) changedRoomSupportLevels.add(resolveLevelId(next, state.nodes)) + } if (!(wallChanged || slabChanged)) return if (previous) changedSlabContextLevels.add(resolveLevelId(previous, prevState.nodes)) if (next) changedSlabContextLevels.add(resolveLevelId(next, state.nodes)) } - for (const id in prevState.nodes) checkSlabContext(id) + for (const id in prevState.nodes) { + if (Object.hasOwn(prevState.nodes, id)) checkSlabContext(id) + } for (const id in state.nodes) { if (!prevState.nodes[id as AnyNodeId]) checkSlabContext(id) } + if (changedRoomSupportLevels.size) + for (const node of Object.values(state.nodes)) { + if (node.type === 'wall' && changedRoomSupportLevels.has(resolveLevelId(node, state.nodes))) + markDirty(node.id) + } + // Detect added nodes for (const [id, node] of Object.entries(state.nodes)) { if (!prevState.nodes[id as AnyNode['id']]) { @@ -249,7 +213,8 @@ export function initSpatialGridSync(): () => void { node.start !== prev.start || node.end !== prev.end || node.curveOffset !== prev.curveOffset || - node.thickness !== prev.thickness + node.thickness !== prev.thickness || + node.justification !== prev.justification ) { // Rendered slab polygons adopt wall bands, so a wall reshape // must reach the manager to refresh its wall map and drop the @@ -334,6 +299,7 @@ export function countBulkSlabChanges( ): number { let count = 0 for (const id in nodes) { + if (!Object.hasOwn(nodes, id)) continue const node = nodes[id]! if (node.type !== 'slab') continue const prev = prevNodes[id] @@ -362,6 +328,7 @@ export function markAllSlabDependents( markDirty: (id: AnyNodeId) => void, ) { for (const id in nodes) { + if (!Object.hasOwn(nodes, id)) continue const node = nodes[id]! if (node.type === 'wall' || node.type === 'ceiling' || node.type === 'stair') { markDirty(node.id) @@ -377,7 +344,8 @@ export function markAllSlabDependents( } } -function arraysEqual(a: number[], b: number[]): boolean { +function arraysEqual(a: unknown, b: unknown): boolean { + if (!Array.isArray(a) || !Array.isArray(b)) return a === b return a.length === b.length && a.every((v, i) => v === b[i]) } @@ -483,10 +451,47 @@ export function markSlabChangeDependents( * decide whether it drapes at all, so the two cannot disagree about which storey * is on the ground. */ +const terrainPlateDependents = new WeakMap>() + export function markTerrainSupportDependents( nodes: Record, markDirty: (id: AnyNodeId) => void, ) { + const plates = Object.values(nodes).filter( + (node): node is SlabNode => + node.type === 'slab' && + isFloorPlate(node) && + !node.recessed && + (node.elevation - node.thickness > 1e-4 || node.elevation < -1e-4), + ) + const previous = terrainPlateDependents.get(nodes) ?? new Set() + const active = new Set() + for (const plate of plates) { + if ( + plate.elevation < -1e-4 || + plate.polygon.some(([x, z], i) => { + const [endX, endZ] = plate.polygon[(i + 1) % plate.polygon.length]! + const count = Math.max(1, Math.ceil(Math.hypot(endX - x, endZ - z) / 0.25)) + for (let j = 0; j <= count; j++) + if ( + plate.elevation - plate.thickness > + levelBaseElevationAt( + nodes, + resolveLevelId(plate, nodes), + x + ((endX - x) * j) / count, + z + ((endZ - z) * j) / count, + ) + + 1e-4 + ) + return true + return false + }) + ) + active.add(plate.id) + } + terrainPlateDependents.set(nodes, active) + // Retain one sweep of former dependents when a dab closes their last ground gap. + const affected = plates.filter((plate) => active.has(plate.id) || previous.has(plate.id)) const gradeLevels = new Map() const isGrade = (levelId: string) => { let cached = gradeLevels.get(levelId) @@ -498,13 +503,33 @@ export function markTerrainSupportDependents( } for (const node of Object.values(nodes)) { - if (node.type === 'slab' && node.fillToTerrain === true) { - if (isGrade(resolveLevelId(node, nodes))) markDirty(node.id) + if (node.type === 'slab') { + const level = nodes[resolveLevelId(node, nodes)] + if ( + node.plateRole === 'base' && + node.foundation?.type === 'solid' && + (isGrade(resolveLevelId(node, nodes)) || (level?.type === 'level' && level.level === 0)) + ) { + markDirty(node.id) + continue + } + if ( + (node.fillToTerrain === true || (node.elevation > 0 && affected.includes(node))) && + isGrade(resolveLevelId(node, nodes)) + ) + markDirty(node.id) continue } if (node.type === 'wall') { - if (node.supportSlabId !== GROUND_SUPPORT_ID && node.fillToTerrain !== true) continue + if ( + node.supportSlabId !== GROUND_SUPPORT_ID && + node.fillToTerrain !== true && + !affected.some( + (plate) => plate.parentId === node.parentId && wallOverlapsPolygon(node, plate.polygon), + ) + ) + continue if (!isGrade(resolveLevelId(node, nodes))) continue markDirty(node.id) continue @@ -607,6 +632,7 @@ function markNodesOverlappingPolygon( end: wall.end, curveOffset: wall.curveOffset ?? 0, thickness: wall.thickness, + justification: wall.justification, }, renderedPolygon, ) @@ -657,6 +683,7 @@ type SlabBoundaryContext = { function slabBoundaryContext(nodes: Record, levels: Set) { const contexts = new Map() for (const id in nodes) { + if (!Object.hasOwn(nodes, id)) continue const node = nodes[id]! const floorPlaced = nodeRegistry.get(node.type)?.capabilities?.floorPlaced if (node.type !== 'wall' && node.type !== 'slab' && !floorPlaced) continue diff --git a/packages/core/src/hooks/spatial-grid/support-host-patch.ts b/packages/core/src/hooks/spatial-grid/support-host-patch.ts index 3d5deb3cac..06b1abb6b4 100644 --- a/packages/core/src/hooks/spatial-grid/support-host-patch.ts +++ b/packages/core/src/hooks/spatial-grid/support-host-patch.ts @@ -136,7 +136,7 @@ export function resolveFrozenFloorPlacementPatch( const effectiveNode = { ...(node as Record), position: options.position, - ...(options.rotation !== undefined ? { rotation: options.rotation } : {}), + ...(options.rotation === undefined ? {} : { rotation: options.rotation }), } as AnyNode const floorPlaced = nodeRegistry.get(effectiveNode.type)?.capabilities?.floorPlaced if (!floorPlaced || (floorPlaced.applies && !floorPlaced.applies(effectiveNode))) { @@ -187,6 +187,8 @@ export function resolveWallSupportSlabPatch( wall.thickness, options?.preferredSlabId, options?.maxElevation, + undefined, + wall.justification, ) const candidateElevations = new Set() for (const node of Object.values(nodes)) { @@ -199,6 +201,9 @@ export function resolveWallSupportSlabPatch( wall.curveOffset, wall.thickness, candidate.id, + undefined, + undefined, + wall.justification, ) if (preferred.electedSlabId === candidate.id) { candidateElevations.add(candidate.elevation) @@ -412,7 +417,7 @@ export function resolveTerrainWallConstructionOptions( defaults?: Record, ): WallConstructionOptions | undefined { const constructionElevation = terrainSupportLift(nodes, levelId, point[0], point[1]) - if (constructionElevation == null) return undefined + if (constructionElevation == null) return const level = nodes[levelId] const constructionHeight = @@ -498,6 +503,8 @@ export function resolveWallConstruction( createdWall.thickness, supportPatch.supportSlabId, wallOptions?.supportCap ?? null, + undefined, + createdWall.justification, ) const groundDraft = preferredSupportSlabId === GROUND_SUPPORT_ID && (terrainBase != null || flatConstructionBase) diff --git a/packages/core/src/hooks/spatial-grid/support-host.test.ts b/packages/core/src/hooks/spatial-grid/support-host.test.ts index 0e3580c7ad..3736bbbbb1 100644 --- a/packages/core/src/hooks/spatial-grid/support-host.test.ts +++ b/packages/core/src/hooks/spatial-grid/support-host.test.ts @@ -436,6 +436,14 @@ describe('persisted support hosts (walls, via the manager)', () => { electedSlabId: null, baseElevation: 1.75, baseSegments: [{ start: 0, end: 1, elevation: 1.75 }], + faceBottom: { + a: [{ start: 0, end: 1, elevation: 1.75 }], + b: [{ start: 0, end: 1, elevation: 1.75 }], + }, + faceDatum: { + a: [{ start: 0, end: 1, elevation: 1.75 }], + b: [{ start: 0, end: 1, elevation: 1.75 }], + }, }) }) diff --git a/packages/core/src/hooks/spatial-grid/wall-elevation-parity.test.ts b/packages/core/src/hooks/spatial-grid/wall-elevation-parity.test.ts new file mode 100644 index 0000000000..58b7809cda --- /dev/null +++ b/packages/core/src/hooks/spatial-grid/wall-elevation-parity.test.ts @@ -0,0 +1,37 @@ +import { expect, test } from 'bun:test' +import { SlabNode, WallNode } from '../../schema' +import { SpatialGridManager } from './spatial-grid-manager' + +test.each([ + 'a', + 'b', +] as const)('wall elevation wrapper matches body support for justification %s', (justification) => { + const levelId = 'level_wall-elevation-parity' + const side = justification === 'a' ? 1 : -1 + const wall = WallNode.parse({ + parentId: levelId, + start: [0, 0], + end: [4, 0], + thickness: 0.2, + justification, + }) + const slab = SlabNode.parse({ + parentId: levelId, + elevation: 0.6, + polygon: [ + [-1, side * 0.15], + [5, side * 0.15], + [5, side], + [-1, side], + ], + }) + const manager = new SpatialGridManager() + manager.handleNodeCreated(wall, levelId) + manager.handleNodeCreated(slab, levelId) + const args = [levelId, wall.start, wall.end, 0, wall.thickness, wall.supportSlabId] as const + + expect(manager.getSlabElevationForWall(...args)).toBe(0) + const support = manager.getSlabSupportForWall(...args, undefined, 0, wall.justification) + expect(support.elevation).toBe(0.6) + expect(manager.getSlabElevationForWall(...args, wall.justification)).toBe(support.elevation) +}) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 27eef2b09c..e707f8e4cf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,3 +1,4 @@ +export * from './commands/structure' export type { BlockEvent, BoxVentEvent, @@ -30,6 +31,7 @@ export type { RoofSegmentEvent, RoomPresetCreateEvent, ScanEvent, + SeparatorEvent, ShelfEvent, SiteEvent, SkylightEvent, @@ -106,6 +108,16 @@ export { resolveAssemblyStack, } from './lib/assembly-stack' export { loadAssetUrl, saveAsset } from './lib/asset-storage' +export { + CEILING_SURFACE_ROLE, + type CeilingSurfaceCell, + ceilingPaintRegions, + ceilingRegionRole, + ceilingRegionsOwner, + ceilingSurfaceSignature, + computeCeilingSurfaceCells, + parseCeilingRegionRole, +} from './lib/ceiling-surface' export { clampDoorOperationState, getDoorRenderOpenAmount, @@ -113,6 +125,48 @@ export { isOperationDoorType, SECTIONAL_GARAGE_RENDER_OPEN_SCALE, } from './lib/door-operation' +export { floorConstructionLift, liftedManualSlab } from './lib/floor-construction-lift' +export { floorFootprintName } from './lib/floor-footprint-name' +export { + automaticFloorHeight, + floorFootprintSupportClass, + floorPlateAtGroundContact, + floorPlateGestureMinimum, + floorPlateHoldsUnderside, + footprintLift, + groundFloorConstruction, + resolvedFootprintPlane, + upperFloorHeightControl, +} from './lib/floor-foundation-datum' +export { changedLevelConstructionDisplacements } from './lib/floor-foundation-stack' +export { + isFloorAnchoredOpening, + openingAperture, + openingLandings, +} from './lib/floor-opening-footprints' +export { + adjacentLevelId, + floorOpeningTargets, + openingsForSurface, +} from './lib/floor-opening-intent' +export { type FloorPlatePaintRefusal, floorPlatePaintRefusal } from './lib/floor-plate-paint' +export { + type FloorStepOverride, + floorStepOverrideFor, + floorStepRole, + floorStepRoleCovers, + parseFloorStepRole, + remapFloorStepOverrideKeys, + resolveFloorStepFinish, + withFloorStepOverride, + withoutFloorStepOverrideKeys, +} from './lib/floor-step-finish' +export { + type ExposedInterval, + exposedIntervals, + plateFootprint, + roomClearPolygon, +} from './lib/level-footprints' export { getDefaultLevelName, getLevelDisplayName } from './lib/level-name' export { areMeasurementPointsCoplanar, @@ -134,6 +188,46 @@ export { remapMeasurementReferences, } from './lib/measurement-geometry' export { HIDDEN_SITE_NOTE, hidesDescendants } from './lib/node-visibility' +export { + getOpeningFloorDatum, + getOpeningWallCut, + getOpeningWallPlacement, + openingDatumFromSupport, + wallSupportForNodes, +} from './lib/opening-floor-datum' +export { + classifyPlateSideAt, + clearPlateSurfaceCaches, + computePlateSurfacePartition, + floorStepKeysOf, + isFloorPlate, + levelWallCover, + type PlateFinish, + type PlateLevelContext, + type PlateSideInterval, + type PlateSideRole, + type PlateSurfacePartition, + type PlateTopCell, + parseRoomFinishRole, + plateFinishKey, + plateLevelContext, + platePartitionSignature, + plateSideRuns, + roomFinishRole, +} from './lib/plate-surface' +export { + area, + containsPoint, + difference, + distanceToBoundary, + intersection, + type MultiPolygon, + type Polygon, + type PolygonInput, + type Ring, + union, +} from './lib/polygon-boolean' +export { polygonInteriorPoint } from './lib/polygon-label' export { type Point2D as PolygonPoint2D, pointInPolygon as pointInPolygon2D, @@ -159,6 +253,30 @@ export { roofPlanBoundsOverlap, roofPlanOverlapEntryOwns, } from './lib/roof-overlap' +export { type RoomDrawnFloor, roomDrawnFloor } from './lib/room-drawn-floor' +export { type RoomFloorChoice, roomFloorChoices } from './lib/room-floor-choices' +export { + checkRoomFloor, + clampRoomFloorHandle, + FLOOR_ELEVATION_EPSILON, + getRoomBaseElevation, + getRoomRelativeFloorElevation, + MIN_GROUND_FLOOR_THICKNESS, + MIN_SLAB_THICKNESS, + type RoomFloorConflict, + roomFloorElevationFromRelative, + roundFloorElevation, +} from './lib/room-floor-feasibility' +export { + type BoundaryNode, + type BoundarySpan, + type ExteriorBoundarySpan, + type IndexedTopologyDelta, + type LevelFootprintContext, + type LevelTopology, + RoomTopologyIndex, + type TopologyRoom, +} from './lib/room-topology-index' export { resolveSelectionProxyId, selectionProxyIdFromMetadata } from './lib/selection-proxy' export { arcRuns, @@ -183,29 +301,37 @@ export { deriveSlotId, isSlotMaterialName, SLOT_MATERIAL_PREFIX, + slotDefaultPaintMaterial, slotLabelFromId, } from './lib/slots' export { - type AutoCeilingPlanningContext, - type AutoCeilingSyncPlan, - type AutoSlabPlanningContext, - type AutoSlabSyncPlan, - type AutoZoneSyncPlan, - createWallBoundSurfaceFollower, + createRoomTopologyIndex, detectSpacesForLevel, + type ExtractedRoom, + extractRooms, initSpaceDetectionSync, isSpaceDetectionPaused, pauseSpaceDetection, - planAutoCeilingsForLevel, - planAutoSlabsForLevel, - planAutoZonesForLevel, - resolveAutoZonePolygon, resumeSpaceDetection, type Space, type SpaceBoundaryFace, wallClosesRoom, wallTouchesOthers, } from './lib/space-detection' +export { applyStructureReconciliation } from './lib/structure-commit' +export { + createLevelStructurePreview, + type LevelStructureSnapshot, + type NodePatch, + reconcileLevelStructure, + type StructureEvent, +} from './lib/structure-kernel' +export { + reconcileSceneStructure, + type SceneStructureInput, + type SceneStructureResult, + type StructureIdFactory, +} from './lib/structure-reconcile' export { advanceStroke, type BrushSettings, @@ -332,13 +458,25 @@ export { type NodeDeletionPlan, type NodeDeletionScene, planNodeDeletion, + planSceneNodeChanges, previewDefaultGutterRefresh, } from './store/actions/node-actions' +export { + assertDerivedNodeWrites, + type DerivedNodeChanges, + DerivedNodeWriteError, + type DerivedSurfaceNode, + type DerivedWriteOperation, + derivedDeletionIntent, + derivedFieldViolations, + isDerivedNode, +} from './store/derived-node-guard' export { acquireSceneHistoryPause, activeSceneCommitNodeIds, beginSceneHistoryPauseSession, getSceneHistoryPauseDepth, + isApplyingRemoteSceneChange, pauseSceneHistory, resetSceneHistoryPauseDepth, resumeSceneHistory, @@ -353,6 +491,7 @@ export { } from './store/history-control' export { withSceneHistoryDraftSuspended } from './store/history-drafts' export { getHistoryDirtyNodeIds } from './store/history-invalidation' +export { materializeRegisteredNodeDefaults } from './store/registered-node-defaults' export { type ControlValue, type DoorAnimationState, @@ -443,6 +582,7 @@ export { isSplineFence, sampleFenceSpline, } from './systems/fence/fence-spline' +export { planOwnedFloorOpenings } from './systems/owned-floor-openings' export { resolveRoofElevation, resolveRoofWallTopElevation } from './systems/roof/roof-elevation' export { RoofElevationSystem } from './systems/roof/roof-elevation-system' export { @@ -454,19 +594,32 @@ export { export { resolveSlabPlacementElevation } from './systems/slab/slab-placement' export { clampSlabElevationForWalls, + computeWallSlabSupport, getSlabElevationUpperBound, + resolveWallFaceBottom, type SlabElevationClamp, + type WallSlabSupport, } from './systems/slab/slab-support' export { createDefaultStairSegment, createStairFlightFromStair, type StairFlightOverrides, } from './systems/stair/stair-flight' -export { type StairFootprintAABB, stairFootprintAABB } from './systems/stair/stair-footprint' +export { + computeStairSegmentFloorStackTransforms, + getStairFloorPlacedFootprints, + getStairSegmentFloorPlacedFootprints, +} from './systems/stair/stair-floor-footprints' +export { + type StairFootprintAABB, + stairDeckLevelId, + stairFootprintAABB, +} from './systems/stair/stair-footprint' export { createSurfaceOpeningPreviewController } from './systems/stair/stair-opening-preview' export { syncAutoStairOpenings } from './systems/stair/stair-opening-sync' export { StairOpeningSystem } from './systems/stair/stair-opening-system' export { resolveStairTotalRise, syncStairRises } from './systems/stair/stair-rise' +export { stairHasNoRise } from './systems/stair/stair-rise-query' export { assemblyThickness, BRICK_AIR_SPACE, @@ -514,6 +667,7 @@ export { getWallChordFrame, getWallCurveFrameAt, getWallCurveLength, + getWallCurveStationAtPoint, getWallMidpointHandlePoint, getWallStraightSnapOffset, getWallSurfacePolygon, @@ -521,12 +675,46 @@ export { normalizeWallCurveOffset, sampleWallCenterline, } from './systems/wall/wall-curve' +export { + buildWallFinishLayout, + getWallLevelZones, + getWallZoneSpans, + parseWallPaintRole, + resolveWallFaceChain, + resolveWallFinish, + type WallFaceChainFinish, + type WallFinishHit, + type WallFinishLayout, + type WallFinishSpan, + type WallPaintRole, + type WallZoneSpan, + wallFinishMaterialIndex, + wallRegionRole, + wallRoomFaceRole, + wallRoomFinishRole, + zoneHasWallFinish, +} from './systems/wall/wall-finish' export { DEFAULT_WALL_HEIGHT, DEFAULT_WALL_THICKNESS, getWallPlanFootprint, getWallThickness, } from './systems/wall/wall-footprint' +export { + buildWallJustificationPatch, + faceOnLine, + getWallBodyCenterOffset, + getWallBodyLine, + getWallFaceAtLocalPoint, + getWallFaceLine, + getWallFaceOffsets, + getWallLocalFaceZ, + justificationForFaceOnLine, + planWallJustification, + reverseWallDirection, + type WallFaceOffsets, + type WallJustification, +} from './systems/wall/wall-frame' export { getWallLayerBands, type WallLayerBand, @@ -560,6 +748,8 @@ export { planWallRectangle, wallRectangleCorners, } from './systems/wall/wall-operations' +export { roomSideFaces } from './systems/wall/wall-room-sides' +export { wallDoorStepRuns } from './systems/wall/wall-step-openings' export { MIN_WALL_HEIGHT, resolveWallEffectiveHeight, diff --git a/packages/core/src/lib/__bench__/structure-preview.bench.ts b/packages/core/src/lib/__bench__/structure-preview.bench.ts new file mode 100644 index 0000000000..b8125ac0d1 --- /dev/null +++ b/packages/core/src/lib/__bench__/structure-preview.bench.ts @@ -0,0 +1,79 @@ +import { type AnyNode, LevelNode, WallNode, ZoneNode } from '../../schema' +import { createLevelStructurePreview, reconcileLevelStructure } from '../structure-kernel' + +const levelId = 'level_bench' +const walls = Array.from({ length: 10 }, (_, i) => { + const x = i * 12 + const ring: [number, number][] = [ + [x, 0], + [x + 8, 0], + [x + 8, 4], + [x, 4], + ] + return ring.map((start, j) => + WallNode.parse({ + id: `wall_${i}_${j}`, + parentId: levelId, + start, + end: ring[(j + 1) % 4], + thickness: 0.2, + }), + ) +}).flat() +const level = LevelNode.parse({ id: levelId, children: walls.map((wall) => wall.id) }) +const nodes: Record = Object.fromEntries( + [level, ...walls].map((node) => [node.id, node]), +) +for (let i = 0; i < 3000; i++) { + const node = ZoneNode.parse({ + id: `zone_unrelated_${i}`, + name: 'Unrelated', + parentId: 'level_other', + polygon: [ + [0, 0], + [1, 0], + [1, 1], + ], + }) + nodes[node.id] = node +} +let id = 0 +for (const patch of reconcileLevelStructure({ + levelId, + nodes, + mintId: (kind) => `${kind}_bench_${id++}`, +}).patches) { + if (patch.op === 'create') nodes[patch.node.id] = patch.node + else if (patch.op === 'update') nodes[patch.id] = { ...nodes[patch.id], ...patch.data } as AnyNode + else delete nodes[patch.id] +} +const preview = createLevelStructurePreview(levelId, nodes) +const frames = [0.1, 0.2].map((offset) => + walls.map( + (wall): WallNode => + wall.id.startsWith('wall_0_') + ? { + ...wall, + start: [wall.start[0] + (wall.start[0] === 8 ? offset : 0), wall.start[1]], + end: [wall.end[0] + (wall.end[0] === 8 ? offset : 0), wall.end[1]], + } + : wall, + ), +) +for (let i = 0; i < 100; i++) preview(frames[i % 2]!) +const rounds: number[] = [] +for (let round = 0; round < 5; round++) { + const start = performance.now() + for (let i = 0; i < 500; i++) preview(frames[i % 2]!) + rounds.push((performance.now() - start) / 500) +} +console.log( + JSON.stringify({ + walls: 40, + unrelatedNodes: 3000, + warmup: 100, + ticksPerRound: 500, + rounds, + medianMs: [...rounds].sort((a, b) => a - b)[2], + }), +) diff --git a/packages/core/src/lib/__fixtures__/joint-merge-rooms.json b/packages/core/src/lib/__fixtures__/joint-merge-rooms.json new file mode 100644 index 0000000000..c2f1f6e221 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/joint-merge-rooms.json @@ -0,0 +1,377 @@ +[ + { + "id": "wall_07la4t3pbhbfsfql", + "start": [5, 3], + "end": [6.8, 3] + }, + { + "id": "wall_0dyaxeipc8xmv1sm", + "start": [-1, 11], + "end": [7, 11] + }, + { + "id": "wall_0umfemdhrmf2cs6v", + "start": [0.7, 6.9], + "end": [1.2, 3.6] + }, + { + "id": "wall_0yirasq40g8i9k8x", + "start": [-3.7, 16.5], + "end": [-6.2, 16.5] + }, + { + "id": "wall_1jcxm2mecwaoumoj", + "start": [9.5, 9.6], + "end": [9.5, 12] + }, + { + "id": "wall_25pzwf1rtwvout0v", + "start": [10.9, 0], + "end": [10.9, 4.4] + }, + { + "id": "wall_32djrllxvicc0y0q", + "start": [8.8, 4.4], + "end": [8.8, 2.9] + }, + { + "id": "wall_3jja9d86f8ricgo3", + "start": [6.8, 2.9], + "end": [8.8, 2.9] + }, + { + "id": "wall_3oe4hrw8ecyng9wh", + "start": [8.8, 2.9], + "end": [8.8, 4.4] + }, + { + "id": "wall_5c6mevss5sd46qkw", + "start": [10.9, 4.4], + "end": [10.9, 3.749999999999999] + }, + { + "id": "wall_5njwa1ht3awf0om3", + "start": [-4.5, 7], + "end": [-4.5, 12] + }, + { + "id": "wall_5nkec3xkhqm6fcwx", + "start": [-4.3, 12], + "end": [-4, 14.5] + }, + { + "id": "wall_5p23k40unbh70yhj", + "start": [-1, 16.5], + "end": [-1, 11] + }, + { + "id": "wall_5pvd5ld5pdauzeox", + "start": [16, 14], + "end": [10.9, 14] + }, + { + "id": "wall_5vd5jwup58xqry4t", + "start": [8, 8.4], + "end": [8, 4.4] + }, + { + "id": "wall_5ym4mwuht60r8n9p", + "start": [4.920792079207921, 4.392079207920792], + "end": [4.6, 7.6] + }, + { + "id": "wall_61pm2709inak0nha", + "start": [-6.5, 14.5], + "end": [-4, 14.5] + }, + { + "id": "wall_621cquklmw9hrobi", + "start": [8, 9.6], + "end": [8, 8.4] + }, + { + "id": "wall_68oz3lv6455h6n0c", + "start": [10.9, 14], + "end": [10.9, 9.5] + }, + { + "id": "wall_6j7a57g3d3a6me3l", + "start": [1.5, 3.6], + "end": [1.5, 0.4] + }, + { + "id": "wall_6o2d5uvkwnx67sfe", + "start": [10.9, 0], + "end": [15, 0] + }, + { + "id": "wall_6up9lddjogt0tk0c", + "start": [10.9, 8.4], + "end": [10.9, 8] + }, + { + "id": "wall_7l11vjjyiqadwo2y", + "start": [8.8, 3], + "end": [8.8, 2.250000000000001] + }, + { + "id": "wall_7qz78yw2g7er81a9", + "start": [-7, 12], + "end": [-6.8, 12] + }, + { + "id": "wall_7wxewc757czoeut3", + "start": [8.8, 2.3], + "end": [10.9, 2.3] + }, + { + "id": "wall_8871fa0j6ahiohoo", + "start": [5.000000000000001, 0], + "end": [10.9, 0] + }, + { + "id": "wall_8bh8nl0mwcj7wt0d", + "start": [-7, 12], + "end": [-7, 7] + }, + { + "id": "wall_8rhhekluspy5ltfz", + "start": [4.6, 7.6], + "end": [0.7, 6.9] + }, + { + "id": "wall_8y7ud0tpykbkdsrt", + "start": [-6.8, 12], + "end": [-4.5, 12] + }, + { + "id": "wall_a732e3f4xtoq8sx2", + "start": [8, 4.4], + "end": [5, 4.4] + }, + { + "id": "wall_ad4uiawg412yc3gt", + "start": [5, 12], + "end": [5, 3] + }, + { + "id": "wall_avhh91q42ksgzia5", + "start": [8.8, 2.250000000000001], + "end": [8.8, 3] + }, + { + "id": "wall_bv80f6r4k8191mwk", + "start": [9.3, 4.4], + "end": [9.3, 3] + }, + { + "id": "wall_crqunqdiewya4j94", + "start": [9.3, 4.4], + "end": [8.8, 4.4] + }, + { + "id": "wall_cxz0zsvaywj2kf8z", + "start": [5, 3.6], + "end": [4.920792079207921, 4.392079207920792] + }, + { + "id": "wall_d7mbxe4hd38wjtwe", + "start": [1.2, 3.6], + "end": [1.5, 3.6] + }, + { + "id": "wall_d9ffuznuk0kb8lom", + "start": [-7, 7], + "end": [-4.5, 7] + }, + { + "id": "wall_deacapmc21fgrdpn", + "start": [-4, 14.5], + "end": [-3.7, 16.5] + }, + { + "id": "wall_dvw6wtb4fs13llix", + "start": [9.3, 3], + "end": [8.8, 3] + }, + { + "id": "wall_dx9h78n5jv1bfq9b", + "start": [10.9, 8.4], + "end": [8, 8.4] + }, + { + "id": "wall_eg9t38fl5pu59wne", + "start": [-7, 9.5], + "end": [-4.5, 9.5] + }, + { + "id": "wall_ej99r5w5muovevls", + "start": [9.5, 12], + "end": [5, 12] + }, + { + "id": "wall_em88vmzjz97zpu7t", + "start": [-6.5, 14.5], + "end": [-6.8, 12] + }, + { + "id": "wall_g2ztqlmzbgfbyz07", + "start": [10.9, 9.5], + "end": [16, 9.5] + }, + { + "id": "wall_gbs20r2xpirwtngw", + "start": [10.9, 3.75], + "end": [10.9, 2.25] + }, + { + "id": "wall_h2iwndxe7xi48frz", + "start": [6.8, 3], + "end": [6.8, 0] + }, + { + "id": "wall_ieqoltdwt9f1nk2y", + "start": [8, 4.4], + "end": [8.8, 4.4] + }, + { + "id": "wall_jhk612y9gab356tx", + "start": [7, 11], + "end": [7, 16.5] + }, + { + "id": "wall_k4zsssy55jxc9753", + "start": [1.5, 3.6], + "end": [5, 3.6] + }, + { + "id": "wall_kbtg82fgezpjtssh", + "start": [5, 3], + "end": [5, 0] + }, + { + "id": "wall_lwmvixqkapidcogu", + "start": [5, 2.9], + "end": [6.8, 2.9] + }, + { + "id": "wall_mlluouv5wn122y4d", + "start": [5, 3.6], + "end": [5, 3] + }, + { + "id": "wall_mq88lzro5nqrsm5d", + "start": [16, 9.5], + "end": [16, 14] + }, + { + "id": "wall_nbkm14h2xpnqi003", + "start": [8.8, 2.250000000000001], + "end": [8.8, 0] + }, + { + "id": "wall_notwtwhs970d5kv6", + "start": [7, 16.5], + "end": [-1, 16.5] + }, + { + "id": "wall_ojf2cslintcepyt4", + "start": [10.9, 4.4], + "end": [9.3, 4.4] + }, + { + "id": "wall_py3c04mu556xh9cn", + "start": [10.9, 4.4], + "end": [10.9, 3.75] + }, + { + "id": "wall_qaxi90jmzkid0ndb", + "start": [6.8, 3], + "end": [8.8, 3] + }, + { + "id": "wall_qvie3p23xuc7jwpe", + "start": [15, 3.75], + "end": [10.9, 3.75] + }, + { + "id": "wall_r1sn05ns8uf062j4", + "start": [8, 4.4], + "end": [8.8, 4.4] + }, + { + "id": "wall_r68ckog6hxznny7k", + "start": [5, 9.6], + "end": [8, 9.6] + }, + { + "id": "wall_rcnzglng6hwh01hn", + "start": [8.8, 2.9], + "end": [8.8, 2.2500000000000004] + }, + { + "id": "wall_rsdzx81mndqy7a7r", + "start": [15, 3.75], + "end": [15, 8] + }, + { + "id": "wall_rybv4hds2zri68y2", + "start": [8, 9.6], + "end": [9.5, 9.6] + }, + { + "id": "wall_sbq15tlokzalfcsc", + "start": [10.9, 2.25], + "end": [10.9, 0] + }, + { + "id": "wall_ufx2vtzmc324iq1j", + "start": [15, 4.4], + "end": [10.9, 4.4] + }, + { + "id": "wall_ugvu58o8fmgsbie8", + "start": [10.9, 8], + "end": [10.9, 4.4] + }, + { + "id": "wall_viv4na07lssdxamu", + "start": [9.3, 4.4], + "end": [8, 4.4] + }, + { + "id": "wall_voiho43jqwfdelez", + "start": [-4.5, 12], + "end": [-4.3, 12] + }, + { + "id": "wall_w47wlzgm1fbdar2u", + "start": [15, 8], + "end": [10.9, 8] + }, + { + "id": "wall_x3hx8bri24jdv8r8", + "start": [1.5, 0.4], + "end": [5, 0] + }, + { + "id": "wall_xwftarvysqfoojq2", + "start": [-6.2, 16.5], + "end": [-6.5, 14.5] + }, + { + "id": "wall_y07gyimkl7xgybng", + "start": [6.8, 3], + "end": [6.8, 3] + }, + { + "id": "wall_ypq333l8mvsy1svg", + "start": [15, 0], + "end": [15, 3.75] + }, + { + "id": "wall_yyljh535a2wao2tn", + "start": [6.8, 3], + "end": [6.8, 3.05] + } +] diff --git a/packages/core/src/lib/__fixtures__/mezzanine.ts b/packages/core/src/lib/__fixtures__/mezzanine.ts new file mode 100644 index 0000000000..d91aefe278 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/mezzanine.ts @@ -0,0 +1,52 @@ +import { createMezzanine } from '../../commands/structure/create-mezzanine' +import { + applyToScratch, + type StructurePlan, + structureChangeBatch, +} from '../../commands/structure/shared' +import { type AnyNode, LevelNode, WallNode, type ZoneNode } from '../../schema' +import { reconcileSceneStructure } from '../structure-reconcile' + +export const mezzaninePolygon: [number, number][] = [ + [0.1, 0.1], + [4, 0.1], + [4, 3], + [0.1, 3], +] + +export function mezzanineFixture(height = 5) { + let serial = 0 + const mintId = (kind: string) => `${kind}_mezz${++serial}` + const ring: [number, number][] = [ + [0, 0], + [8, 0], + [8, 6], + [0, 6], + ] + const walls = ring.map((start, i) => + WallNode.parse({ + id: mintId('wall'), + parentId: 'level_mezz', + start, + end: ring[(i + 1) % 4], + thickness: 0.2, + }), + ) + const level = LevelNode.parse({ + id: 'level_mezz', + height, + children: walls.map((wall) => wall.id), + }) + const reconcile = (nodes: Readonly>) => + reconcileSceneStructure({ nodes, mintId }) + const before = reconcile(Object.fromEntries([level, ...walls].map((n) => [n.id, n]))).nodes + const host = Object.values(before).find((node): node is ZoneNode => node.type === 'zone')! + const apply = (nodes: Readonly>, plan: StructurePlan) => + reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))).nodes + const plan = createMezzanine(before, { hostZoneId: host.id, polygon: mezzaninePolygon, mintId }) + const nodes = apply(before, plan) + const zone = nodes[plan.zoneId] as ZoneNode + const plate = Object.values(nodes).find((n) => n.type === 'slab' && n.zoneIds?.includes(zone.id))! + if (plate.type !== 'slab') throw Error('Missing mezzanine plate') + return { before, nodes, host, zone, plate, level, walls, apply, reconcile, mintId } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/README.md b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/README.md new file mode 100644 index 0000000000..f6b78f50d0 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/README.md @@ -0,0 +1,19 @@ +Trimmed, anonymised production scenes from the frozen `f03f3ce4` M4/M5 evidence. +Node IDs, coordinates, construction, saved holes and transport intent are +retained; names, asset URLs and project IDs are neutral. Furniture and unrelated +level geometry are omitted; ancestor levels and stair source/destination +construction remain so opening queries use the real stack. `areas` and `gaps` +retain the frozen report's measurements and sample stations. + +- `scene-21`: one of the largest reported area losses and a reported gap scene. + M4 preserves its visible area within 1%; ensuring missing stair holes + accounts for the later loss, and its reported gap samples lie in newly + ensured stair openings (9 walls), including boundary cuts. +- `scene-10`, `scene-19`: legacy elevators parented to levels. The service + query must find the owning building before client reparenting, including a + level whose building is recorded only through `building.children`. Client + hydration, shared normalization and mounted opening systems must agree. + +Visible area in `scene-21` (m²): 25.675 before M4, 25.675 after M4 and 22.108 +after opening repair. Saved holes are never redrawn to make the area/gap +measurements pass. diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-10.json b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-10.json new file mode 100644 index 0000000000..6756504961 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-10.json @@ -0,0 +1,1751 @@ +{ + "sceneId": "scene-10", + "rootNodeIds": [ + "site_h6vard6xtg4zo3u0", + "level_h8x92a52k04kkmcl", + "building_9lu5dxyei66vzyk8" + ], + "nodes": { + "door_4cex42oh520ieg4j": { + "id": "door_4cex42oh520ieg4j", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 1.54, + "object": "node", + "wallId": "wall_ljs1lkrucrae1ehu", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_ljs1lkrucrae1ehu", + "position": [0.65, 0.77, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_6vo2kk9qjz120411": { + "id": "door_6vo2kk9qjz120411", + "name": "Door 3", + "side": "front", + "type": "door", + "width": 0.8, + "handle": true, + "height": 1.99, + "object": "node", + "wallId": "wall_yf3ydk7h4wdxfiug", + "visible": true, + "doorType": "hinged", + "metadata": { + "isNew": true + }, + "panicBar": false, + "parentId": "wall_yf3ydk7h4wdxfiug", + "position": [5.5, 0.995, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "outward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_jc83bgu03wdgnday": { + "id": "door_jc83bgu03wdgnday", + "name": "Door 7", + "side": "back", + "type": "door", + "width": 0.8, + "handle": true, + "height": 2, + "object": "node", + "wallId": "wall_4i1hxi8zpeipa23h", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_4i1hxi8zpeipa23h", + "position": [0.47, 1, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_myk189tnihfh2t08": { + "id": "door_myk189tnihfh2t08", + "name": "Door 3", + "side": "front", + "type": "door", + "width": 0.8, + "handle": true, + "height": 2, + "object": "node", + "wallId": "wall_yf3ydk7h4wdxfiug", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_yf3ydk7h4wdxfiug", + "position": [1.95, 1, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "right", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "outward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_ns7ya5ozeflnr7bo": { + "id": "door_ns7ya5ozeflnr7bo", + "name": "Door 7", + "side": "back", + "type": "door", + "width": 0.6, + "handle": true, + "height": 1.95, + "object": "node", + "wallId": "wall_nbzpfpxuqpi810hv", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_nbzpfpxuqpi810hv", + "position": [0.46, 0.975, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.06, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_qq3ve6mcxfn9brmd": { + "id": "door_qq3ve6mcxfn9brmd", + "name": "Door 3", + "side": "front", + "type": "door", + "width": 1.02, + "handle": true, + "height": 2.01, + "object": "node", + "wallId": "wall_lhhm85stz20g08lk", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_lhhm85stz20g08lk", + "position": [6.22, 1.005, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "glass", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [ + 0.3333333333333333, 0.3333333333333333, 0.3333333333333333 + ], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.035, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_qyt8cuw79rfbnrv3": { + "id": "door_qyt8cuw79rfbnrv3", + "name": "Door 3", + "side": "front", + "type": "door", + "width": 0.8, + "handle": true, + "height": 2, + "object": "node", + "wallId": "wall_yf3ydk7h4wdxfiug", + "visible": true, + "doorType": "hinged", + "metadata": { + "isNew": true + }, + "panicBar": false, + "parentId": "wall_yf3ydk7h4wdxfiug", + "position": [4.48, 1, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "right", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "outward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_s0bnpcxubepexar6": { + "id": "door_s0bnpcxubepexar6", + "name": "Door 2", + "side": "front", + "type": "door", + "width": 2.2, + "handle": false, + "height": 2.05, + "object": "node", + "wallId": "wall_lhhm85stz20g08lk", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_lhhm85stz20g08lk", + "position": [1.7, 1.025, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.25, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.25, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.2500000000000001, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.25, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.01, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_twxqhdmjg5rsxad6": { + "id": "door_twxqhdmjg5rsxad6", + "name": "Door 2", + "side": "front", + "type": "door", + "width": 1.49, + "handle": true, + "height": 2.05, + "object": "node", + "wallId": "wall_lhhm85stz20g08lk", + "visible": true, + "doorType": "hinged", + "metadata": { + "isNew": true + }, + "panicBar": false, + "parentId": "wall_lhhm85stz20g08lk", + "position": [4.3, 1.025, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "glass", + "panelDepth": 0.03, + "panelInset": 0.02, + "heightRatio": 0.18000000000000002, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0, + "panelInset": 0.08, + "heightRatio": 0.39, + "columnRatios": [0.52, 0.48], + "dividerThickness": 0.05 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.19830188679245278, + "columnRatios": [0.5, 0.5], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.025, + "panelInset": 0.04, + "heightRatio": 0.2316981132075472, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.05, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.06, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "door_xg9075m1yeeu63sw": { + "id": "door_xg9075m1yeeu63sw", + "name": "Door 2", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_d026m7v4076l1cgy", + "visible": true, + "doorType": "hinged", + "metadata": { + "isNew": true + }, + "panicBar": false, + "parentId": "wall_d026m7v4076l1cgy", + "position": [0.88, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "right", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "garagePanelCount": 4, + "openingRadiusMode": "all", + "openingRevealRadius": 0.025 + }, + "site_h6vard6xtg4zo3u0": { + "id": "site_h6vard6xtg4zo3u0", + "type": "site", + "camera": { + "mode": "orthographic", + "target": [ + -10.515729765694447, -5.28280862547024e-16, -13.17898945322312 + ], + "position": [ + -22.151992381253844, 10.575033870417357, -5.914965018981419 + ] + }, + "object": "node", + "polygon": { + "type": "polygon", + "points": [[-14.5, -17.5], [-5, -17.5], [-5, -2.5], [-14.5, -2.5]] + }, + "visible": true, + "children": ["building_9lu5dxyei66vzyk8"], + "metadata": {}, + "parentId": null + }, + "slab_3qvdkxyrc0ue844p": { + "id": "slab_3qvdkxyrc0ue844p", + "name": "Slab 3", + "type": "slab", + "holes": [ + [[-17.09, -11.09], [-14.91, -11.09], [-14.91, -8.91], [-17.09, -8.91]], + [[-15.59, -11.09], [-13.41, -11.09], [-13.41, -8.91], [-15.59, -8.91]] + ], + "object": "node", + "polygon": [ + [-14.5, -9.5], + [-14.5, -9.5], + [-15, -9.5], + [-15, -9.5], + [-15, -9.5], + [-15, -12], + [-14.5, -12], + [-14.5, -11.5] + ], + "visible": true, + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "elevation": 0.05, + "holeMetadata": [ + { + "source": "elevator", + "elevatorId": "elevator_lc8riouvdbmku7cu" + }, + { + "source": "elevator", + "elevatorId": "elevator_nausl9toywu6dsmz" + } + ], + "autoFromWalls": false + }, + "slab_5vtppeywfgqu3cap": { + "id": "slab_5vtppeywfgqu3cap", + "name": "Room 2 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-10, -15], [-10, -17.5], [-8, -17.5], [-8, -15]], + "visible": true, + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_7khqwimv3wga257e": { + "id": "slab_7khqwimv3wga257e", + "name": "Room 1 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-5, -17.5], + [-5, -15], + [-5.5, -15], + [-5, -15], + [-5, -11.5], + [-9.5, -11.5], + [-9.5, -9.5], + [-11, -9.5], + [-11, -17.5], + [-11, -9.5], + [-15, -9.5], + [-15, -12], + [-11, -12], + [-14.5, -12], + [-14.5, -17.5], + [-10, -17.5], + [-10, -15], + [-7.5, -15], + [-8, -15], + [-8, -17.5] + ], + "visible": true, + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_pevoa0ihrbaizb32": { + "id": "slab_pevoa0ihrbaizb32", + "name": "Slab 3", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-14.5, -2.5], [-14.5, -17.5], [-5, -17.5], [-5, -2.5]], + "visible": true, + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "elevation": 0.05 + }, + "slab_yrjfxy5tkbw0h54f": { + "id": "slab_yrjfxy5tkbw0h54f", + "name": "Room 1 Slab", + "type": "slab", + "holes": [ + [[-10.25, -10.5], [-9.25, -10.5], [-9.25, -9.5], [-10.25, -9.5]] + ], + "object": "node", + "polygon": [[-5, -2.5], [-14.5, -2.5], [-14.5, -17.5], [-5, -17.5]], + "visible": true, + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "elevation": 0.05, + "holeMetadata": [ + { + "source": "manual" + } + ], + "autoFromWalls": true + }, + "wall_1k4l0c5wnoywjhtl": { + "id": "wall_1k4l0c5wnoywjhtl", + "end": [-5, -11.5], + "name": "Wall 29", + "type": "wall", + "start": [-5, -2.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_2dvvfmp8ax6s2a7v": { + "id": "wall_2dvvfmp8ax6s2a7v", + "end": [-14.5, -12], + "name": "Wall 15", + "type": "wall", + "start": [-15, -12], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_4hzsgalqbbrflv1x": { + "id": "wall_4hzsgalqbbrflv1x", + "end": [-14.5, -2.5], + "name": "Wall 2", + "type": "wall", + "start": [-5, -2.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "interior" + }, + "wall_4i1hxi8zpeipa23h": { + "id": "wall_4i1hxi8zpeipa23h", + "end": [-10, -17.5], + "name": "Wall 37", + "type": "wall", + "start": [-10, -15], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_jc83bgu03wdgnday"], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_4xrmiid6djh9ht67": { + "id": "wall_4xrmiid6djh9ht67", + "end": [-5, -2.5], + "name": "Wall 25", + "type": "wall", + "start": [-14.5, -2.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_6xud5tu4v47q9fbn": { + "id": "wall_6xud5tu4v47q9fbn", + "end": [-5, -17.5], + "name": "Wall 26", + "type": "wall", + "start": [-5, -15], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["window_u47d958kpt9df1fr"], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_73qrrf7y5kbiic29": { + "id": "wall_73qrrf7y5kbiic29", + "end": [-15, -12], + "name": "Wall 12", + "type": "wall", + "start": [-15, -9.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_su7lapeiavhgao7n"], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_7wu1puyfyiof4j74": { + "id": "wall_7wu1puyfyiof4j74", + "end": [-14.5, -12], + "name": "Wall 19", + "type": "wall", + "start": [-14.5, -17.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["window_zpblgc1ali214trb", "window_8boy8pphv5954dvw"], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_85qpjeyx15wl000e": { + "id": "wall_85qpjeyx15wl000e", + "end": [-8, -9.5], + "name": "Wall 36", + "type": "wall", + "start": [-8, -10.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "unknown" + }, + "wall_8kns6y3qjgyx37lx": { + "id": "wall_8kns6y3qjgyx37lx", + "end": [-14.5, -14.5], + "name": "Wall 25", + "type": "wall", + "start": [-11, -14.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_9kmz1j4aw90ajydr": { + "id": "wall_9kmz1j4aw90ajydr", + "end": [-9.5, -9.5], + "name": "Wall 21", + "type": "wall", + "start": [-11, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_9zxdrlltiuq3vbz7": { + "id": "wall_9zxdrlltiuq3vbz7", + "end": [-5, -17.5], + "name": "Wall 27", + "type": "wall", + "start": [-8, -17.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_a11l5eq280rv89j8": { + "id": "wall_a11l5eq280rv89j8", + "end": [-14.5, -2.5], + "name": "Wall 25", + "type": "wall", + "start": [-14.5, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["window_r1su33g9uo8kr3pe", "window_eigy6vlkpu4kc8gy"], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_behx0njxq5a8fpiy": { + "id": "wall_behx0njxq5a8fpiy", + "end": [-14.5, -10.5], + "name": "Wall 35", + "type": "wall", + "start": [-8, -10.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "interior" + }, + "wall_d026m7v4076l1cgy": { + "id": "wall_d026m7v4076l1cgy", + "end": [-9.5, -9.5], + "name": "Wall 38", + "type": "wall", + "start": [-9.5, -11.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_xg9075m1yeeu63sw"], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_es4gydlae1ub9d2y": { + "id": "wall_es4gydlae1ub9d2y", + "end": [-8, -17.5], + "name": "Wall 30", + "type": "wall", + "start": [-10, -17.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_gagfj9rjvl7htzik": { + "id": "wall_gagfj9rjvl7htzik", + "end": [-5, -15], + "name": "Wall 25", + "type": "wall", + "start": [-5, -11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_gik0nngsycq6ryht": { + "id": "wall_gik0nngsycq6ryht", + "end": [-5, -9.5], + "name": "Wall 23", + "type": "wall", + "start": [-9.5, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_hwqon10hvxnim7aa": { + "id": "wall_hwqon10hvxnim7aa", + "end": [-14.5, -17.5], + "name": "Wall 4", + "type": "wall", + "start": [-5, -17.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "exterior" + }, + "wall_l40mvb7sgbn7f63s": { + "id": "wall_l40mvb7sgbn7f63s", + "end": [-5, -12], + "name": "Wall 35", + "type": "wall", + "start": [-14.5, -12], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "interior" + }, + "wall_l5fymr1oj0myklao": { + "id": "wall_l5fymr1oj0myklao", + "end": [-5.5, -15], + "name": "Wall 38", + "type": "wall", + "start": [-5, -15], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "unknown" + }, + "wall_lhhm85stz20g08lk": { + "id": "wall_lhhm85stz20g08lk", + "end": [-14.5, -2.5], + "name": "Wall 1", + "type": "wall", + "start": [-14.5, -17.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [ + "window_5wuloqgnhk1tyd5r", + "door_s0bnpcxubepexar6", + "window_d6x9afmhcuwuitdo", + "door_twxqhdmjg5rsxad6", + "door_qq3ve6mcxfn9brmd" + ], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "exterior" + }, + "wall_ljs1lkrucrae1ehu": { + "id": "wall_ljs1lkrucrae1ehu", + "end": [-5, -9.5], + "name": "Wall 32", + "type": "wall", + "start": [-8, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_4cex42oh520ieg4j"], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "interior" + }, + "wall_nbzpfpxuqpi810hv": { + "id": "wall_nbzpfpxuqpi810hv", + "end": [-11, -16], + "name": "Wall 36", + "type": "wall", + "start": [-10, -16], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_ns7ya5ozeflnr7bo"], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "unknown" + }, + "wall_oxn28vtmm6usw5wh": { + "id": "wall_oxn28vtmm6usw5wh", + "end": [-10, -17.5], + "name": "Wall 24", + "type": "wall", + "start": [-14.5, -17.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_pqt3zuqb06rdkwz9": { + "id": "wall_pqt3zuqb06rdkwz9", + "end": [-9.5, -15], + "name": "Wall 29", + "type": "wall", + "start": [-8, -15], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_qnn2pieoi14576qm": { + "id": "wall_qnn2pieoi14576qm", + "end": [-7.5, -15], + "name": "Wall 39", + "type": "wall", + "start": [-8, -15], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_qzzi64mskrxc82wk": { + "id": "wall_qzzi64mskrxc82wk", + "end": [-5, -17.5], + "name": "Wall 29", + "type": "wall", + "start": [-5, -2.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "frontSide": "exterior" + }, + "wall_stpx3s6yp4o04jol": { + "id": "wall_stpx3s6yp4o04jol", + "end": [-5, -11.5], + "name": "Wall 24", + "type": "wall", + "start": [-9.5, -11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "wall_ua82xlgs0uedp776": { + "id": "wall_ua82xlgs0uedp776", + "end": [-11, -12], + "name": "Wall 37", + "type": "wall", + "start": [-14.5, -12], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_woof6rdiva1beuu8": { + "id": "wall_woof6rdiva1beuu8", + "end": [-8, -15], + "name": "Wall 28", + "type": "wall", + "start": [-8, -17.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_y3or8ft4ssj616co": { + "id": "wall_y3or8ft4ssj616co", + "end": [-10, -15], + "name": "Wall 35", + "type": "wall", + "start": [-9.5, -15], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "unknown" + }, + "wall_yf3ydk7h4wdxfiug": { + "id": "wall_yf3ydk7h4wdxfiug", + "end": [-11, -17.5], + "name": "Wall 19", + "type": "wall", + "start": [-11, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [ + "door_myk189tnihfh2t08", + "door_qyt8cuw79rfbnrv3", + "door_6vo2kk9qjz120411" + ], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "interior" + }, + "wall_zxnf7enxxjynwyxq": { + "id": "wall_zxnf7enxxjynwyxq", + "end": [-11, -9.5], + "name": "Wall 20", + "type": "wall", + "start": [-15, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "frontSide": "exterior" + }, + "zone_4frexevfaeiq49mm": { + "id": "zone_4frexevfaeiq49mm", + "name": "Room A", + "type": "zone", + "color": "#ef4444", + "object": "node", + "polygon": [[-14.5, -9], [-5, -9], [-5, -2.5], [-14.5, -2.5]], + "visible": true, + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0" + }, + "level_28jvuqfcdv7xttd0": { + "id": "level_28jvuqfcdv7xttd0", + "name": "Level A", + "type": "level", + "level": 1, + "object": "node", + "visible": true, + "children": [ + "slab_3qvdkxyrc0ue844p", + "wall_73qrrf7y5kbiic29", + "wall_7wu1puyfyiof4j74", + "wall_2dvvfmp8ax6s2a7v", + "wall_yf3ydk7h4wdxfiug", + "wall_zxnf7enxxjynwyxq", + "wall_9kmz1j4aw90ajydr", + "wall_8kns6y3qjgyx37lx", + "wall_oxn28vtmm6usw5wh", + "wall_a11l5eq280rv89j8", + "wall_4xrmiid6djh9ht67", + "wall_gik0nngsycq6ryht", + "wall_stpx3s6yp4o04jol", + "wall_gagfj9rjvl7htzik", + "wall_6xud5tu4v47q9fbn", + "wall_9zxdrlltiuq3vbz7", + "wall_woof6rdiva1beuu8", + "wall_pqt3zuqb06rdkwz9", + "wall_1k4l0c5wnoywjhtl", + "wall_es4gydlae1ub9d2y", + "wall_y3or8ft4ssj616co", + "wall_nbzpfpxuqpi810hv", + "wall_4i1hxi8zpeipa23h", + "wall_l5fymr1oj0myklao", + "wall_qnn2pieoi14576qm", + "ceiling_mqb2seac6c14nvws", + "zone_4frexevfaeiq49mm", + "wall_d026m7v4076l1cgy", + "slab_pevoa0ihrbaizb32", + "wall_ua82xlgs0uedp776", + "slab_7khqwimv3wga257e", + "slab_5vtppeywfgqu3cap", + "ceiling_bj9u8xk8iysslmss", + "ceiling_9qkyxa6lce2gkfgc" + ], + "metadata": {}, + "parentId": "building_9lu5dxyei66vzyk8" + }, + "level_h8x92a52k04kkmcl": { + "id": "level_h8x92a52k04kkmcl", + "name": "Level B", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_lhhm85stz20g08lk", + "wall_4hzsgalqbbrflv1x", + "wall_hwqon10hvxnim7aa", + "wall_qzzi64mskrxc82wk", + "wall_ljs1lkrucrae1ehu", + "wall_l40mvb7sgbn7f63s", + "wall_behx0njxq5a8fpiy", + "wall_85qpjeyx15wl000e", + "slab_yrjfxy5tkbw0h54f", + "ceiling_b8axlap7bfteejwd", + "elevator_ezywn92p4c0kbwzm" + ], + "metadata": {}, + "parentId": null + }, + "window_5wuloqgnhk1tyd5r": { + "id": "window_5wuloqgnhk1tyd5r", + "name": "Window 2", + "side": "front", + "sill": true, + "type": "window", + "width": 1.4, + "height": 1.1, + "object": "node", + "wallId": "wall_lhhm85stz20g08lk", + "visible": true, + "metadata": {}, + "parentId": "wall_lhhm85stz20g08lk", + "position": [10, 1.5, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_8boy8pphv5954dvw": { + "id": "window_8boy8pphv5954dvw", + "side": "front", + "sill": true, + "type": "window", + "width": 1.4, + "height": 1.1, + "object": "node", + "wallId": "wall_7wu1puyfyiof4j74", + "visible": true, + "metadata": {}, + "parentId": "wall_7wu1puyfyiof4j74", + "position": [2, 1.5, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_d6x9afmhcuwuitdo": { + "id": "window_d6x9afmhcuwuitdo", + "side": "front", + "sill": true, + "type": "window", + "width": 1.4, + "height": 1.1, + "object": "node", + "wallId": "wall_lhhm85stz20g08lk", + "visible": true, + "metadata": {}, + "parentId": "wall_lhhm85stz20g08lk", + "position": [12, 1.5, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_eigy6vlkpu4kc8gy": { + "id": "window_eigy6vlkpu4kc8gy", + "side": "front", + "sill": true, + "type": "window", + "width": 1.4, + "height": 1.1, + "object": "node", + "wallId": "wall_a11l5eq280rv89j8", + "visible": true, + "metadata": {}, + "parentId": "wall_a11l5eq280rv89j8", + "position": [4, 1.5, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_r1su33g9uo8kr3pe": { + "id": "window_r1su33g9uo8kr3pe", + "side": "front", + "sill": true, + "type": "window", + "width": 1.4, + "height": 1.1, + "object": "node", + "wallId": "wall_a11l5eq280rv89j8", + "visible": true, + "metadata": {}, + "parentId": "wall_a11l5eq280rv89j8", + "position": [2, 1.5, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_su7lapeiavhgao7n": { + "id": "window_su7lapeiavhgao7n", + "name": "Window 1", + "side": "back", + "sill": true, + "type": "window", + "width": 2.1, + "height": 1.1, + "object": "node", + "wallId": "wall_73qrrf7y5kbiic29", + "visible": true, + "metadata": {}, + "parentId": "wall_73qrrf7y5kbiic29", + "position": [1.24, 1.5, 0], + "rotation": [0, 3.141592653589793, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_u47d958kpt9df1fr": { + "id": "window_u47d958kpt9df1fr", + "name": "Window 6", + "side": "front", + "sill": true, + "type": "window", + "width": 1.8, + "height": 1.1, + "object": "node", + "wallId": "wall_6xud5tu4v47q9fbn", + "visible": true, + "metadata": {}, + "parentId": "wall_6xud5tu4v47q9fbn", + "position": [1.3, 1.5, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_zpblgc1ali214trb": { + "id": "window_zpblgc1ali214trb", + "name": "Window 2", + "side": "front", + "sill": true, + "type": "window", + "width": 1.4, + "height": 1.1, + "object": "node", + "wallId": "wall_7wu1puyfyiof4j74", + "visible": true, + "metadata": {}, + "parentId": "wall_7wu1puyfyiof4j74", + "position": [4, 1.5, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "ceiling_9qkyxa6lce2gkfgc": { + "id": "ceiling_9qkyxa6lce2gkfgc", + "name": "Room 2 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.55, + "object": "node", + "polygon": [[-10, -15], [-10, -17.5], [-8, -17.5], [-8, -15]], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_b8axlap7bfteejwd": { + "id": "ceiling_b8axlap7bfteejwd", + "name": "Room 1 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.55, + "object": "node", + "polygon": [[-5, -2.5], [-14.5, -2.5], [-14.5, -17.5], [-5, -17.5]], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_bj9u8xk8iysslmss": { + "id": "ceiling_bj9u8xk8iysslmss", + "name": "Room 1 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.55, + "object": "node", + "polygon": [ + [-5, -17.5], + [-5, -15], + [-5.5, -15], + [-5, -15], + [-5, -11.5], + [-9.5, -11.5], + [-9.5, -9.5], + [-11, -9.5], + [-11, -17.5], + [-11, -9.5], + [-15, -9.5], + [-15, -12], + [-11, -12], + [-14.5, -12], + [-14.5, -17.5], + [-10, -17.5], + [-10, -15], + [-7.5, -15], + [-8, -15], + [-8, -17.5] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_mqb2seac6c14nvws": { + "id": "ceiling_mqb2seac6c14nvws", + "name": "Ceiling 1", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [-14.5, -17.5], + [-5, -17.5], + [-5, -11.5], + [-9.5, -11.5], + [-9.5, -9.5], + [-15, -9.5], + [-15, -12], + [-14.5, -12] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_28jvuqfcdv7xttd0" + }, + "building_9lu5dxyei66vzyk8": { + "id": "building_9lu5dxyei66vzyk8", + "type": "building", + "camera": { + "mode": "orthographic", + "target": [-10.515729765694447, 0, -13.17898945322312], + "position": [ + -22.151992381253844, 10.575033870417357, -5.914965018981419 + ] + }, + "object": "node", + "visible": true, + "children": [ + "level_h8x92a52k04kkmcl", + "level_28jvuqfcdv7xttd0", + "elevator_lc8riouvdbmku7cu", + "elevator_nausl9toywu6dsmz" + ], + "metadata": {}, + "parentId": null, + "position": [0, 0, 0], + "rotation": [0, 0, 0] + }, + "elevator_ezywn92p4c0kbwzm": { + "id": "elevator_ezywn92p4c0kbwzm", + "name": "Elevator 1", + "type": "elevator", + "depth": 2, + "speed": 2.2, + "width": 2, + "object": "node", + "dwellMs": 1400, + "visible": true, + "metadata": {}, + "parentId": "level_h8x92a52k04kkmcl", + "position": [-12.97654227567001, 0, -9.48154227567001], + "rotation": 0, + "cabHeight": 2.35, + "doorStyle": "center-opening", + "doorWidth": 0.95, + "toLevelId": "level_ur37y4bqjfs8c1xx", + "doorHeight": 2.1, + "shaftStyle": "solid", + "fromLevelId": "level_mqq2u8qtyor3ahss", + "defaultLevelId": "level_mqq2u8qtyor3ahss", + "doorDurationMs": 900, + "doorPanelStyle": "glass-frame", + "disabledLevelIds": [], + "shaftWallThickness": 0.09, + "serviceOnlyLevelIds": [] + }, + "elevator_lc8riouvdbmku7cu": { + "id": "elevator_lc8riouvdbmku7cu", + "name": "Elevator 2", + "type": "elevator", + "depth": 1.84, + "speed": 2.2, + "width": 1.84, + "object": "node", + "dwellMs": 1400, + "visible": true, + "metadata": {}, + "parentId": "building_9lu5dxyei66vzyk8", + "position": [-16, 0, -10], + "rotation": 0, + "cabHeight": 2.35, + "doorStyle": "center-opening", + "doorWidth": 0.95, + "toLevelId": "level_28jvuqfcdv7xttd0", + "doorHeight": 2.1, + "shaftStyle": "solid", + "fromLevelId": "level_h8x92a52k04kkmcl", + "defaultLevelId": "level_h8x92a52k04kkmcl", + "doorDurationMs": 900, + "doorPanelStyle": "glass-frame", + "disabledLevelIds": [], + "shaftWallThickness": 0.09, + "serviceOnlyLevelIds": [] + }, + "elevator_nausl9toywu6dsmz": { + "id": "elevator_nausl9toywu6dsmz", + "name": "Elevator 3", + "type": "elevator", + "depth": 1.84, + "speed": 2.2, + "width": 1.84, + "object": "node", + "dwellMs": 1400, + "visible": true, + "metadata": {}, + "parentId": "building_9lu5dxyei66vzyk8", + "position": [-14.5, 0.05, -10], + "rotation": 0, + "cabHeight": 2.35, + "doorStyle": "center-opening", + "doorWidth": 0.95, + "toLevelId": "level_28jvuqfcdv7xttd0", + "doorHeight": 2.1, + "shaftStyle": "solid", + "fromLevelId": "level_h8x92a52k04kkmcl", + "defaultLevelId": "level_h8x92a52k04kkmcl", + "doorDurationMs": 900, + "doorPanelStyle": "glass-frame", + "disabledLevelIds": [], + "shaftWallThickness": 0.09, + "serviceOnlyLevelIds": [] + } + }, + "areas": [], + "gaps": [] +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-19.json b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-19.json new file mode 100644 index 0000000000..6ddec325b6 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-19.json @@ -0,0 +1,2593 @@ +{ + "sceneId": "scene-19", + "rootNodeIds": [ + "site_mzooxtt7vdjmnfz5", + "level_o2mqfskh43eds0kh", + "building_opg1pcqcaexock0a" + ], + "nodes": { + "door_3tblpxorpkmly0i7": { + "id": "door_3tblpxorpkmly0i7", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 1.8, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_d438lv0gfnu9ulpl", + "visible": true, + "doorType": "folding", + "metadata": {}, + "panicBar": false, + "parentId": "wall_d438lv0gfnu9ulpl", + "position": [1, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.008, + "panelInset": 0.025, + "heightRatio": 1, + "columnRatios": [1], + "dividerThickness": 0.02 + } + ], + "leafCount": 4, + "threshold": false, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "visible", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.03, 0.04], + "frameThickness": 0.05, + "operationState": 0.65, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_8f6gd7jm2w8veibl": { + "id": "door_8f6gd7jm2w8veibl", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_mha03gkut8yj34gm", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_mha03gkut8yj34gm", + "position": [1.0015945510581363, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_armztuvxan66q5ct": { + "id": "door_armztuvxan66q5ct", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 1.5, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_ay4i32j42khlxjsd", + "visible": true, + "doorType": "french", + "metadata": {}, + "panicBar": false, + "parentId": "wall_ay4i32j42khlxjsd", + "position": [1.85, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "glass", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.76, + "columnRatios": [1, 1], + "dividerThickness": 0.025 + }, + { + "type": "panel", + "panelDepth": 0.012, + "panelInset": 0.035, + "heightRatio": 0.24, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 2, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.045, 0.055], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_gm5prhor6c3964fr": { + "id": "door_gm5prhor6c3964fr", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_xvdj23rc9pjtoul5", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_xvdj23rc9pjtoul5", + "position": [0.915, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_iumom5q4laa8inub": { + "id": "door_iumom5q4laa8inub", + "name": "Door 4", + "side": "front", + "type": "door", + "width": 1.3, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_0pb1oz4mexnwt5gz", + "visible": true, + "doorType": "folding", + "metadata": {}, + "panicBar": false, + "parentId": "wall_0pb1oz4mexnwt5gz", + "position": [0.8, 1.05, 0], + "rotation": [0, 6.283185307179586, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.008, + "panelInset": 0.025, + "heightRatio": 1, + "columnRatios": [1], + "dividerThickness": 0.02 + } + ], + "leafCount": 4, + "threshold": false, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "visible", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.03, 0.04], + "frameThickness": 0.05, + "operationState": 0.63, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_jfdzs4jegvwgfapg": { + "id": "door_jfdzs4jegvwgfapg", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_8gqw24qgotjmoh6h", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_8gqw24qgotjmoh6h", + "position": [1, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_u77o9vdoy157oayz": { + "id": "door_u77o9vdoy157oayz", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_xccvsw30w0cm6ll4", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_xccvsw30w0cm6ll4", + "position": [1.7000000000000002, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "glass", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "visible", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.03, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_uxttk8axivfeq8ba": { + "id": "door_uxttk8axivfeq8ba", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 1.8, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_8dl9xr8i4t29kdju", + "visible": true, + "doorType": "folding", + "metadata": {}, + "panicBar": false, + "parentId": "wall_8dl9xr8i4t29kdju", + "position": [1.7375000000000003, 1.05, 0], + "rotation": [0, 9.42477796076938, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.008, + "panelInset": 0.025, + "heightRatio": 1, + "columnRatios": [1], + "dividerThickness": 0.02 + } + ], + "leafCount": 4, + "threshold": false, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "visible", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.03, 0.04], + "frameThickness": 0.05, + "operationState": 0.65, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "site_mzooxtt7vdjmnfz5": { + "id": "site_mzooxtt7vdjmnfz5", + "type": "site", + "object": "node", + "polygon": { + "type": "polygon", + "points": [ + [-15, -15], + [2.669066905975342, -22.70280647277832], + [15, -15], + [15, 15], + [-15, 15] + ] + }, + "visible": true, + "children": ["building_opg1pcqcaexock0a"], + "metadata": {}, + "parentId": null + }, + "slab_3pdm80mtcj01rkto": { + "id": "slab_3pdm80mtcj01rkto", + "name": "Room 8 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-1, 2.5], [-1, 4.5], [-2, 4.5], [-2, 2.5]], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_3xfuw0pinjiaywhj": { + "id": "slab_3xfuw0pinjiaywhj", + "name": "Room 10 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-2.525, 0.5], + [-6, 0.5], + [-6, -0.8595930435954164], + [-2.525, -0.8595930435954162] + ], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_6dw0uk679w25ou4x": { + "id": "slab_6dw0uk679w25ou4x", + "name": "Room 5 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-6, 2.5], + [-2, 2.5], + [-2, 7.5], + [-4.6000000000000005, 7.5], + [-4.6000000000000005, 6], + [-6, 6] + ], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_7q1m7rrhuvw8tply": { + "id": "slab_7q1m7rrhuvw8tply", + "name": "Room 3 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-4.6000000000000005, 7.5], + [-6, 7.5], + [-6, 6], + [-4.6000000000000005, 6] + ], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_9cvs1mxa2pomo9aw": { + "id": "slab_9cvs1mxa2pomo9aw", + "name": "Room 9 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-6, -0.8595930435954164], + [-6, -7], + [1.75, -7], + [1.75, -5], + [0, -5], + [0, 0.5], + [-2.525, 0.5], + [-2.525, -0.8595930435954162] + ], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_fe79j0kl5jaz18g9": { + "id": "slab_fe79j0kl5jaz18g9", + "name": "Room 7 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [6.75, -5], + [6.75, 7.5], + [-2, 7.5], + [-2, 4.5], + [-1, 4.5], + [-1, 2.5], + [-5.05, 2.5], + [-5.05, 0.5], + [0, 0.5], + [0, -5] + ], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_lii0xjwv02vtck7x": { + "id": "slab_lii0xjwv02vtck7x", + "name": "Room 11 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-5.05, 0.5], [-5.05, 2.5], [-6, 2.5], [-6, 0.5]], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_nr7tc88e1o3xsyiq": { + "id": "slab_nr7tc88e1o3xsyiq", + "name": "Slab 8", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-10, 2], [-13, 1.5], [-12.5, -2], [-10, -1.5]], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 2.49799398413038, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_rnkvnpngzvcs2mxa": { + "id": "slab_rnkvnpngzvcs2mxa", + "name": "Room 2 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-10.75, -6.25], + [-7.249198776, -6.25], + [-7.249198776, -2.75], + [-10.75, -2.75] + ], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "wall_075j2ctgqolbmb91": { + "id": "wall_075j2ctgqolbmb91", + "end": [1.75, -5], + "name": "Wall 20", + "type": "wall", + "start": [0, -5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "exterior" + }, + "wall_0gjvnn2kyfj71m75": { + "id": "wall_0gjvnn2kyfj71m75", + "end": [11.5, -17.5], + "name": "Wall 49", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [9.5, -9.5], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_to8wj5k809p5dc82", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_0pb1oz4mexnwt5gz": { + "id": "wall_0pb1oz4mexnwt5gz", + "end": [-1, 2.5], + "name": "Wall 28", + "type": "wall", + "start": [-1, 4.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_iumom5q4laa8inub"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "assemblyLayers": [] + }, + "wall_17am4d8ex5h81g3x": { + "id": "wall_17am4d8ex5h81g3x", + "end": [-6, 2.5], + "name": "Wall 6", + "type": "wall", + "start": [-6, 6], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_2u4hb1whhn5c5d5x"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_28zw5ynivttqdj0o": { + "id": "wall_28zw5ynivttqdj0o", + "end": [-2, 2.5], + "name": "Wall 13", + "type": "wall", + "start": [-1, 2.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "assemblyLayers": [] + }, + "wall_290mz1o47yk6gt96": { + "id": "wall_290mz1o47yk6gt96", + "end": [0, -5], + "name": "Wall 21", + "type": "wall", + "start": [0, 0.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "exterior" + }, + "wall_2kghl1sm9vu9gezk": { + "id": "wall_2kghl1sm9vu9gezk", + "end": [-10.75, -6.25], + "name": "Wall 11", + "type": "wall", + "start": [-10.75, -2.75], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_2ym04hv4brklswe0": { + "id": "wall_2ym04hv4brklswe0", + "end": [6.75, 7.5], + "name": "Wall 4", + "type": "wall", + "start": [6.75, 1.25], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_4rjd2lhn0kapokbi": { + "id": "wall_4rjd2lhn0kapokbi", + "end": [5.5, -13.5], + "name": "Wall 47", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [0.5, -8], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_to8wj5k809p5dc82", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_597tp0pvgvhvnabd": { + "id": "wall_597tp0pvgvhvnabd", + "end": [1.75, -7], + "name": "Wall 1", + "type": "wall", + "start": [-6, -7], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_z76realwuq6o2nc1", "window_euu92ugb9g1a5y26"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_5nk7aadyro5fp2yd": { + "id": "wall_5nk7aadyro5fp2yd", + "end": [6.75, 1.25], + "name": "Wall 4", + "type": "wall", + "start": [6.75, -5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_om4gt4gt7a46n93c", "window_94ik4qafvnn74h75"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_63ovkqaw83qikxzi": { + "id": "wall_63ovkqaw83qikxzi", + "end": [-3, 12.5], + "name": "Wall 35", + "type": "wall", + "start": [-6, 7.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "curveOffset": -1.35, + "assemblyLayers": [] + }, + "wall_67r2efbtiek7ine9": { + "id": "wall_67r2efbtiek7ine9", + "end": [-2.525, 0.5], + "name": "Wall 22", + "type": "wall", + "start": [-5.05, 0.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "exterior" + }, + "wall_68mr9skvqcbgh4ad": { + "id": "wall_68mr9skvqcbgh4ad", + "end": [6, -2.5], + "name": "Wall 45", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [14, -17], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_to8wj5k809p5dc82", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_6zx56nvuqhiuejlo": { + "id": "wall_6zx56nvuqhiuejlo", + "end": [11, 9.5], + "name": "Wall 38", + "type": "wall", + "start": [11, 5], + "height": 0.7331780629740767, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "assemblyLayers": [] + }, + "wall_8cgfardys3fu092a": { + "id": "wall_8cgfardys3fu092a", + "end": [5.75, 1.25], + "name": "Wall 26", + "type": "wall", + "start": [6.75, 1.25], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown" + }, + "wall_8dl9xr8i4t29kdju": { + "id": "wall_8dl9xr8i4t29kdju", + "end": [-6, -0.8595930435954164], + "name": "Wall 31", + "type": "wall", + "start": [-2.525, -0.8595930435954162], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_uxttk8axivfeq8ba"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown" + }, + "wall_8gqw24qgotjmoh6h": { + "id": "wall_8gqw24qgotjmoh6h", + "end": [0, 0.5], + "name": "Wall 22", + "type": "wall", + "start": [-2.525, 0.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_jfdzs4jegvwgfapg"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "exterior" + }, + "wall_8x2wsldzmgsk9dtk": { + "id": "wall_8x2wsldzmgsk9dtk", + "end": [1.75, -5], + "name": "Wall 2", + "type": "wall", + "start": [1.75, -7], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_8xoab4o07c22qe73": { + "id": "wall_8xoab4o07c22qe73", + "end": [11, 5], + "name": "Wall 37", + "type": "wall", + "start": [6.5, 5.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "curveOffset": -1.35, + "assemblyLayers": [] + }, + "wall_919ya5j89y8b74gn": { + "id": "wall_919ya5j89y8b74gn", + "end": [-1.5, 10.5], + "name": "Wall 36", + "type": "wall", + "start": [-3, 12.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "curveOffset": -1.35, + "assemblyLayers": [] + }, + "wall_ay4i32j42khlxjsd": { + "id": "wall_ay4i32j42khlxjsd", + "end": [6.75, -5], + "name": "Wall 3", + "type": "wall", + "start": [1.75, -5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_armztuvxan66q5ct"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_b6pgekxsakmmf21j": { + "id": "wall_b6pgekxsakmmf21j", + "end": [-13, 1.5], + "name": "Wall 44", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [-12.5, -2], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "exterior", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_bgtwxo0a0e6vvucm": { + "id": "wall_bgtwxo0a0e6vvucm", + "end": [-10, 2], + "name": "Wall 41", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [-13, 1.5], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "exterior", + "thickness": 0.12, + "curveOffset": -1.5206906325745546, + "assemblyLayers": [] + }, + "wall_d438lv0gfnu9ulpl": { + "id": "wall_d438lv0gfnu9ulpl", + "end": [-5.05, 0.5], + "name": "Wall 23", + "type": "wall", + "start": [-5.05, 2.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_3tblpxorpkmly0i7"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "exterior" + }, + "wall_g8asgs8crqg1njuf": { + "id": "wall_g8asgs8crqg1njuf", + "end": [9.5, -9.5], + "name": "Wall 48", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [5.5, -13.5], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_to8wj5k809p5dc82", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_gejdhoues39krxgx": { + "id": "wall_gejdhoues39krxgx", + "end": [5, 9.5], + "name": "Wall 39", + "type": "wall", + "start": [11, 9.5], + "height": 0.7331780629740767, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "assemblyLayers": [] + }, + "wall_gs71n1w2fznv2osi": { + "id": "wall_gs71n1w2fznv2osi", + "end": [-2, 4.5], + "name": "Wall 9", + "type": "wall", + "start": [-2, 2.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_h467hotghrdm88l2": { + "id": "wall_h467hotghrdm88l2", + "end": [-2, 4.5], + "name": "Wall 11", + "type": "wall", + "start": [-1, 4.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "assemblyLayers": [] + }, + "wall_htx18qj2xjmeo2kq": { + "id": "wall_htx18qj2xjmeo2kq", + "end": [-6, 7.5], + "name": "Wall 5", + "type": "wall", + "start": [-4.6000000000000005, 7.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_j9wtbo4gd56ehlaq": { + "id": "wall_j9wtbo4gd56ehlaq", + "end": [0.5, 4], + "name": "Wall 34", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [0.5, 1], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "curveOffset": 0, + "assemblyLayers": [] + }, + "wall_jb7oq1p7ezglt2dj": { + "id": "wall_jb7oq1p7ezglt2dj", + "end": [2, 7.5], + "name": "Wall 5", + "type": "wall", + "start": [6.75, 7.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_2t3o71fi4e6vb9z7"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_mha03gkut8yj34gm": { + "id": "wall_mha03gkut8yj34gm", + "end": [-7.249198776, -6.25], + "name": "Wall 8", + "type": "wall", + "start": [-10.75, -6.25], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_8f6gd7jm2w8veibl"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_oh60g8trnt4eevgt": { + "id": "wall_oh60g8trnt4eevgt", + "end": [-7.249198776, -2.75], + "name": "Wall 9", + "type": "wall", + "start": [-7.249198776, -6.25], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_o75d2dm3qpzvt00g"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_oyb9n0a4wyypiak2": { + "id": "wall_oyb9n0a4wyypiak2", + "end": [-10.75, -2.75], + "name": "Wall 10", + "type": "wall", + "start": [-7.249198776, -2.75], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_q6zjwwwrrp4enn61": { + "id": "wall_q6zjwwwrrp4enn61", + "end": [2, 7.5], + "name": "Wall 7", + "type": "wall", + "start": [2, 6.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown" + }, + "wall_qkx6h2ffxf2qvat5": { + "id": "wall_qkx6h2ffxf2qvat5", + "end": [-6, 6], + "name": "Wall 18", + "type": "wall", + "start": [-4.6000000000000005, 6], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown" + }, + "wall_quwfh3kz9ozysirh": { + "id": "wall_quwfh3kz9ozysirh", + "end": [3, 1.5], + "name": "Wall 32", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [3.5, 4], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_rv4mboowu4blii9v": { + "id": "wall_rv4mboowu4blii9v", + "end": [-6, 6], + "name": "Wall 6", + "type": "wall", + "start": [-6, 7.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_s17ardyxx1kmzioy": { + "id": "wall_s17ardyxx1kmzioy", + "end": [-12.5, -2], + "name": "Wall 43", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [-10, -1.5], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "exterior", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_sm6sr4glzmtruqrq": { + "id": "wall_sm6sr4glzmtruqrq", + "end": [5, 12], + "name": "Wall 40", + "type": "wall", + "start": [5, 9.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown", + "assemblyLayers": [] + }, + "wall_sw6l32tjc3nzyoub": { + "id": "wall_sw6l32tjc3nzyoub", + "end": [-6, -7], + "name": "Wall 6", + "type": "wall", + "start": [-6, 2.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_4zjvos53aqga95m0", "window_w5kjcoaqonf1xc4g"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior" + }, + "wall_txgkulm4vrp4v6h0": { + "id": "wall_txgkulm4vrp4v6h0", + "end": [-2, 7.5], + "name": "Wall 9", + "type": "wall", + "start": [-2, 4.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_unavdn1k0ktnkrm3": { + "id": "wall_unavdn1k0ktnkrm3", + "end": [0.5, -8], + "name": "Wall 46", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [6, -2.5], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_to8wj5k809p5dc82", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_v3brr27ru1yhpb3h": { + "id": "wall_v3brr27ru1yhpb3h", + "end": [1, 2.5], + "name": "Wall 33", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [3, 1.5], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "unknown", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_wofxy5sk7jenwxhn": { + "id": "wall_wofxy5sk7jenwxhn", + "end": [-6, 2.5], + "name": "Wall 14", + "type": "wall", + "start": [-5.05, 2.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "exterior" + }, + "wall_x0mx4waevowv9bzj": { + "id": "wall_x0mx4waevowv9bzj", + "end": [-10, -1.5], + "name": "Wall 42", + "type": "wall", + "crown": { + "proud": 0.055, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "crown-cove" + }, + "start": [-10, 2], + "height": 2.8, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "skirting": { + "proud": 0.02, + "sides": "both", + "height": 0.12, + "enabled": true, + "profile": "base-colonial" + }, + "chairRail": { + "proud": 0.026, + "sides": "interior", + "height": 0.055, + "enabled": true, + "offsetY": 0.9, + "profile": "rail-rounded" + }, + "frontSide": "exterior", + "thickness": 0.12, + "assemblyLayers": [] + }, + "wall_xccvsw30w0cm6ll4": { + "id": "wall_xccvsw30w0cm6ll4", + "end": [-2, 7.5], + "name": "Wall 5", + "type": "wall", + "start": [2, 7.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_u77o9vdoy157oayz"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_xetjlo0mb59g8ec1": { + "id": "wall_xetjlo0mb59g8ec1", + "end": [-5.05, 0.5], + "name": "Wall 22", + "type": "wall", + "start": [-6, 0.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown" + }, + "wall_xvdj23rc9pjtoul5": { + "id": "wall_xvdj23rc9pjtoul5", + "end": [-5.05, 2.5], + "name": "Wall 14", + "type": "wall", + "start": [-2, 2.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_gm5prhor6c3964fr"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "exterior", + "assemblyLayers": [] + }, + "wall_yhzx1p89bhtngr0f": { + "id": "wall_yhzx1p89bhtngr0f", + "end": [-4.6000000000000005, 6], + "name": "Wall 16", + "type": "wall", + "start": [-4.6000000000000005, 7.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown" + }, + "wall_zeugtceqcu536k6s": { + "id": "wall_zeugtceqcu536k6s", + "end": [-4.6000000000000005, 7.5], + "name": "Wall 5", + "type": "wall", + "start": [-2, 7.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_ouem007ynbasm0tc"], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "interior", + "assemblyLayers": [] + }, + "wall_zllt3fpao2kc21m7": { + "id": "wall_zllt3fpao2kc21m7", + "end": [-2.525, -0.8595930435954162], + "name": "Wall 30", + "type": "wall", + "start": [-2.525, 0.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "frontSide": "unknown" + }, + "zone_0s6ovw0bk7yrawt8": { + "id": "zone_0s6ovw0bk7yrawt8", + "name": "Room A", + "type": "zone", + "color": "#f59e0b", + "object": "node", + "polygon": [[7, 1.5], [0, 1.5], [0, -5], [7, -5]], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh" + }, + "zone_26ckz415d87vfb55": { + "id": "zone_26ckz415d87vfb55", + "name": "Room B", + "type": "zone", + "color": "#ef4444", + "object": "node", + "polygon": [[2, -5], [0, -5], [0, 0.5], [-6, 0.5], [-6, -7], [2, -7]], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh" + }, + "zone_c6a97occymu4p8bs": { + "id": "zone_c6a97occymu4p8bs", + "name": "Room C", + "type": "zone", + "color": "#a855f7", + "object": "node", + "polygon": [[-1, 2.5], [-1, 4.5], [-2, 4.5], [-2, 2.5]], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "occupancy": "", + "spaceRole": "generic", + "roomNumber": "", + "wallFinish": "", + "floorFinish": "", + "autoFromWalls": true, + "ceilingFinish": "", + "ceilingHeight": 2.7, + "boundaryWallIds": [ + "wall_0pb1oz4mexnwt5gz", + "wall_h467hotghrdm88l2", + "wall_gs71n1w2fznv2osi", + "wall_28zw5ynivttqdj0o" + ], + "enclosureStatus": "auto", + "clearDimensionPolicy": "none" + }, + "zone_efax5p51xhl203sw": { + "id": "zone_efax5p51xhl203sw", + "name": "Room D", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[-2, 7.5], [7, 7.5], [7, 1.5], [-1, 1.5], [-1, 4], [-2, 4]], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh" + }, + "zone_idu4ovu6zimt19ie": { + "id": "zone_idu4ovu6zimt19ie", + "name": "Room E", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-7.25, -6.25], + [-7.25, -2.75], + [-10.75, -2.75], + [-10.75, -6.25] + ], + "visible": true, + "metadata": { + "roomPreset": { + "sourceItemId": "item_preset01" + } + }, + "parentId": "level_o2mqfskh43eds0kh", + "occupancy": "", + "spaceRole": "generic", + "roomNumber": "", + "wallFinish": "", + "floorFinish": "", + "autoFromWalls": false, + "ceilingFinish": "", + "ceilingHeight": 2.7, + "boundaryWallIds": [], + "enclosureStatus": "auto", + "clearDimensionPolicy": "none" + }, + "zone_plc8aapk45z4j29b": { + "id": "zone_plc8aapk45z4j29b", + "name": "Room E", + "type": "zone", + "color": "#10b981", + "object": "node", + "polygon": [ + [-2, 7.5], + [-4.5, 7.5], + [-4.5, 6], + [-6, 6], + [-6, 2.5], + [-2, 2.5] + ], + "visible": true, + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh" + }, + "level_o2mqfskh43eds0kh": { + "id": "level_o2mqfskh43eds0kh", + "type": "level", + "level": 0, + "height": 2.55, + "object": "node", + "visible": true, + "children": [ + "wall_8x2wsldzmgsk9dtk", + "wall_ay4i32j42khlxjsd", + "wall_597tp0pvgvhvnabd", + "wall_jb7oq1p7ezglt2dj", + "wall_q6zjwwwrrp4enn61", + "wall_xccvsw30w0cm6ll4", + "wall_gs71n1w2fznv2osi", + "wall_txgkulm4vrp4v6h0", + "wall_h467hotghrdm88l2", + "wall_28zw5ynivttqdj0o", + "wall_zeugtceqcu536k6s", + "wall_htx18qj2xjmeo2kq", + "wall_yhzx1p89bhtngr0f", + "wall_rv4mboowu4blii9v", + "wall_17am4d8ex5h81g3x", + "wall_qkx6h2ffxf2qvat5", + "slab_7q1m7rrhuvw8tply", + "ceiling_uvpbkkg9qiy66eyp", + "wall_075j2ctgqolbmb91", + "wall_290mz1o47yk6gt96", + "wall_sw6l32tjc3nzyoub", + "wall_xetjlo0mb59g8ec1", + "wall_xvdj23rc9pjtoul5", + "wall_wofxy5sk7jenwxhn", + "slab_6dw0uk679w25ou4x", + "ceiling_z47n7p0iy0cs74b0", + "wall_d438lv0gfnu9ulpl", + "wall_5nk7aadyro5fp2yd", + "wall_2ym04hv4brklswe0", + "slab_fe79j0kl5jaz18g9", + "ceiling_txx2lwpdnqmhsz03", + "wall_8cgfardys3fu092a", + "wall_0pb1oz4mexnwt5gz", + "slab_3pdm80mtcj01rkto", + "ceiling_7svsrg2f8q0mpfo8", + "wall_67r2efbtiek7ine9", + "wall_8gqw24qgotjmoh6h", + "slab_9cvs1mxa2pomo9aw", + "ceiling_sjwhk3lo4w5zijnh", + "wall_zllt3fpao2kc21m7", + "wall_8dl9xr8i4t29kdju", + "zone_efax5p51xhl203sw", + "zone_0s6ovw0bk7yrawt8", + "zone_26ckz415d87vfb55", + "zone_c6a97occymu4p8bs", + "zone_plc8aapk45z4j29b", + "wall_quwfh3kz9ozysirh", + "slab_3xfuw0pinjiaywhj", + "slab_lii0xjwv02vtck7x", + "ceiling_bsup9d1o2k3e1ncw", + "ceiling_dh8z6fnkdw2v7q3y", + "wall_v3brr27ru1yhpb3h", + "wall_j9wtbo4gd56ehlaq", + "wall_63ovkqaw83qikxzi", + "wall_919ya5j89y8b74gn", + "wall_8xoab4o07c22qe73", + "wall_6zx56nvuqhiuejlo", + "wall_gejdhoues39krxgx", + "wall_sm6sr4glzmtruqrq", + "slab_nr7tc88e1o3xsyiq", + "wall_bgtwxo0a0e6vvucm", + "wall_x0mx4waevowv9bzj", + "wall_s17ardyxx1kmzioy", + "wall_b6pgekxsakmmf21j", + "ceiling_mc61hqdwsc04rnus", + "wall_mha03gkut8yj34gm", + "wall_oh60g8trnt4eevgt", + "wall_oyb9n0a4wyypiak2", + "wall_2kghl1sm9vu9gezk", + "slab_rnkvnpngzvcs2mxa", + "ceiling_s5408m9m09fja1z6", + "zone_idu4ovu6zimt19ie" + ], + "metadata": {}, + "parentId": null + }, + "level_sxzzgczbfryx35f9": { + "id": "level_sxzzgczbfryx35f9", + "type": "level", + "level": 1, + "height": 2.5, + "object": "node", + "visible": true, + "children": [], + "metadata": {}, + "parentId": "building_opg1pcqcaexock0a" + }, + "level_to8wj5k809p5dc82": { + "id": "level_to8wj5k809p5dc82", + "type": "level", + "level": -1, + "height": 2.5, + "object": "node", + "visible": true, + "children": [ + "wall_68mr9skvqcbgh4ad", + "wall_unavdn1k0ktnkrm3", + "wall_4rjd2lhn0kapokbi", + "wall_g8asgs8crqg1njuf", + "wall_0gjvnn2kyfj71m75", + "elevator_is2pp44c7ald26h7" + ], + "metadata": {}, + "parentId": "building_opg1pcqcaexock0a" + }, + "window_2t3o71fi4e6vb9z7": { + "id": "window_2t3o71fi4e6vb9z7", + "name": "Window 5", + "side": "front", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_jb7oq1p7ezglt2dj", + "visible": true, + "metadata": {}, + "parentId": "wall_jb7oq1p7ezglt2dj", + "position": [2.5, 1.25, 0], + "rotation": [0, 0, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_2u4hb1whhn5c5d5x": { + "id": "window_2u4hb1whhn5c5d5x", + "name": "Window 5", + "side": "back", + "sill": false, + "type": "window", + "width": 2.5821362717886975, + "height": 0.96320213380565, + "object": "node", + "wallId": "wall_17am4d8ex5h81g3x", + "visible": true, + "metadata": {}, + "parentId": "wall_17am4d8ex5h81g3x", + "position": [ + 1.7086506198362748, 1.518398933097175, 2.5552331372260513e-17 + ], + "rotation": [0, 3.141592653589793, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "awning", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 0.3, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_4zjvos53aqga95m0": { + "id": "window_4zjvos53aqga95m0", + "name": "Window 5", + "side": "back", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_sw6l32tjc3nzyoub", + "visible": true, + "metadata": {}, + "parentId": "wall_sw6l32tjc3nzyoub", + "position": [8, 1.25, 0], + "rotation": [0, 3.141592653589793, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_94ik4qafvnn74h75": { + "id": "window_94ik4qafvnn74h75", + "name": "Window 5", + "side": "front", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_5nk7aadyro5fp2yd", + "visible": true, + "metadata": {}, + "parentId": "wall_5nk7aadyro5fp2yd", + "position": [1.5, 1.25, 0], + "rotation": [0, 0, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_euu92ugb9g1a5y26": { + "id": "window_euu92ugb9g1a5y26", + "name": "Window 5", + "side": "back", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_597tp0pvgvhvnabd", + "visible": true, + "metadata": {}, + "parentId": "wall_597tp0pvgvhvnabd", + "position": [2, 1.25, 0], + "rotation": [0, 3.141592653589793, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_o75d2dm3qpzvt00g": { + "id": "window_o75d2dm3qpzvt00g", + "name": "Window 5", + "side": "front", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_oh60g8trnt4eevgt", + "visible": true, + "metadata": {}, + "parentId": "wall_oh60g8trnt4eevgt", + "position": [1.75, 1.5, 0], + "rotation": [0, 6.283185307179586, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_om4gt4gt7a46n93c": { + "id": "window_om4gt4gt7a46n93c", + "name": "Window 5", + "side": "front", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_5nk7aadyro5fp2yd", + "visible": true, + "metadata": {}, + "parentId": "wall_5nk7aadyro5fp2yd", + "position": [4.5, 1.25, 0], + "rotation": [0, 0, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_ouem007ynbasm0tc": { + "id": "window_ouem007ynbasm0tc", + "name": "Window 5", + "side": "back", + "sill": false, + "type": "window", + "width": 1.5672227378182955, + "height": 1.062739605261072, + "object": "node", + "wallId": "wall_zeugtceqcu536k6s", + "visible": true, + "metadata": {}, + "parentId": "wall_zeugtceqcu536k6s", + "position": [ + 1.3130584858159007, 1.468630197369464, -5.350990267601551e-17 + ], + "rotation": [0, 3.141592653589793, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "awning", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 0.3, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_w5kjcoaqonf1xc4g": { + "id": "window_w5kjcoaqonf1xc4g", + "name": "Window 5", + "side": "back", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_sw6l32tjc3nzyoub", + "visible": true, + "metadata": {}, + "parentId": "wall_sw6l32tjc3nzyoub", + "position": [4.6, 1.25, 0], + "rotation": [0, 3.141592653589793, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_z76realwuq6o2nc1": { + "id": "window_z76realwuq6o2nc1", + "name": "Window 5", + "side": "back", + "sill": false, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_597tp0pvgvhvnabd", + "visible": true, + "metadata": {}, + "parentId": "wall_597tp0pvgvhvnabd", + "position": [5.72, 1.25, 0], + "rotation": [0, 3.141592653589793, 0], + "rowRatios": [0.75, 0.25], + "sillDepth": 0.08, + "archHeight": 0.35, + "frameDepth": 0.11, + "hingesSide": "left", + "windowType": "single-hung", + "openingKind": "window", + "columnRatios": [1], + "cornerRadius": 0.38, + "openingShape": "rectangle", + "casementStyle": "single", + "sillThickness": 0.03, + "frameThickness": 0.06, + "operationState": 1, + "awningDirection": "up", + "constructionType": "framed", + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingCornerRadii": [0.15, 0.15, 0.15, 0.15], + "openingRevealRadius": 0, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "ceiling_7svsrg2f8q0mpfo8": { + "id": "ceiling_7svsrg2f8q0mpfo8", + "name": "Room 8 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [[-1, 2.5], [-1, 4.5], [-2, 4.5], [-2, 2.5]], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_bsup9d1o2k3e1ncw": { + "id": "ceiling_bsup9d1o2k3e1ncw", + "name": "Room 10 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [ + [-2.525, 0.5], + [-6, 0.5], + [-6, -0.8595930435954164], + [-2.525, -0.8595930435954162] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_dh8z6fnkdw2v7q3y": { + "id": "ceiling_dh8z6fnkdw2v7q3y", + "name": "Room 11 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [[-5.05, 0.5], [-5.05, 2.5], [-6, 2.5], [-6, 0.5]], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_mc61hqdwsc04rnus": { + "id": "ceiling_mc61hqdwsc04rnus", + "name": "Room 12 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [ + [-11.156944734580188, 3.2314901568582024], + [-11.75, 3.2499999999999996], + [-12.304995031675457, 3.0401484406756576], + [-12.737436867076458, 2.633883476483184], + [-12.981490156858202, 2.0930552654198125], + [-13, 1.5], + [-12.5, -2], + [-10, -1.5], + [-10, 2], + [-10.209851559324342, 2.554995031675456], + [-10.616116523516816, 2.9874368670764584] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_s5408m9m09fja1z6": { + "id": "ceiling_s5408m9m09fja1z6", + "name": "Room 2 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.55, + "object": "node", + "polygon": [ + [-10.75, -6.25], + [-7.249198776, -6.25], + [-7.249198776, -2.75], + [-10.75, -2.75] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_sjwhk3lo4w5zijnh": { + "id": "ceiling_sjwhk3lo4w5zijnh", + "name": "Room 9 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [ + [-6, -0.8595930435954164], + [-6, -7], + [1.75, -7], + [1.75, -5], + [0, -5], + [0, 0.5], + [-2.525, 0.5], + [-2.525, -0.8595930435954162] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_txx2lwpdnqmhsz03": { + "id": "ceiling_txx2lwpdnqmhsz03", + "name": "Room 7 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [ + [6.75, -5], + [6.75, 7.5], + [-2, 7.5], + [-2, 4.5], + [-1, 4.5], + [-1, 2.5], + [-5.05, 2.5], + [-5.05, 0.5], + [0, 0.5], + [0, -5] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_uvpbkkg9qiy66eyp": { + "id": "ceiling_uvpbkkg9qiy66eyp", + "name": "Room 3 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [ + [-4.6000000000000005, 7.5], + [-6, 7.5], + [-6, 6], + [-4.6000000000000005, 6] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_z47n7p0iy0cs74b0": { + "id": "ceiling_z47n7p0iy0cs74b0", + "name": "Room 5 Ceiling", + "type": "ceiling", + "holes": [], + "object": "node", + "polygon": [ + [-6, 2.5], + [-2, 2.5], + [-2, 7.5], + [-4.6000000000000005, 7.5], + [-4.6000000000000005, 6], + [-6, 6] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_o2mqfskh43eds0kh", + "holeMetadata": [], + "autoFromWalls": true + }, + "building_opg1pcqcaexock0a": { + "id": "building_opg1pcqcaexock0a", + "type": "building", + "object": "node", + "visible": true, + "children": [ + "level_o2mqfskh43eds0kh", + "level_sxzzgczbfryx35f9", + "level_to8wj5k809p5dc82" + ], + "metadata": {}, + "parentId": null, + "position": [0, 0, 0], + "rotation": [0, 0, 0] + }, + "elevator_is2pp44c7ald26h7": { + "id": "elevator_is2pp44c7ald26h7", + "name": "Elevator 1", + "type": "elevator", + "depth": 2, + "speed": 2.2, + "width": 2, + "object": "node", + "dwellMs": 1400, + "visible": true, + "metadata": {}, + "parentId": "level_to8wj5k809p5dc82", + "position": [-3.5, 0, 3.5], + "rotation": -0.5572337824763812, + "cabHeight": 2.35, + "doorStyle": "center-opening", + "doorWidth": 0.95, + "toLevelId": "level_ur37y4bqjfs8c1xx", + "doorHeight": 2.1, + "shaftStyle": "solid", + "fromLevelId": "level_mqq2u8qtyor3ahss", + "defaultLevelId": "level_mqq2u8qtyor3ahss", + "doorDurationMs": 900, + "doorPanelStyle": "glass-frame", + "disabledLevelIds": [], + "shaftWallThickness": 0.09, + "serviceOnlyLevelIds": [] + } + }, + "areas": [], + "gaps": [] +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-21.json b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-21.json new file mode 100644 index 0000000000..a84d8170e0 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/frozen-gate/scene-21.json @@ -0,0 +1,2365 @@ +{ + "sceneId": "scene-21", + "rootNodeIds": [ + "site_seisz0r0cw00i8ui", + "level_s77ej91id9kylvae", + "building_cufg85qnzt1dpy3r" + ], + "nodes": { + "door_537qkuq9kbjpkvj7": { + "id": "door_537qkuq9kbjpkvj7", + "name": "Door 3", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_fpmilgdmzj65f0uc", + "visible": true, + "metadata": {}, + "panicBar": false, + "parentId": "wall_fpmilgdmzj65f0uc", + "position": [0.9, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "threshold": true, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "handleHeight": 1.05, + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "panicBarHeight": 1, + "swingDirection": "inward", + "thresholdHeight": 0.02 + }, + "door_6ubqjrvl0dqiy0ly": { + "id": "door_6ubqjrvl0dqiy0ly", + "name": "Door 1", + "side": "front", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_cn7fjrln3m91hrlw", + "visible": true, + "metadata": {}, + "panicBar": false, + "parentId": "wall_cn7fjrln3m91hrlw", + "position": [1.25, 1.05, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "threshold": true, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "handleHeight": 1.05, + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "panicBarHeight": 1, + "swingDirection": "inward", + "thresholdHeight": 0.02 + }, + "door_huvn8g5xhl25arvj": { + "id": "door_huvn8g5xhl25arvj", + "name": "Door 2", + "side": "back", + "type": "door", + "width": 0.8, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_zejsv7so71uy6v6j", + "visible": true, + "metadata": {}, + "panicBar": false, + "parentId": "wall_zejsv7so71uy6v6j", + "position": [0.45, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "threshold": true, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "handleHeight": 1.05, + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "panicBarHeight": 1, + "swingDirection": "inward", + "thresholdHeight": 0.02 + }, + "door_r5n7cv0l6o6fb4h5": { + "id": "door_r5n7cv0l6o6fb4h5", + "name": "Door 1", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_lw9oab3p7670erll", + "visible": true, + "metadata": {}, + "panicBar": false, + "parentId": "wall_lw9oab3p7670erll", + "position": [0.5, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "threshold": true, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "handleHeight": 1.05, + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "panicBarHeight": 1, + "swingDirection": "inward", + "thresholdHeight": 0.02 + }, + "door_wc258tpvshg0gjhs": { + "id": "door_wc258tpvshg0gjhs", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.95, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_04kbr5brwhqoe9kp", + "visible": true, + "metadata": {}, + "panicBar": false, + "parentId": "wall_04kbr5brwhqoe9kp", + "position": [0.5, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "threshold": true, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "handleHeight": 1.05, + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "panicBarHeight": 1, + "swingDirection": "inward", + "thresholdHeight": 0.02 + }, + "site_seisz0r0cw00i8ui": { + "id": "site_seisz0r0cw00i8ui", + "type": "site", + "object": "node", + "polygon": { + "type": "polygon", + "points": [[-15, -15], [15, -15], [15, 15], [-15, 15]] + }, + "visible": true, + "children": ["building_cufg85qnzt1dpy3r"], + "metadata": {}, + "parentId": null + }, + "slab_0h665xzly6z7ibd7": { + "id": "slab_0h665xzly6z7ibd7", + "name": "Room 6 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [9.850000000000001, 9.700000000000001], + [8.8, 9.700000000000001], + [8.8, 9.3], + [8.15, 9.3], + [8.15, 9.200000000000001], + [8.3, 9.200000000000001], + [8.3, 7.4], + [9.850000000000001, 7.4] + ], + "visible": true, + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_1qxilit9sqhlr5k3": { + "id": "slab_1qxilit9sqhlr5k3", + "name": "Room 7 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [9.850000000000001, 11.5], + [8.15, 11.5], + [8.15, 9.3], + [8.8, 9.3], + [8.8, 9.700000000000001], + [9.850000000000001, 9.700000000000001] + ], + "visible": true, + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_42o2bxthq8wk6i9j": { + "id": "slab_42o2bxthq8wk6i9j", + "name": "Room 5 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [4.850000000000001, 11.5], + [4.85, 6.6000000000000005], + [9, 6.6000000000000005], + [9, 7.4], + [8.3, 7.4], + [8.3, 9.200000000000001], + [8.15, 9.200000000000001], + [8.15, 11.5] + ], + "visible": true, + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_7u5zmy6mvy5edxpv": { + "id": "slab_7u5zmy6mvy5edxpv", + "name": "Room 8 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [11.150052310400081, 7.949996448536031], + [11.150126917140366, 4.799997340542237], + [14.000126917127918, 4.800005763346264], + [13.999860390136186, 7.950005752070608] + ], + "visible": true, + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_b99b0vdon5mfo2gv": { + "id": "slab_b99b0vdon5mfo2gv", + "name": "Room 7 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [14, 14], + [13, 14], + [13, 12.85], + [11.4, 12.850000000000001], + [11.4, 12.3], + [11.200000000000001, 12.3], + [11.200000000000001, 11.8], + [9.65, 11.8], + [9.65, 12.4], + [4.45, 12.4], + [4.45, 12.1], + [4.25, 12.1], + [4.25, 6], + [5.05, 4.7], + [10.75, 4.7], + [10.75, 7.15], + [9.599999856860167, 7.150000018402363], + [9.600000906552417, 8.250000018401861], + [9.750000906551431, 8.250000406924356], + [9.749995467237504, 10.35000002628131], + [9.849995467237504, 10.350000035041878], + [9.850000001600208, 7.150000014401847], + [10.849999999999127, 7.149999704416012], + [10.850000998639025, 10.349999334231049], + [11.149995467192301, 10.34999480153872], + [11.150052310400081, 7.949996448536031], + [12.149860390385824, 7.95003614374959], + [12.16, 11.600000000000001], + [14, 11.600000000000001] + ], + "visible": true, + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_ctzn70siekeblrsh": { + "id": "slab_ctzn70siekeblrsh", + "name": "Room 4 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [13.999889274484472, 8.549995191187701], + [12.150418963193307, 8.550035883746549], + [12.149860390385824, 7.95003614374959], + [13.999860390136186, 7.950005752070608] + ], + "visible": true, + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_espwew9tbh3cuz2v": { + "id": "slab_espwew9tbh3cuz2v", + "name": "Room 3 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [9, 6.6000000000000005], + [10.950000000000001, 6.6000000000000005], + [10.9, 9.700000000000001], + [9.850000000000001, 9.700000000000001], + [9.9, 7.4], + [9, 7.4] + ], + "visible": true, + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_fidzsjcloh2lmuyl": { + "id": "slab_fidzsjcloh2lmuyl", + "name": "Room 6 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [11.200000000000001, 11.8], + [11.200000000000001, 12.3], + [9.65, 12.3], + [9.65, 11.8] + ], + "visible": true, + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_gglstknouxy9vdj1": { + "id": "slab_gglstknouxy9vdj1", + "name": "Room 3 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [14, 10.850000000000001], + [12.154832112622467, 10.850656330257777], + [12.150418963193307, 8.550035883746549], + [13.999889274484472, 8.549995191187701] + ], + "visible": true, + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_jqfjifekdfxz6q1b": { + "id": "slab_jqfjifekdfxz6q1b", + "name": "Room 2 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [12.154832112622467, 10.850656330257777], + [14, 10.850000000000001], + [14, 11.6], + [12.16, 11.600000000000001] + ], + "visible": true, + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_nx854sa7s5wi8htg": { + "id": "slab_nx854sa7s5wi8htg", + "name": "Room 9 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [11.150071258092904, 7.149998817453418], + [11.14999546723061, 10.349997336980962], + [10.850000998639025, 10.349999334231049], + [10.849999999999127, 7.149999704416012] + ], + "visible": true, + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "sseg_1mhb9w5vzhir58g6": { + "id": "sseg_1mhb9w5vzhir58g6", + "type": "stair-segment", + "width": 1, + "height": 0, + "length": 1, + "object": "node", + "visible": true, + "metadata": {}, + "parentId": "stair_aekaj43u90vkdzq3", + "position": [0, 0, 0], + "rotation": -8.881784197001252e-16, + "stepCount": 0, + "thickness": 0.32, + "fillToFloor": true, + "segmentType": "landing", + "attachmentSide": "front" + }, + "sseg_1wxi490hqvty6ysz": { + "id": "sseg_1wxi490hqvty6ysz", + "type": "stair-segment", + "width": 1, + "height": 0.5, + "length": 0.9, + "object": "node", + "visible": true, + "metadata": {}, + "parentId": "stair_aekaj43u90vkdzq3", + "position": [0, 0, 0], + "rotation": 1.5707963267948966, + "stepCount": 3, + "thickness": 0.25, + "fillToFloor": false, + "segmentType": "stair", + "attachmentSide": "left" + }, + "sseg_ok1uiyak000yjrcn": { + "id": "sseg_ok1uiyak000yjrcn", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "metadata": {}, + "parentId": "stair_aekaj43u90vkdzq3", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "wall_04kbr5brwhqoe9kp": { + "id": "wall_04kbr5brwhqoe9kp", + "end": [11.150052310400081, 7.949996448536031], + "name": "Wall 47", + "type": "wall", + "start": [12.149860390385824, 7.95003614374959], + "height": 3, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_wc258tpvshg0gjhs"], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "unknown" + }, + "wall_0oexl2u1nw9hndbg": { + "id": "wall_0oexl2u1nw9hndbg", + "end": [4.850000000000001, 11.5], + "name": "Wall 61", + "type": "wall", + "start": [4.85, 6.6000000000000005], + "height": 1, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_1eas7x8sro9zwzgp": { + "id": "wall_1eas7x8sro9zwzgp", + "end": [9.850000000000001, 7.4], + "name": "Wall 73", + "type": "wall", + "start": [9, 7.4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_2d7hi4uyqwqgjoy5": { + "id": "wall_2d7hi4uyqwqgjoy5", + "end": [9.849999999199898, 7.150000014401847], + "name": "Wall 54", + "type": "wall", + "start": [9.849995467237504, 10.350000035041878], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "unknown" + }, + "wall_2iabelzkagu40hxi": { + "id": "wall_2iabelzkagu40hxi", + "end": [11.100000000000001, 9.700000000000001], + "name": "Wall 76", + "type": "wall", + "start": [10.9, 9.700000000000001], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "unknown" + }, + "wall_4l8tivw5us5v4d8d": { + "id": "wall_4l8tivw5us5v4d8d", + "end": [9.600000906552417, 8.250000018401861], + "name": "Wall 22", + "type": "wall", + "start": [9.750000906552417, 8.250000026288353], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_4yxkzxu98e5k7kx6": { + "id": "wall_4yxkzxu98e5k7kx6", + "end": [12.154832112622467, 10.850656330257777], + "name": "Wall 39", + "type": "wall", + "start": [14, 10.850000000000001], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_4zskrr9pzbe5slvj": { + "id": "wall_4zskrr9pzbe5slvj", + "end": [12.150418963193307, 8.550035883746549], + "name": "Wall 11", + "type": "wall", + "start": [12.14865906764651, 9.600034408872972], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_600rnoyye6h1d7ag": { + "id": "wall_600rnoyye6h1d7ag", + "end": [9.850000000000001, 9.700000000000001], + "name": "Wall 72", + "type": "wall", + "start": [9.850000000000001, 11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_6hrri1wrkzzt5x0w": { + "id": "wall_6hrri1wrkzzt5x0w", + "end": [11.14999546723061, 10.349997336980962], + "name": "Wall 17", + "type": "wall", + "start": [11.149995467192301, 10.34999480153872], + "height": 3, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "unknown" + }, + "wall_6ll2kmyu076kol55": { + "id": "wall_6ll2kmyu076kol55", + "end": [8.75, 12.4], + "name": "Wall 34", + "type": "wall", + "start": [9.65, 12.4], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_6r8kl2ijb851sndy": { + "id": "wall_6r8kl2ijb851sndy", + "end": [14, 11.600000000000001], + "name": "Wall 2", + "type": "wall", + "start": [14, 14], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_6z1d05a2b78j7ink": { + "id": "wall_6z1d05a2b78j7ink", + "end": [13, 12.85], + "name": "Wall 4", + "type": "wall", + "start": [13, 14], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_76l9b1ip77hs596n": { + "id": "wall_76l9b1ip77hs596n", + "end": [8.8, 9.3], + "name": "Wall 76", + "type": "wall", + "start": [8.8, 9.700000000000001], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "unknown" + }, + "wall_7eamkn90sd375gtn": { + "id": "wall_7eamkn90sd375gtn", + "end": [12.151724334734052, 10.40002853643747], + "name": "Wall 9", + "type": "wall", + "start": [12.154832112622467, 10.850656330257777], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_8li5qzqog6dampr9": { + "id": "wall_8li5qzqog6dampr9", + "end": [14, 10.850000000000001], + "name": "Wall 37", + "type": "wall", + "start": [14, 11.600000000000001], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_8pf02ob17pb9fk5x": { + "id": "wall_8pf02ob17pb9fk5x", + "end": [9.850000000000001, 9.700000000000001], + "name": "Wall 78", + "type": "wall", + "start": [10.9, 9.700000000000001], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_abqiydefqw1r00na": { + "id": "wall_abqiydefqw1r00na", + "end": [9.850000000000001, 9.700000000000001], + "name": "Wall 71", + "type": "wall", + "start": [8.8, 9.700000000000001], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_be5smpfk6680mmua": { + "id": "wall_be5smpfk6680mmua", + "end": [9.750000906551431, 8.250000406924356], + "name": "Wall 21", + "type": "wall", + "start": [9.749995467238152, 10.349999776026882], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_c6k0qt2oe4fga9w5": { + "id": "wall_c6k0qt2oe4fga9w5", + "end": [11.4, 12.850000000000001], + "name": "Wall 5", + "type": "wall", + "start": [13, 12.85], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_c8e2pziezazm3238": { + "id": "wall_c8e2pziezazm3238", + "end": [10.849995467237258, 10.349999334267874], + "name": "Wall 18", + "type": "wall", + "start": [10.850000998639025, 10.349999334231049], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_ciycxeyf016nrhan": { + "id": "wall_ciycxeyf016nrhan", + "end": [9.850000000000001, 11.5], + "name": "Wall 62", + "type": "wall", + "start": [8.15, 11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_cn7fjrln3m91hrlw": { + "id": "wall_cn7fjrln3m91hrlw", + "end": [8.15, 11.5], + "name": "Wall 74", + "type": "wall", + "start": [8.15, 9.3], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_6ubqjrvl0dqiy0ly"], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "unknown" + }, + "wall_cy2mtjb6n4calmoe": { + "id": "wall_cy2mtjb6n4calmoe", + "end": [13.999889274484472, 8.549995191187701], + "name": "Wall 42", + "type": "wall", + "start": [12.150418963193307, 8.550035883746549], + "height": 3, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "unknown" + }, + "wall_czuz45hlu6v4ccu4": { + "id": "wall_czuz45hlu6v4ccu4", + "end": [11.150071258092904, 7.149998817453418], + "name": "Wall 45", + "type": "wall", + "start": [10.849999999999127, 7.149999704416012], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_d83s8ivbfc9oe1or": { + "id": "wall_d83s8ivbfc9oe1or", + "end": [11.4, 12.3], + "name": "Wall 6", + "type": "wall", + "start": [11.4, 12.850000000000001], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_e5yq1salxe6yejc0": { + "id": "wall_e5yq1salxe6yejc0", + "end": [8.15, 9.3], + "name": "Wall 77", + "type": "wall", + "start": [8.8, 9.3], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "unknown" + }, + "wall_fpmilgdmzj65f0uc": { + "id": "wall_fpmilgdmzj65f0uc", + "end": [12.16, 11.600000000000001], + "name": "Wall 3", + "type": "wall", + "start": [14, 11.6], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_537qkuq9kbjpkvj7"], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_fvf21a8bu4lia4p2": { + "id": "wall_fvf21a8bu4lia4p2", + "end": [9.850000000000001, 7.4], + "name": "Wall 74", + "type": "wall", + "start": [9.850000000000001, 9.700000000000001], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_gh6oxf3uycxrh303": { + "id": "wall_gh6oxf3uycxrh303", + "end": [5.75, 12.4], + "name": "Wall 32", + "type": "wall", + "start": [8.75, 12.4], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_grxgj4lsjrcvkk0h": { + "id": "wall_grxgj4lsjrcvkk0h", + "end": [9.65, 12.4], + "name": "Wall 33", + "type": "wall", + "start": [9.65, 12.3], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_gv41j5pxmgj5wwh9": { + "id": "wall_gv41j5pxmgj5wwh9", + "end": [11.150052310400081, 7.949996448536031], + "name": "Wall 17", + "type": "wall", + "start": [11.150071258092904, 7.149998817453418], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_h3skhchd5phtfs8b": { + "id": "wall_h3skhchd5phtfs8b", + "end": [11.149995467192301, 10.34999480153872], + "name": "Wall 17", + "type": "wall", + "start": [11.150052310400081, 7.949996448536031], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_h50026uwlcjay9ld": { + "id": "wall_h50026uwlcjay9ld", + "end": [13.999889274484472, 8.549995191187701], + "name": "Wall 41", + "type": "wall", + "start": [13.999860390136186, 7.950005752070608], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_hri91fwpe6aj18bg": { + "id": "wall_hri91fwpe6aj18bg", + "end": [11.200000000000001, 11.8], + "name": "Wall 8", + "type": "wall", + "start": [11.200000000000001, 12.3], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_i2k5o816l4197xlt": { + "id": "wall_i2k5o816l4197xlt", + "end": [10.950000000000001, 6.6000000000000005], + "name": "Wall 78", + "type": "wall", + "start": [10.9, 9.700000000000001], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_ijs2zfxdp6jdgaww": { + "id": "wall_ijs2zfxdp6jdgaww", + "end": [12.154832112622467, 10.850656330257777], + "name": "Wall 9", + "type": "wall", + "start": [12.16, 11.600000000000001], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_j59q59pfookl2n2p": { + "id": "wall_j59q59pfookl2n2p", + "end": [10.850000998639025, 10.349999334231049], + "name": "Wall 18", + "type": "wall", + "start": [11.14999546723061, 10.349997336980962], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_k704sdtck0c6q03m": { + "id": "wall_k704sdtck0c6q03m", + "end": [8.15, 9.3], + "name": "Wall 73", + "type": "wall", + "start": [8.15, 9.200000000000001], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "unknown" + }, + "wall_khrev0i0hubdh06a": { + "id": "wall_khrev0i0hubdh06a", + "end": [10.950000000000001, 6.6000000000000005], + "name": "Wall 59", + "type": "wall", + "start": [9.9, 6.6000000000000005], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_kmk414yk7km509i4": { + "id": "wall_kmk414yk7km509i4", + "end": [4.25, 6], + "name": "Wall 36", + "type": "wall", + "start": [4.25, 12.1], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_g3ffzdx5jbf17xu8", "window_9d36l690ph6y6z4m"], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_kn6pb5xk9msciy1e": { + "id": "wall_kn6pb5xk9msciy1e", + "end": [11.150071258092904, 7.149998817453418], + "name": "Wall 17", + "type": "wall", + "start": [11.150126917140366, 4.799997340542237], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_kntvq6gpqbyolk2h": { + "id": "wall_kntvq6gpqbyolk2h", + "end": [9.65, 12.3], + "name": "Wall 44", + "type": "wall", + "start": [11.200000000000001, 12.3], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_kp79sph70cd7kkpi": { + "id": "wall_kp79sph70cd7kkpi", + "end": [4.25, 6], + "name": "Wall 35", + "type": "wall", + "start": [5.05, 4.7], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_l0ls78r2xmxcauvv": { + "id": "wall_l0ls78r2xmxcauvv", + "end": [5.05, 4.7], + "name": "Wall 27", + "type": "wall", + "start": [10.75, 4.7], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_l6blx06ez8n3p60b": { + "id": "wall_l6blx06ez8n3p60b", + "end": [4.45, 12.4], + "name": "Wall 33", + "type": "wall", + "start": [5.75, 12.4], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_lmmg8ajn3znwdoqu": { + "id": "wall_lmmg8ajn3znwdoqu", + "end": [10.75, 7.15], + "name": "Wall 25", + "type": "wall", + "start": [9.850000001600208, 7.150000014401847], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_lw9oab3p7670erll": { + "id": "wall_lw9oab3p7670erll", + "end": [13, 14], + "name": "Wall 1", + "type": "wall", + "start": [14, 14], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_r5n7cv0l6o6fb4h5"], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_mkte3tx1ynknqnue": { + "id": "wall_mkte3tx1ynknqnue", + "end": [9.749995467237504, 10.35000002628131], + "name": "Wall 20", + "type": "wall", + "start": [9.849995467237504, 10.350000035041878], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_n0bf0li8li2drbkl": { + "id": "wall_n0bf0li8li2drbkl", + "end": [8.3, 9.200000000000001], + "name": "Wall 66", + "type": "wall", + "start": [8.3, 7.4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_n0mqnisazbpph1fn": { + "id": "wall_n0mqnisazbpph1fn", + "end": [4.85, 6.6000000000000005], + "name": "Wall 60", + "type": "wall", + "start": [9, 6.6000000000000005], + "height": 1, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_n5zq5i9kz2xccf34": { + "id": "wall_n5zq5i9kz2xccf34", + "end": [9.749995467238152, 10.349999776026882], + "name": "Wall 21", + "type": "wall", + "start": [9.749995467237504, 10.35000002628131], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_nobaxdqyh1npmk5a": { + "id": "wall_nobaxdqyh1npmk5a", + "end": [9.9, 6.6000000000000005], + "name": "Wall 58", + "type": "wall", + "start": [9, 6.6000000000000005], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_nucf86xy2hdhj97k": { + "id": "wall_nucf86xy2hdhj97k", + "end": [11.150126917140366, 4.799997340542237], + "name": "Wall 15", + "type": "wall", + "start": [14.000126917127918, 4.800005763346264], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_ohb6qaoz1kz2hbte": { + "id": "wall_ohb6qaoz1kz2hbte", + "end": [9.599999856860167, 7.150000018402363], + "name": "Wall 24", + "type": "wall", + "start": [9.600000906552417, 8.250000018401861], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_om4uk9kbpivyocco": { + "id": "wall_om4uk9kbpivyocco", + "end": [4.25, 12.1], + "name": "Wall 35", + "type": "wall", + "start": [4.45, 12.1], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_pepxayk6j16y72dw": { + "id": "wall_pepxayk6j16y72dw", + "end": [8.15, 9.200000000000001], + "name": "Wall 67", + "type": "wall", + "start": [8.3, 9.200000000000001], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_qfszpe9z8o4kbe7s": { + "id": "wall_qfszpe9z8o4kbe7s", + "end": [12.149860390385824, 7.95003614374959], + "name": "Wall 12", + "type": "wall", + "start": [12.150418963193307, 8.550035883746549], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_sdi8ol7dl59wlwgp": { + "id": "wall_sdi8ol7dl59wlwgp", + "end": [13.999860390136186, 7.950005752070608], + "name": "Wall 13", + "type": "wall", + "start": [12.149860390385824, 7.95003614374959], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_shbz9ypyynjqko57": { + "id": "wall_shbz9ypyynjqko57", + "end": [9, 6.6000000000000005], + "name": "Wall 57", + "type": "wall", + "start": [9, 7.4], + "height": 0.1, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_souzmz6s6huekzlh": { + "id": "wall_souzmz6s6huekzlh", + "end": [10.849999999999127, 7.149999704416012], + "name": "Wall 45", + "type": "wall", + "start": [10.75, 7.15], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_t2ulzn6ldxltng2l": { + "id": "wall_t2ulzn6ldxltng2l", + "end": [11.200000000000001, 12.3], + "name": "Wall 7", + "type": "wall", + "start": [11.4, 12.3], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_tojbdfss16gqbfac": { + "id": "wall_tojbdfss16gqbfac", + "end": [10.75, 4.7], + "name": "Wall 26", + "type": "wall", + "start": [10.75, 7.15], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_twbt3tis0g6a58ei": { + "id": "wall_twbt3tis0g6a58ei", + "end": [9.65, 12.3], + "name": "Wall 33", + "type": "wall", + "start": [9.65, 11.8], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_u2n22r52i8oxpzul": { + "id": "wall_u2n22r52i8oxpzul", + "end": [8.15, 11.5], + "name": "Wall 62", + "type": "wall", + "start": [4.850000000000001, 11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "exterior" + }, + "wall_ub12fx0dveq6jtju": { + "id": "wall_ub12fx0dveq6jtju", + "end": [9.849999999199898, 7.150000014401847], + "name": "Wall 25", + "type": "wall", + "start": [9.599999856860167, 7.150000018402363], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_up58hw5bsioyoqbx": { + "id": "wall_up58hw5bsioyoqbx", + "end": [14, 11.6], + "name": "Wall 2", + "type": "wall", + "start": [14, 11.600000000000001], + "height": 3, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "unknown" + }, + "wall_v13izaodb887sfag": { + "id": "wall_v13izaodb887sfag", + "end": [14.000126917127918, 4.800005763346264], + "name": "Wall 14", + "type": "wall", + "start": [13.999860390136186, 7.950005752070608], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_vfjotnrl39diz2rc": { + "id": "wall_vfjotnrl39diz2rc", + "end": [8.3, 7.4], + "name": "Wall 56", + "type": "wall", + "start": [9, 7.4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "interior" + }, + "wall_vlmfb7v7i0p98omi": { + "id": "wall_vlmfb7v7i0p98omi", + "end": [14, 10.850000000000001], + "name": "Wall 41", + "type": "wall", + "start": [13.999889274484472, 8.549995191187701], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_vsvtig4yhaedu8h0": { + "id": "wall_vsvtig4yhaedu8h0", + "end": [9.750000906552417, 8.250000026288353], + "name": "Wall 21", + "type": "wall", + "start": [9.750000906551431, 8.250000406924356], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_yalj7mu240c41lnk": { + "id": "wall_yalj7mu240c41lnk", + "end": [9.9, 7.4], + "name": "Wall 73", + "type": "wall", + "start": [9.850000000000001, 7.4], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "frontSide": "unknown" + }, + "wall_yi576ij8anlbxtqk": { + "id": "wall_yi576ij8anlbxtqk", + "end": [10.849999999999127, 7.149999704416012], + "name": "Wall 49", + "type": "wall", + "start": [10.850000998639025, 10.349999334231049], + "height": 3, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "unknown" + }, + "wall_z35z1vw6twjhez3d": { + "id": "wall_z35z1vw6twjhez3d", + "end": [4.45, 12.1], + "name": "Wall 34", + "type": "wall", + "start": [4.45, 12.4], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_zbay14bi2g5dxhvq": { + "id": "wall_zbay14bi2g5dxhvq", + "end": [9.850000001600208, 7.150000014401847], + "name": "Wall 25", + "type": "wall", + "start": [9.849999999199898, 7.150000014401847], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "wall_zejsv7so71uy6v6j": { + "id": "wall_zejsv7so71uy6v6j", + "end": [12.14865906764651, 9.600034408872972], + "name": "Wall 10", + "type": "wall", + "start": [12.151724334734052, 10.40002853643747], + "height": 3, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_huvn8g5xhl25arvj"], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "interior" + }, + "wall_zh59q60sbqnvbc2u": { + "id": "wall_zh59q60sbqnvbc2u", + "end": [9.65, 11.8], + "name": "Wall 32", + "type": "wall", + "start": [11.200000000000001, 11.8], + "height": 3, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "frontSide": "exterior" + }, + "level_i9jregd6u2ha794o": { + "id": "level_i9jregd6u2ha794o", + "type": "level", + "level": 1, + "object": "node", + "visible": true, + "children": [ + "wall_vfjotnrl39diz2rc", + "wall_shbz9ypyynjqko57", + "wall_nobaxdqyh1npmk5a", + "wall_khrev0i0hubdh06a", + "wall_n0mqnisazbpph1fn", + "wall_0oexl2u1nw9hndbg", + "wall_n0bf0li8li2drbkl", + "wall_pepxayk6j16y72dw", + "wall_600rnoyye6h1d7ag", + "wall_1eas7x8sro9zwzgp", + "wall_yalj7mu240c41lnk", + "wall_fvf21a8bu4lia4p2", + "slab_espwew9tbh3cuz2v", + "wall_abqiydefqw1r00na", + "wall_2iabelzkagu40hxi", + "wall_i2k5o816l4197xlt", + "wall_8pf02ob17pb9fk5x", + "ceiling_tcsr2y9dvily9elw", + "wall_u2n22r52i8oxpzul", + "wall_ciycxeyf016nrhan", + "wall_cn7fjrln3m91hrlw", + "slab_42o2bxthq8wk6i9j", + "ceiling_l4xja6gbpcbhytep", + "wall_76l9b1ip77hs596n", + "wall_k704sdtck0c6q03m", + "slab_0h665xzly6z7ibd7", + "ceiling_9rvasdx4y6smymcg", + "wall_e5yq1salxe6yejc0", + "slab_1qxilit9sqhlr5k3", + "ceiling_k9dxyrb2iu66c4rm" + ], + "metadata": {}, + "parentId": "building_cufg85qnzt1dpy3r" + }, + "level_s77ej91id9kylvae": { + "id": "level_s77ej91id9kylvae", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_lw9oab3p7670erll", + "wall_fpmilgdmzj65f0uc", + "wall_6z1d05a2b78j7ink", + "wall_c6k0qt2oe4fga9w5", + "wall_d83s8ivbfc9oe1or", + "wall_t2ulzn6ldxltng2l", + "wall_hri91fwpe6aj18bg", + "wall_zejsv7so71uy6v6j", + "wall_4zskrr9pzbe5slvj", + "wall_qfszpe9z8o4kbe7s", + "wall_sdi8ol7dl59wlwgp", + "wall_v13izaodb887sfag", + "wall_nucf86xy2hdhj97k", + "wall_6hrri1wrkzzt5x0w", + "wall_mkte3tx1ynknqnue", + "wall_4l8tivw5us5v4d8d", + "wall_vsvtig4yhaedu8h0", + "wall_ohb6qaoz1kz2hbte", + "wall_tojbdfss16gqbfac", + "wall_l0ls78r2xmxcauvv", + "wall_kp79sph70cd7kkpi", + "wall_zh59q60sbqnvbc2u", + "wall_6ll2kmyu076kol55", + "wall_gh6oxf3uycxrh303", + "wall_l6blx06ez8n3p60b", + "wall_z35z1vw6twjhez3d", + "wall_om4uk9kbpivyocco", + "wall_kmk414yk7km509i4", + "wall_6r8kl2ijb851sndy", + "wall_up58hw5bsioyoqbx", + "wall_8li5qzqog6dampr9", + "wall_ijs2zfxdp6jdgaww", + "wall_7eamkn90sd375gtn", + "wall_4yxkzxu98e5k7kx6", + "slab_jqfjifekdfxz6q1b", + "ceiling_xhib130ctg9594ay", + "slab_gglstknouxy9vdj1", + "ceiling_czvvqlkr38o2lula", + "wall_h50026uwlcjay9ld", + "wall_vlmfb7v7i0p98omi", + "wall_cy2mtjb6n4calmoe", + "slab_ctzn70siekeblrsh", + "ceiling_n9wqs8ejktg8ujkp", + "wall_twbt3tis0g6a58ei", + "wall_grxgj4lsjrcvkk0h", + "wall_kntvq6gpqbyolk2h", + "slab_fidzsjcloh2lmuyl", + "ceiling_4nxj67wzax2y8987", + "wall_kn6pb5xk9msciy1e", + "slab_b99b0vdon5mfo2gv", + "ceiling_b1q4lga1qt3dt20z", + "wall_gv41j5pxmgj5wwh9", + "wall_h3skhchd5phtfs8b", + "wall_04kbr5brwhqoe9kp", + "slab_7u5zmy6mvy5edxpv", + "ceiling_8qatbubze7bjiw8c", + "wall_souzmz6s6huekzlh", + "wall_czuz45hlu6v4ccu4", + "wall_j59q59pfookl2n2p", + "wall_c8e2pziezazm3238", + "wall_yi576ij8anlbxtqk", + "slab_nx854sa7s5wi8htg", + "ceiling_bi8ididdu22dbif5", + "wall_lmmg8ajn3znwdoqu", + "wall_n5zq5i9kz2xccf34", + "wall_be5smpfk6680mmua", + "wall_ub12fx0dveq6jtju", + "wall_zbay14bi2g5dxhvq", + "wall_2d7hi4uyqwqgjoy5", + "stair_aekaj43u90vkdzq3" + ], + "metadata": {}, + "parentId": null + }, + "stair_aekaj43u90vkdzq3": { + "id": "stair_aekaj43u90vkdzq3", + "name": "Staircase 1", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": [ + "sseg_ok1uiyak000yjrcn", + "sseg_1mhb9w5vzhir58g6", + "sseg_1wxi490hqvty6ysz" + ], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "position": [10.4, 0, 10.4], + "rotation": 3.141592653589793, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_i9jregd6u2ha794o", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_s77ej91id9kylvae", + "innerRadius": 0.9, + "railingMode": "none", + "openingOffset": 0.08, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "window_9d36l690ph6y6z4m": { + "id": "window_9d36l690ph6y6z4m", + "name": "Window 2", + "side": "front", + "sill": true, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_kmk414yk7km509i4", + "visible": true, + "metadata": {}, + "parentId": "wall_kmk414yk7km509i4", + "position": [4.15, 1.25, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "window_g3ffzdx5jbf17xu8": { + "id": "window_g3ffzdx5jbf17xu8", + "name": "Window 1", + "side": "front", + "sill": true, + "type": "window", + "width": 1.5, + "height": 1.5, + "object": "node", + "wallId": "wall_kmk414yk7km509i4", + "visible": true, + "metadata": {}, + "parentId": "wall_kmk414yk7km509i4", + "position": [1.3, 1.2000000000000002, 0], + "rotation": [0, 0, 0], + "rowRatios": [1], + "sillDepth": 0.08, + "frameDepth": 0.07, + "columnRatios": [1], + "sillThickness": 0.03, + "frameThickness": 0.05, + "rowDividerThickness": 0.03, + "columnDividerThickness": 0.03 + }, + "ceiling_4nxj67wzax2y8987": { + "id": "ceiling_4nxj67wzax2y8987", + "name": "Room 6 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [11.200000000000001, 11.8], + [11.200000000000001, 12.3], + [9.65, 12.3], + [9.65, 11.8] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_8qatbubze7bjiw8c": { + "id": "ceiling_8qatbubze7bjiw8c", + "name": "Room 8 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [11.150052310400081, 7.949996448536031], + [11.150126917140366, 4.799997340542237], + [14.000126917127918, 4.800005763346264], + [13.999860390136186, 7.950005752070608] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_9rvasdx4y6smymcg": { + "id": "ceiling_9rvasdx4y6smymcg", + "name": "Room 8 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [9.850000000000001, 9.700000000000001], + [8.8, 9.700000000000001], + [8.8, 9.3], + [8.15, 9.3], + [8.15, 9.200000000000001], + [8.3, 9.200000000000001], + [8.3, 7.4], + [9.850000000000001, 7.4] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_b1q4lga1qt3dt20z": { + "id": "ceiling_b1q4lga1qt3dt20z", + "name": "Room 7 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [14, 14], + [13, 14], + [13, 12.85], + [11.4, 12.850000000000001], + [11.4, 12.3], + [11.200000000000001, 12.3], + [11.200000000000001, 11.8], + [9.65, 11.8], + [9.65, 12.4], + [4.45, 12.4], + [4.45, 12.1], + [4.25, 12.1], + [4.25, 6], + [5.05, 4.7], + [10.75, 4.7], + [10.75, 7.15], + [9.599999856860167, 7.150000018402363], + [9.600000906552417, 8.250000018401861], + [9.750000906551431, 8.250000406924356], + [9.749995467237504, 10.35000002628131], + [9.849995467237504, 10.350000035041878], + [9.850000001600208, 7.150000014401847], + [10.849999999999127, 7.149999704416012], + [10.850000998639025, 10.349999334231049], + [11.149995467192301, 10.34999480153872], + [11.150052310400081, 7.949996448536031], + [12.149860390385824, 7.95003614374959], + [12.16, 11.600000000000001], + [14, 11.600000000000001] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_bi8ididdu22dbif5": { + "id": "ceiling_bi8ididdu22dbif5", + "name": "Room 9 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [11.150071258092904, 7.149998817453418], + [11.14999546723061, 10.349997336980962], + [10.850000998639025, 10.349999334231049], + [10.849999999999127, 7.149999704416012] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_czvvqlkr38o2lula": { + "id": "ceiling_czvvqlkr38o2lula", + "name": "Room 3 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [14, 10.850000000000001], + [12.154832112622467, 10.850656330257777], + [12.150418963193307, 8.550035883746549], + [13.999889274484472, 8.549995191187701] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_k9dxyrb2iu66c4rm": { + "id": "ceiling_k9dxyrb2iu66c4rm", + "name": "Room 9 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [9.850000000000001, 11.5], + [8.15, 11.5], + [8.15, 9.3], + [8.8, 9.3], + [8.8, 9.700000000000001], + [9.850000000000001, 9.700000000000001] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_l4xja6gbpcbhytep": { + "id": "ceiling_l4xja6gbpcbhytep", + "name": "Room 7 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [4.850000000000001, 11.5], + [4.85, 6.6000000000000005], + [9, 6.6000000000000005], + [9, 7.4], + [8.3, 7.4], + [8.3, 9.200000000000001], + [8.15, 9.200000000000001], + [8.15, 11.5] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_n9wqs8ejktg8ujkp": { + "id": "ceiling_n9wqs8ejktg8ujkp", + "name": "Room 4 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [13.999889274484472, 8.549995191187701], + [12.150418963193307, 8.550035883746549], + [12.149860390385824, 7.95003614374959], + [13.999860390136186, 7.950005752070608] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_tcsr2y9dvily9elw": { + "id": "ceiling_tcsr2y9dvily9elw", + "name": "Room 5 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [9, 6.6000000000000005], + [10.950000000000001, 6.6000000000000005], + [10.9, 9.700000000000001], + [9.850000000000001, 9.700000000000001], + [9.9, 7.4], + [9, 7.4] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_i9jregd6u2ha794o", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_xhib130ctg9594ay": { + "id": "ceiling_xhib130ctg9594ay", + "name": "Room 2 Ceiling", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [12.154832112622467, 10.850656330257777], + [14, 10.850000000000001], + [14, 11.6], + [12.16, 11.600000000000001] + ], + "visible": true, + "children": [], + "metadata": {}, + "parentId": "level_s77ej91id9kylvae", + "holeMetadata": [], + "autoFromWalls": true + }, + "building_cufg85qnzt1dpy3r": { + "id": "building_cufg85qnzt1dpy3r", + "type": "building", + "object": "node", + "visible": true, + "children": ["level_s77ej91id9kylvae", "level_i9jregd6u2ha794o"], + "metadata": {}, + "parentId": null, + "position": [0, 0, 0], + "rotation": [0, 0, 0] + } + }, + "areas": [ + { + "levelId": "level_i9jregd6u2ha794o", + "beforeVisible": 25.674980354843715, + "afterVisible": 22.107599999999966 + } + ], + "gaps": [ + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_1eas7x8sro9zwzgp", + "status": "gap", + "supportedFaces": ["a", "b"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.1334166406412635, + "gapSizeBucket": "5–20 cm", + "faces": [ + { + "face": "a", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + }, + { + "face": "b", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_8pf02ob17pb9fk5x", + "status": "gap", + "supportedFaces": ["a"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.09999999999999964, + "gapSizeBucket": "5–20 cm", + "faces": [ + { + "face": "a", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_fvf21a8bu4lia4p2", + "status": "gap", + "supportedFaces": ["a", "b"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.08544003745317712, + "gapSizeBucket": "5–20 cm", + "faces": [ + { + "face": "a", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + }, + { + "face": "b", + "exposure": "interior", + "extent": "corner", + "uncoveredSamples": [8] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_i2k5o816l4197xlt", + "status": "gap", + "supportedFaces": ["b"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.0999870468527178, + "gapSizeBucket": "5–20 cm", + "faces": [ + { + "face": "b", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_khrev0i0hubdh06a", + "status": "gap", + "supportedFaces": ["a"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.10000000000000142, + "gapSizeBucket": "5–20 cm", + "faces": [ + { + "face": "a", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_n0mqnisazbpph1fn", + "status": "gap", + "supportedFaces": ["b"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.029999999999997584, + "gapSizeBucket": "2–5 cm", + "faces": [ + { + "face": "b", + "exposure": "interior", + "extent": "corner", + "uncoveredSamples": [0] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_nobaxdqyh1npmk5a", + "status": "gap", + "supportedFaces": ["a"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.10000000000000142, + "gapSizeBucket": "5–20 cm", + "faces": [ + { + "face": "a", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_shbz9ypyynjqko57", + "status": "gap", + "supportedFaces": ["a", "b"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.13000000000000078, + "gapSizeBucket": "5–20 cm", + "faces": [ + { + "face": "a", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + }, + { + "face": "b", + "exposure": "exterior", + "extent": "edge", + "uncoveredSamples": [0, 1, 2, 3, 4, 5, 6, 7, 8] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + }, + { + "levelId": "level_i9jregd6u2ha794o", + "wallId": "wall_vfjotnrl39diz2rc", + "status": "gap", + "supportedFaces": ["a", "b"], + "plateIds": ["slab_0000kt1bi7hs5a77"], + "maxUncoveredDistance": 0.03000000000000025, + "gapSizeBucket": "2–5 cm", + "faces": [ + { + "face": "a", + "exposure": "interior", + "extent": "corner", + "uncoveredSamples": [0] + }, + { + "face": "b", + "exposure": "interior", + "extent": "corner", + "uncoveredSamples": [0] + } + ], + "legacyHoleSamples": [], + "sampleStations": [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] + } + ] +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-04.json b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-04.json new file mode 100644 index 0000000000..05612183ae --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-04.json @@ -0,0 +1,1925 @@ +{ + "sceneId": "scene-04", + "levelId": "level_stlelmley1l34sa3", + "rootNodeIds": ["level_stlelmley1l34sa3"], + "nodes": { + "slab_4ayxwcccspdn2om1": { + "id": "slab_4ayxwcccspdn2om1", + "type": "slab", + "object": "node", + "polygon": [ + [14, 17], + [14, -11], + [17, -11], + [17, -13.5], + [31.5, -13.5], + [31.5, 17], + [32, 17] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05 + }, + "slab_5fy9c24rhwaumj4a": { + "id": "slab_5fy9c24rhwaumj4a", + "type": "slab", + "object": "node", + "polygon": [ + [-26.5, -16], + [-26.5, -25], + [-54, -25], + [-54, 2], + [-27.5, 2], + [-27.5, -4], + [-43.5, -4], + [-43.5, -16] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.02 + }, + "slab_5hsaa9zuz876s97b": { + "id": "slab_5hsaa9zuz876s97b", + "type": "slab", + "object": "node", + "polygon": [ + [-35.5, -14.5], + [-34, -16], + [-43.5, -16], + [-43.5, -13], + [-35.5, -13], + [-35.5, -13] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05 + }, + "slab_6kljkihx1fl8fczc": { + "id": "slab_6kljkihx1fl8fczc", + "type": "slab", + "object": "node", + "polygon": [[16, -4], [16, -9], [17, -9], [17, -4], [17.5, -4]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.15 + }, + "slab_a4l2atfuq2oq8iqc": { + "id": "slab_a4l2atfuq2oq8iqc", + "type": "slab", + "object": "node", + "polygon": [ + [-5.5, -11], + [-5.5, -13], + [-5, -13], + [-5, -13.5], + [16, -13.5], + [16, -11], + [16, -11] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05 + }, + "slab_abmcx8ded3a5nkkh": { + "id": "slab_abmcx8ded3a5nkkh", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-5, -16], + [-5, -13], + [-7.5, -13], + [-7.5, -11.5], + [-35.5, -11.5], + [-35.5, -14.5], + [-34, -16] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_bnta4or3eqh2xplm": { + "id": "slab_bnta4or3eqh2xplm", + "type": "slab", + "object": "node", + "polygon": [ + [-5, -16], + [-5, -13], + [-5.5, -13], + [-5.5, -4], + [-43.5, -4], + [-43.5, -13], + [-35.5, -13], + [-35.5, -14.5], + [-34, -16] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05 + }, + "slab_f9ggedzfr5o3t149": { + "id": "slab_f9ggedzfr5o3t149", + "type": "slab", + "object": "node", + "polygon": [[-5.5, -11], [14, -11], [14, 17], [-5.5, 17]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.1 + }, + "slab_ngfjur4pgtze9obe": { + "id": "slab_ngfjur4pgtze9obe", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-37.5, 1], [-37.5, -2], [-34.5, -2], [-34.5, 1]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_phiaz2oon3pbersd": { + "id": "slab_phiaz2oon3pbersd", + "type": "slab", + "object": "node", + "polygon": [ + [17, -3.5], + [17, -9.5], + [20.5, -9.5], + [20.5, -3.5], + [20.5, -3.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.4 + }, + "slab_qq16dvomnxldijly": { + "id": "slab_qq16dvomnxldijly", + "type": "slab", + "object": "node", + "polygon": [[17, -13.5], [17, -23], [-5, -23], [-5, -13.5], [-5, -13.5]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.02 + }, + "slab_sy7spjy224lcizow": { + "id": "slab_sy7spjy224lcizow", + "type": "slab", + "object": "node", + "polygon": [ + [-21.5, 17], + [-21.5, 32], + [-17, 32], + [-17, 27], + [-5.5, 27], + [-2, 23.5], + [10, 23.5], + [11, 22.5], + [13.5, 22.5], + [13.5, 28], + [24.5, 28], + [24.5, 23], + [31.5, 23], + [31.5, 17], + [31.5, 17] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.02 + }, + "slab_tkzjta7h17uxm37y": { + "id": "slab_tkzjta7h17uxm37y", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-31, -2], [-31, 1], [-33.5, 1], [-33.5, -2]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_wrmpydclyqul2spi": { + "id": "slab_wrmpydclyqul2spi", + "type": "slab", + "object": "node", + "polygon": [ + [-5.5, 17], + [-21.5, 17], + [-21.5, 1], + [-27.5, 1], + [-27.5, -4], + [-5.5, -4], + [-5.5, -4] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05 + }, + "slab_xfxova3w95a5ibga": { + "id": "slab_xfxova3w95a5ibga", + "type": "slab", + "object": "node", + "polygon": [[16, -13.5], [17, -13.5], [17, -11], [16, -11], [16, -11]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.05 + }, + "slab_z4arxxumfwf49pjh": { + "id": "slab_z4arxxumfwf49pjh", + "type": "slab", + "object": "node", + "polygon": [ + [-17, 32], + [-17, 27], + [-5.5, 27], + [-2, 23.5], + [10, 23.5], + [11, 22.5], + [13.5, 22.5], + [13.5, 28], + [24, 28], + [24, 23], + [31.5, 23], + [31.5, 32], + [30, 32] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "elevation": 0.2 + }, + "wall_0aj6wic7qio2izo6": { + "id": "wall_0aj6wic7qio2izo6", + "end": [3.5, 10.5], + "type": "wall", + "start": [-5.5, 10.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_0isztqpjued64sfa": { + "id": "wall_0isztqpjued64sfa", + "end": [-38.5, -13], + "type": "wall", + "start": [-38.5, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_0kvzfdiwgy4cnacw": { + "id": "wall_0kvzfdiwgy4cnacw", + "end": [11, 15.5], + "type": "wall", + "start": [10, 15.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_0nzvz9px5dar8z0l": { + "id": "wall_0nzvz9px5dar8z0l", + "end": [14, 8], + "type": "wall", + "start": [5, 8], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_0s2pcd4cgvowhu3v": { + "id": "wall_0s2pcd4cgvowhu3v", + "end": [-38.5, -9.5], + "type": "wall", + "start": [-37.5, -9.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_15949dfouwj8qpsc": { + "id": "wall_15949dfouwj8qpsc", + "end": [14, 17], + "type": "wall", + "start": [-5.5, 17], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_1hbtnvgrxy7f6poe": { + "id": "wall_1hbtnvgrxy7f6poe", + "end": [1, 9], + "type": "wall", + "start": [1, 10.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_1ze5jq3fefffjw52": { + "id": "wall_1ze5jq3fefffjw52", + "end": [7.5, 6], + "type": "wall", + "start": [7.5, 8], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_2u1njfwqugli3tid": { + "id": "wall_2u1njfwqugli3tid", + "end": [-29, -7.5], + "type": "wall", + "start": [-27.5, -7.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_36dy9x3sqoy6wgg4": { + "id": "wall_36dy9x3sqoy6wgg4", + "end": [-5, -16], + "type": "wall", + "start": [-5, -13], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_3mg06sehmdoqnyjv": { + "id": "wall_3mg06sehmdoqnyjv", + "end": [-20, -9.5], + "type": "wall", + "start": [-20, -4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_3n77gwhl9s8tmvxo": { + "id": "wall_3n77gwhl9s8tmvxo", + "end": [14, -5], + "type": "wall", + "start": [11, -5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_43f64trfdbf6a310": { + "id": "wall_43f64trfdbf6a310", + "end": [-29.5, -19.5], + "type": "wall", + "start": [-27, -19.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_4f9e66w9suetb950": { + "id": "wall_4f9e66w9suetb950", + "end": [-37.5, -6], + "type": "wall", + "start": [-39.5, -6], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_4ip1giowtafnh058": { + "id": "wall_4ip1giowtafnh058", + "end": [-7.5, -13], + "type": "wall", + "start": [-7.5, -11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_52tqioykvtf8odjm": { + "id": "wall_52tqioykvtf8odjm", + "end": [-33, -16], + "type": "wall", + "start": [-5, -16], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_536z30eic22fqgqc": { + "id": "wall_536z30eic22fqgqc", + "end": [1.5, -3.5], + "type": "wall", + "start": [1.5, -1.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_5ada6bnjsopj7mcv": { + "id": "wall_5ada6bnjsopj7mcv", + "end": [-39.5, -9.5], + "type": "wall", + "start": [-39.5, -6], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_5mo4hmjez28klk9f": { + "id": "wall_5mo4hmjez28klk9f", + "end": [14, -11], + "type": "wall", + "start": [-5.5, -11], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_63ajr53v7ywxmd7g": { + "id": "wall_63ajr53v7ywxmd7g", + "end": [-17.5, -6], + "type": "wall", + "start": [-20, -6], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_6d992n60jpziiblz": { + "id": "wall_6d992n60jpziiblz", + "end": [-31, -2], + "type": "wall", + "start": [-31, 1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_6j4eo4lls3q11ljn": { + "id": "wall_6j4eo4lls3q11ljn", + "end": [-29.5, -22.5], + "type": "wall", + "start": [-27, -22.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_6lxpax19l50n5h9t": { + "id": "wall_6lxpax19l50n5h9t", + "end": [-26, -12.5], + "type": "wall", + "start": [-28.5, -12.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_6veh8ry5dbj2fiey": { + "id": "wall_6veh8ry5dbj2fiey", + "end": [9, -1], + "type": "wall", + "start": [5, -1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_6vp77787saf6um2t": { + "id": "wall_6vp77787saf6um2t", + "end": [-5, -14], + "type": "wall", + "start": [-7, -14], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_71divlgstgb9mpvc": { + "id": "wall_71divlgstgb9mpvc", + "end": [3.5, 9], + "type": "wall", + "start": [-5.5, 9], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_793bsazcqyfsvz9c": { + "id": "wall_793bsazcqyfsvz9c", + "end": [-3, -3.5], + "type": "wall", + "start": [-3, -1.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_8andzf9w44m5rkhx": { + "id": "wall_8andzf9w44m5rkhx", + "end": [-35.5, -14.5], + "type": "wall", + "start": [-35.5, -13], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_8rloffkfsu5t91zm": { + "id": "wall_8rloffkfsu5t91zm", + "end": [-27, -19.5], + "type": "wall", + "start": [-27, -22.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_9vf0kbq25dzshewk": { + "id": "wall_9vf0kbq25dzshewk", + "end": [-17.5, -9.5], + "type": "wall", + "start": [-17.5, -4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_as5w6vi16699chpx": { + "id": "wall_as5w6vi16699chpx", + "end": [-3, 9], + "type": "wall", + "start": [-3, 10.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_asootvz55p1q038b": { + "id": "wall_asootvz55p1q038b", + "end": [5, -3.5], + "type": "wall", + "start": [5, -1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_bjg67mcipb7kg4di": { + "id": "wall_bjg67mcipb7kg4di", + "end": [-28.5, -14.5], + "type": "wall", + "start": [-26, -14.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_blj1enmtun5ipbug": { + "id": "wall_blj1enmtun5ipbug", + "end": [-16.5, -13], + "type": "wall", + "start": [-16.5, -11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_c6az6y1r54z2drtn": { + "id": "wall_c6az6y1r54z2drtn", + "end": [-37.5, -9.5], + "type": "wall", + "start": [-37.5, -6], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_c956y17nxbly3x5f": { + "id": "wall_c956y17nxbly3x5f", + "end": [-7.5, -6], + "type": "wall", + "start": [-5.5, -6], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_de36jozhode1q6v7": { + "id": "wall_de36jozhode1q6v7", + "end": [-5, -13], + "type": "wall", + "start": [-5.5, -13], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_dfsxus2f85opn40n": { + "id": "wall_dfsxus2f85opn40n", + "end": [-37.5, -2], + "type": "wall", + "start": [-37.5, 1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_e3deyjy3xkrju0gc": { + "id": "wall_e3deyjy3xkrju0gc", + "end": [14, 6], + "type": "wall", + "start": [5, 6], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_exwjt85vc7j0s9ww": { + "id": "wall_exwjt85vc7j0s9ww", + "end": [-41, -8.5], + "type": "wall", + "start": [-41, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_f7rgk2xj964j29p4": { + "id": "wall_f7rgk2xj964j29p4", + "end": [-16.5, -14.5], + "type": "wall", + "start": [-16.5, -16], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_fx5nfcudovy7heif": { + "id": "wall_fx5nfcudovy7heif", + "end": [-37.5, 1], + "type": "wall", + "start": [-34.5, 1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_g5tbuam7nfha9lo8": { + "id": "wall_g5tbuam7nfha9lo8", + "end": [10.5, -3.5], + "type": "wall", + "start": [10.5, 0.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_gs14pl04cx36pva7": { + "id": "wall_gs14pl04cx36pva7", + "end": [14, 0.5], + "type": "wall", + "start": [5, 0.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_h34zsooyggh7sqbp": { + "id": "wall_h34zsooyggh7sqbp", + "end": [-43.5, -13], + "type": "wall", + "start": [-35.5, -13], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_h3v6rziamua2p22o": { + "id": "wall_h3v6rziamua2p22o", + "end": [-7.5, -8.5], + "type": "wall", + "start": [-5.5, -8.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_hfruuqr173j480ek": { + "id": "wall_hfruuqr173j480ek", + "end": [-27.5, -9.5], + "type": "wall", + "start": [-27.5, -4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_hziwxf7z9ezmz1js": { + "id": "wall_hziwxf7z9ezmz1js", + "end": [-33.5, 1], + "type": "wall", + "start": [-31, 1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_iut41ui0tqarloab": { + "id": "wall_iut41ui0tqarloab", + "end": [3.5, -3.5], + "type": "wall", + "start": [3.5, 17], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_iz7is9455wjpnc2l": { + "id": "wall_iz7is9455wjpnc2l", + "end": [-5, -13], + "type": "wall", + "start": [-7.5, -13], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_jlnc9j00z8kzgux3": { + "id": "wall_jlnc9j00z8kzgux3", + "end": [-6.5, -14], + "type": "wall", + "start": [-6.5, -13.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_k087pyy898llp3js": { + "id": "wall_k087pyy898llp3js", + "end": [-7.5, -11.5], + "type": "wall", + "start": [-35.5, -11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_l3gxn37y3q4pi5ax": { + "id": "wall_l3gxn37y3q4pi5ax", + "end": [3.5, 3.5], + "type": "wall", + "start": [-5.5, 3.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_l8vxzycrphhwah48": { + "id": "wall_l8vxzycrphhwah48", + "end": [-34.5, -2], + "type": "wall", + "start": [-37.5, -2], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_l90984dthq0mmyzl": { + "id": "wall_l90984dthq0mmyzl", + "end": [-43.5, -8.5], + "type": "wall", + "start": [-41, -8.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_lb7olr6dgnlvaqgo": { + "id": "wall_lb7olr6dgnlvaqgo", + "end": [6.5, 17], + "type": "wall", + "start": [6.5, 14], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_lifk2135hrgc9kp0": { + "id": "wall_lifk2135hrgc9kp0", + "end": [-33, -16], + "type": "wall", + "start": [-34, -16], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_lpz601bzwwp5mi0i": { + "id": "wall_lpz601bzwwp5mi0i", + "end": [-7, -16], + "type": "wall", + "start": [-7, -14], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_ly1s30afyln6hg6q": { + "id": "wall_ly1s30afyln6hg6q", + "end": [-5.5, -13], + "type": "wall", + "start": [-5.5, -11], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_m3csql2jg7ux6ord": { + "id": "wall_m3csql2jg7ux6ord", + "end": [11, 14], + "type": "wall", + "start": [11, 15.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_mee37i6fzcdnuzt9": { + "id": "wall_mee37i6fzcdnuzt9", + "end": [9.5, 6], + "type": "wall", + "start": [9.5, 8], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_mkmkcx6l4h3dr5ip": { + "id": "wall_mkmkcx6l4h3dr5ip", + "end": [-17.5, -7.5], + "type": "wall", + "start": [-20, -7.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_n88dnm2ks9pwhmuc": { + "id": "wall_n88dnm2ks9pwhmuc", + "end": [-28.5, -11.5], + "type": "wall", + "start": [-28.5, -16], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_nhv0ynccf6opvq3v": { + "id": "wall_nhv0ynccf6opvq3v", + "end": [-7.5, -9.5], + "type": "wall", + "start": [-7.5, -4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_ogpav323b07xg0na": { + "id": "wall_ogpav323b07xg0na", + "end": [11.5, -5], + "type": "wall", + "start": [11.5, -3.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_ped3g0xbv9bwjsn1": { + "id": "wall_ped3g0xbv9bwjsn1", + "end": [-0.5, -3.5], + "type": "wall", + "start": [-0.5, -1.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_pfutg6hwyc8grm5g": { + "id": "wall_pfutg6hwyc8grm5g", + "end": [14, -3.5], + "type": "wall", + "start": [-5.5, -3.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_pn4o5vor2ors8vnm": { + "id": "wall_pn4o5vor2ors8vnm", + "end": [-35.5, -11.5], + "type": "wall", + "start": [-35.5, -13], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_qr3ato2gte412a2p": { + "id": "wall_qr3ato2gte412a2p", + "end": [5, 14], + "type": "wall", + "start": [5, 0.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_r8nuh4u93nwjv8b3": { + "id": "wall_r8nuh4u93nwjv8b3", + "end": [-34, -16], + "type": "wall", + "start": [-35.5, -14.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_r9btdhflwvty2ohz": { + "id": "wall_r9btdhflwvty2ohz", + "end": [-37.5, -9.5], + "type": "wall", + "start": [-7.5, -9.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_rbctpv0dyha6oddf": { + "id": "wall_rbctpv0dyha6oddf", + "end": [-43.5, -4], + "type": "wall", + "start": [-5.5, -4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_rbfr59eoh5tpahlh": { + "id": "wall_rbfr59eoh5tpahlh", + "end": [-1, 9], + "type": "wall", + "start": [-1, 10.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_rxzrcmqna3ut46xo": { + "id": "wall_rxzrcmqna3ut46xo", + "end": [14, 17], + "type": "wall", + "start": [14, -11], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_s630rqqw6obzqq8s": { + "id": "wall_s630rqqw6obzqq8s", + "end": [-19, -7.5], + "type": "wall", + "start": [-19, -6], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_sglpg4ks9cn0x4l5": { + "id": "wall_sglpg4ks9cn0x4l5", + "end": [-34.5, 1], + "type": "wall", + "start": [-34.5, -2], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_t126sy3x03fql0pw": { + "id": "wall_t126sy3x03fql0pw", + "end": [11, -5], + "type": "wall", + "start": [11, -3.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_votgocvw5vp44ifa": { + "id": "wall_votgocvw5vp44ifa", + "end": [-29, -9.5], + "type": "wall", + "start": [-29, -7.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_vqnovjffgbf52omt": { + "id": "wall_vqnovjffgbf52omt", + "end": [-39.5, -6], + "type": "wall", + "start": [-39.5, -4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_w5thykpbcwtxuc3o": { + "id": "wall_w5thykpbcwtxuc3o", + "end": [-41, -9.5], + "type": "wall", + "start": [-38.5, -9.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_wft5otdvnjsvspbw": { + "id": "wall_wft5otdvnjsvspbw", + "end": [10, 14], + "type": "wall", + "start": [10, 15.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_wkolqpdukfo4dide": { + "id": "wall_wkolqpdukfo4dide", + "end": [5, -11], + "type": "wall", + "start": [5, -3.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_wm1714a343f1o9vl": { + "id": "wall_wm1714a343f1o9vl", + "end": [-27, -11.5], + "type": "wall", + "start": [-27, -12.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_wxnmg48u9il73pd8": { + "id": "wall_wxnmg48u9il73pd8", + "end": [14, 14], + "type": "wall", + "start": [5, 14], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_x6dyeldyr3ol0hwg": { + "id": "wall_x6dyeldyr3ol0hwg", + "end": [-43.5, -13], + "type": "wall", + "start": [-43.5, -4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "unknown" + }, + "wall_xbze9dp4tpkuqw8r": { + "id": "wall_xbze9dp4tpkuqw8r", + "end": [-33.5, 1], + "type": "wall", + "start": [-33.5, -2], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_xgucj6ycg2i0l0sg": { + "id": "wall_xgucj6ycg2i0l0sg", + "end": [-43.5, -9], + "type": "wall", + "start": [-41, -9], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_xz8qiz635z2ffltn": { + "id": "wall_xz8qiz635z2ffltn", + "end": [12, 6], + "type": "wall", + "start": [12, 8], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_ydkfgbicm374lro9": { + "id": "wall_ydkfgbicm374lro9", + "end": [-33.5, -2], + "type": "wall", + "start": [-31, -2], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "exterior" + }, + "wall_z1dclxzx6n3w0isr": { + "id": "wall_z1dclxzx6n3w0isr", + "end": [3.5, -1.5], + "type": "wall", + "start": [-5.5, -1.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_zbup6o4184iy6f5e": { + "id": "wall_zbup6o4184iy6f5e", + "end": [-5.5, -11], + "type": "wall", + "start": [-5.5, 17], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "wall_zexfzinrw2mhkcw1": { + "id": "wall_zexfzinrw2mhkcw1", + "end": [-26, -16], + "type": "wall", + "start": [-26, -11.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_stlelmley1l34sa3", + "frontSide": "interior" + }, + "zone_02mgeamdu8fpwmff": { + "id": "zone_02mgeamdu8fpwmff", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-43.5, -8.5], + [-41, -8.5], + [-41, -9.5], + [-39.5, -9.5], + [-39.5, -4], + [-43.5, -4], + [-43.5, -4] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_2iedg57y9ph9af0s": { + "id": "zone_2iedg57y9ph9af0s", + "type": "zone", + "color": "#22c55e", + "object": "node", + "polygon": [ + [14, -11], + [17, -11], + [17, -13.5], + [31.5, -13.5], + [31.5, 17], + [14, 17], + [14, 16.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_425elvlzj0ps4p3o": { + "id": "zone_425elvlzj0ps4p3o", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[5, -3.5], [5, 0.5], [14, 0.5], [14, -3.5]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_4ew25x5rpevmmdu3": { + "id": "zone_4ew25x5rpevmmdu3", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[5, 6], [5, 0.5], [14, 0.5], [14, 6], [14, 6]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_5b1u5efn6p9tng0h": { + "id": "zone_5b1u5efn6p9tng0h", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-37.5, -9.5], + [-37.5, -6], + [-39.5, -6], + [-39.5, -4], + [-27.5, -4], + [-27.5, -9.5], + [-27.5, -9.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_71niiasy3rc1tg6n": { + "id": "zone_71niiasy3rc1tg6n", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[5, 17], [10, 17], [10, 14], [5, 14], [5, 14]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_81p4tzwqh2rvp04f": { + "id": "zone_81p4tzwqh2rvp04f", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-20, -9.5], + [-27.5, -9.5], + [-27.5, -4], + [-20, -4], + [-20, -4] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_ab82x68tp2kgbpjd": { + "id": "zone_ab82x68tp2kgbpjd", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[3.5, 17], [5, 17], [5, -3.5], [3.5, -3.5], [3.5, -3.5]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_ak85yb8awfoijozf": { + "id": "zone_ak85yb8awfoijozf", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-20, -9.5], + [-17.5, -9.5], + [-17.5, -7.5], + [-20, -7.5], + [-20, -7.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_cf7j9xw66ilkel27": { + "id": "zone_cf7j9xw66ilkel27", + "type": "zone", + "color": "#84cc16", + "object": "node", + "polygon": [[-5.5, 17], [-21.5, 17], [-21.5, 1], [-5.5, 1], [-5.5, 1]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_dxyk58bskw5a7p2w": { + "id": "zone_dxyk58bskw5a7p2w", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-38.5, -13], + [-43.5, -13], + [-43.5, -9], + [-41, -9], + [-41, -9.5], + [-38.5, -9.5], + [-38.5, -9.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_eaxtcshk704vnfue": { + "id": "zone_eaxtcshk704vnfue", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[-5.5, -11], [-5.5, -3.5], [5, -3.5], [5, -11], [5, -11]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_g01ibjbcq6gcq88x": { + "id": "zone_g01ibjbcq6gcq88x", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-7.5, -11.5], + [-7.5, -13], + [-5, -13], + [-5, -16], + [-16.5, -16], + [-16.5, -11.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_g2fgejhov4knj45s": { + "id": "zone_g2fgejhov4knj45s", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-16.5, -16], + [-26, -16], + [-26, -11.5], + [-16.5, -11.5], + [-16.5, -11.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_jsae6tlqu428abn7": { + "id": "zone_jsae6tlqu428abn7", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-5.5, -13], + [-7.5, -13], + [-7.5, -11.5], + [-35.5, -11.5], + [-35.5, -13], + [-38.5, -13], + [-38.5, -9.5], + [-7.5, -9.5], + [-7.5, -8.5], + [-5.5, -8.5], + [-5.5, -8.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_l2ygwifjgmniy3a9": { + "id": "zone_l2ygwifjgmniy3a9", + "type": "zone", + "color": "#22c55e", + "object": "node", + "polygon": [[-5.5, 1], [-5.5, -4], [-27.5, -4], [-27.5, 1], [-27.5, 1]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_l5umv5qx10o6tx7o": { + "id": "zone_l5umv5qx10o6tx7o", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-5.5, 3.5], + [-5.5, -1.5], + [3.5, -1.5], + [3.5, 3.5], + [3.5, 3.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_lhzkjb0lb62zn53i": { + "id": "zone_lhzkjb0lb62zn53i", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[14, -3.5], [14, -11], [5, -11], [5, -3.5], [5, -3.5]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_myle84xzx8epqmf7": { + "id": "zone_myle84xzx8epqmf7", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [11, 14], + [14, 14], + [14, 17], + [11, 17], + [10, 17], + [10, 15.5], + [11, 15.5], + [11, 15.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_nuqv0hxhptv15svx": { + "id": "zone_nuqv0hxhptv15svx", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[-5.5, 3.5], [3.5, 3.5], [3.5, 9], [-5.5, 9]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_sw03csg2ku4jjsuy": { + "id": "zone_sw03csg2ku4jjsuy", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[5, 14], [5, 8], [14, 8], [14, 14], [14, 14]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_tgwj2a84df1wrvvz": { + "id": "zone_tgwj2a84df1wrvvz", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [3.5, 10.5], + [3.5, 17], + [-5.5, 17], + [-5.5, 10.5], + [-5.5, 10.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_xdbym44pzqc1gv0b": { + "id": "zone_xdbym44pzqc1gv0b", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[-17.5, -9.5], [-17.5, -4], [-7.5, -4], [-7.5, -9.5]], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_z3b0gbhvmp2ok0uk": { + "id": "zone_z3b0gbhvmp2ok0uk", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-28.5, -11.5], + [-28.5, -16], + [-34, -16], + [-35.5, -14.5], + [-35.5, -11.5], + [-35.5, -11.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "zone_zb636fiw49ygjkjx": { + "id": "zone_zb636fiw49ygjkjx", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-7.5, -6], + [-5.5, -6], + [-5.5, -8.5], + [-7.5, -8.5], + [-7.5, -8.5] + ], + "visible": true, + "parentId": "level_stlelmley1l34sa3", + "name": "Room" + }, + "level_stlelmley1l34sa3": { + "id": "level_stlelmley1l34sa3", + "type": "level", + "level": 0, + "camera": { + "mode": "perspective", + "target": [ + -0.15496487479346924, 9.39225262481153e-16, 2.82795297001999 + ], + "position": [15.396158493906801, 28.040758323000606, 24.326125040179864] + }, + "object": "node", + "visible": true, + "children": [ + "wall_5mo4hmjez28klk9f", + "wall_rxzrcmqna3ut46xo", + "slab_f9ggedzfr5o3t149", + "wall_15949dfouwj8qpsc", + "wall_zbup6o4184iy6f5e", + "wall_pfutg6hwyc8grm5g", + "wall_iut41ui0tqarloab", + "wall_l3gxn37y3q4pi5ax", + "wall_0aj6wic7qio2izo6", + "wall_71divlgstgb9mpvc", + "wall_as5w6vi16699chpx", + "wall_rbfr59eoh5tpahlh", + "wall_1hbtnvgrxy7f6poe", + "wall_0nzvz9px5dar8z0l", + "wall_wxnmg48u9il73pd8", + "wall_z1dclxzx6n3w0isr", + "wall_793bsazcqyfsvz9c", + "wall_536z30eic22fqgqc", + "wall_ped3g0xbv9bwjsn1", + "wall_gs14pl04cx36pva7", + "wall_e3deyjy3xkrju0gc", + "wall_mee37i6fzcdnuzt9", + "wall_xz8qiz635z2ffltn", + "wall_1ze5jq3fefffjw52", + "wall_wft5otdvnjsvspbw", + "wall_0kvzfdiwgy4cnacw", + "wall_m3csql2jg7ux6ord", + "wall_6veh8ry5dbj2fiey", + "wall_g5tbuam7nfha9lo8", + "wall_wkolqpdukfo4dide", + "wall_t126sy3x03fql0pw", + "wall_3n77gwhl9s8tmvxo", + "wall_ogpav323b07xg0na", + "wall_ly1s30afyln6hg6q", + "wall_de36jozhode1q6v7", + "wall_36dy9x3sqoy6wgg4", + "zone_tgwj2a84df1wrvvz", + "zone_myle84xzx8epqmf7", + "zone_71niiasy3rc1tg6n", + "zone_ab82x68tp2kgbpjd", + "zone_sw03csg2ku4jjsuy", + "zone_4ew25x5rpevmmdu3", + "wall_lb7olr6dgnlvaqgo", + "wall_qr3ato2gte412a2p", + "wall_asootvz55p1q038b", + "wall_h3v6rziamua2p22o", + "wall_c956y17nxbly3x5f", + "wall_52tqioykvtf8odjm", + "wall_x6dyeldyr3ol0hwg", + "wall_8andzf9w44m5rkhx", + "wall_r8nuh4u93nwjv8b3", + "wall_lifk2135hrgc9kp0", + "wall_h34zsooyggh7sqbp", + "wall_rbctpv0dyha6oddf", + "slab_bnta4or3eqh2xplm", + "wall_nhv0ynccf6opvq3v", + "wall_r9btdhflwvty2ohz", + "wall_pn4o5vor2ors8vnm", + "wall_k087pyy898llp3js", + "wall_4ip1giowtafnh058", + "wall_iz7is9455wjpnc2l", + "wall_lpz601bzwwp5mi0i", + "wall_6vp77787saf6um2t", + "wall_jlnc9j00z8kzgux3", + "wall_9vf0kbq25dzshewk", + "wall_3mg06sehmdoqnyjv", + "wall_mkmkcx6l4h3dr5ip", + "wall_63ajr53v7ywxmd7g", + "wall_s630rqqw6obzqq8s", + "wall_hfruuqr173j480ek", + "wall_2u1njfwqugli3tid", + "wall_votgocvw5vp44ifa", + "wall_vqnovjffgbf52omt", + "wall_4f9e66w9suetb950", + "wall_c6az6y1r54z2drtn", + "wall_0s2pcd4cgvowhu3v", + "wall_0isztqpjued64sfa", + "wall_w5thykpbcwtxuc3o", + "wall_exwjt85vc7j0s9ww", + "wall_l90984dthq0mmyzl", + "wall_5ada6bnjsopj7mcv", + "wall_zexfzinrw2mhkcw1", + "wall_blj1enmtun5ipbug", + "wall_f7rgk2xj964j29p4", + "zone_nuqv0hxhptv15svx", + "zone_l5umv5qx10o6tx7o", + "zone_425elvlzj0ps4p3o", + "zone_lhzkjb0lb62zn53i", + "zone_eaxtcshk704vnfue", + "zone_jsae6tlqu428abn7", + "zone_xdbym44pzqc1gv0b", + "zone_81p4tzwqh2rvp04f", + "zone_5b1u5efn6p9tng0h", + "zone_g01ibjbcq6gcq88x", + "zone_g2fgejhov4knj45s", + "wall_n88dnm2ks9pwhmuc", + "wall_bjg67mcipb7kg4di", + "wall_6lxpax19l50n5h9t", + "wall_wm1714a343f1o9vl", + "wall_xgucj6ycg2i0l0sg", + "zone_z3b0gbhvmp2ok0uk", + "zone_dxyk58bskw5a7p2w", + "zone_02mgeamdu8fpwmff", + "zone_zb636fiw49ygjkjx", + "zone_ak85yb8awfoijozf", + "slab_a4l2atfuq2oq8iqc", + "slab_xfxova3w95a5ibga", + "slab_6kljkihx1fl8fczc", + "slab_phiaz2oon3pbersd", + "zone_2iedg57y9ph9af0s", + "zone_cf7j9xw66ilkel27", + "zone_l2ygwifjgmniy3a9", + "wall_xbze9dp4tpkuqw8r", + "wall_hziwxf7z9ezmz1js", + "wall_6d992n60jpziiblz", + "wall_ydkfgbicm374lro9", + "wall_sglpg4ks9cn0x4l5", + "wall_fx5nfcudovy7heif", + "wall_dfsxus2f85opn40n", + "wall_l8vxzycrphhwah48", + "slab_sy7spjy224lcizow", + "slab_z4arxxumfwf49pjh", + "slab_4ayxwcccspdn2om1", + "slab_wrmpydclyqul2spi", + "slab_5hsaa9zuz876s97b", + "wall_6j4eo4lls3q11ljn", + "wall_8rloffkfsu5t91zm", + "wall_43f64trfdbf6a310", + "slab_5fy9c24rhwaumj4a", + "slab_qq16dvomnxldijly", + "slab_abmcx8ded3a5nkkh", + "slab_ngfjur4pgtze9obe", + "slab_tkzjta7h17uxm37y", + "ceiling_c30veqmu0wu0waa3", + "ceiling_45nuif1zn3axkfpy", + "ceiling_kyumxtnn3dkl6q6r", + "ceiling_j0h82w75e2yc80zg" + ], + "parentId": null + }, + "ceiling_45nuif1zn3axkfpy": { + "id": "ceiling_45nuif1zn3axkfpy", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [ + [-5, -16], + [-5, -13], + [-7.5, -13], + [-7.5, -11.5], + [-35.5, -11.5], + [-35.5, -14.5], + [-34, -16] + ], + "visible": true, + "children": [], + "parentId": "level_stlelmley1l34sa3", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_c30veqmu0wu0waa3": { + "id": "ceiling_c30veqmu0wu0waa3", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [[14, 17], [-5.5, 17], [-5.5, -11], [14, -11]], + "visible": true, + "children": [], + "parentId": "level_stlelmley1l34sa3", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_j0h82w75e2yc80zg": { + "id": "ceiling_j0h82w75e2yc80zg", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [[-31, -2], [-31, 1], [-33.5, 1], [-33.5, -2]], + "visible": true, + "children": [], + "parentId": "level_stlelmley1l34sa3", + "holeMetadata": [], + "autoFromWalls": true + }, + "ceiling_kyumxtnn3dkl6q6r": { + "id": "ceiling_kyumxtnn3dkl6q6r", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [[-37.5, 1], [-37.5, -2], [-34.5, -2], [-34.5, 1]], + "visible": true, + "children": [], + "parentId": "level_stlelmley1l34sa3", + "holeMetadata": [], + "autoFromWalls": true + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-13.json b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-13.json new file mode 100644 index 0000000000..d2413c5b3b --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-13.json @@ -0,0 +1,59 @@ +{ + "sceneId": "scene-13", + "levelId": "level_001", + "rootNodeIds": ["level_001"], + "nodes": { + "wall_001": { + "id": "wall_001", + "end": [5, 0], + "type": "wall", + "start": [0, 0], + "object": "node", + "visible": true, + "backSide": "exterior", + "parentId": "level_001", + "frontSide": "interior" + }, + "wall_002": { + "id": "wall_002", + "end": [5, 4], + "type": "wall", + "start": [5, 0], + "object": "node", + "visible": true, + "backSide": "exterior", + "parentId": "level_001", + "frontSide": "interior" + }, + "wall_003": { + "id": "wall_003", + "end": [0, 4], + "type": "wall", + "start": [5, 4], + "object": "node", + "visible": true, + "backSide": "exterior", + "parentId": "level_001", + "frontSide": "interior" + }, + "wall_004": { + "id": "wall_004", + "end": [0, 0], + "type": "wall", + "start": [0, 4], + "object": "node", + "visible": true, + "backSide": "exterior", + "parentId": "level_001", + "frontSide": "interior" + }, + "level_001": { + "id": "level_001", + "type": "level", + "object": "node", + "visible": true, + "parentId": null, + "level": 0 + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-16.json b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-16.json new file mode 100644 index 0000000000..86c4aef3e7 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-16.json @@ -0,0 +1,559 @@ +{ + "sceneId": "scene-16", + "levelId": "level_jjq25jwx1hmqc5i3", + "rootNodeIds": ["site_goelvxil8ko4gd5f", "building_a3lwlwrdusk5hka2"], + "nodes": { + "site_goelvxil8ko4gd5f": { + "id": "site_goelvxil8ko4gd5f", + "type": "site", + "object": "node", + "polygon": { + "type": "polygon", + "points": [[-15, -15], [15, -15], [15, 15], [-15, 15]] + }, + "visible": true, + "children": ["building_a3lwlwrdusk5hka2"], + "parentId": null + }, + "slab_85bhtpk4tc7ycgt1": { + "id": "slab_85bhtpk4tc7ycgt1", + "type": "slab", + "holes": [ + [ + [7.6000000000000005, -1.7], + [7.6000000000000005, -0.7], + [4.6000000000000005, -0.6999999999999997], + [4.6000000000000005, -1.6999999999999997] + ] + ], + "object": "node", + "polygon": [ + [7.9, -0.9], + [6.1000000000000005, -0.9], + [6.1000000000000005, -2.7], + [7.9, -2.7], + [7.9, -1.8] + ], + "visible": true, + "parentId": "level_jjq25jwx1hmqc5i3", + "elevation": 0.05, + "holeMetadata": [ + { + "source": "stair", + "stairId": "stair_jo3mobjwhln74zc8" + } + ], + "autoFromWalls": false + }, + "slab_wshl8mj112jbo6dw": { + "id": "slab_wshl8mj112jbo6dw", + "type": "slab", + "holes": [ + [ + [7.6000000000000005, -1.7], + [7.6000000000000005, -0.7], + [4.6000000000000005, -0.6999999999999997], + [4.6000000000000005, -1.6999999999999997] + ] + ], + "object": "node", + "polygon": [[8, -1], [6, -1], [6, -2.5], [8, -2.5]], + "visible": true, + "parentId": "level_jjq25jwx1hmqc5i3", + "elevation": 0.05, + "holeMetadata": [ + { + "source": "stair", + "stairId": "stair_jo3mobjwhln74zc8" + } + ], + "autoFromWalls": false + }, + "sseg_32fu35v69hsi670w": { + "id": "sseg_32fu35v69hsi670w", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_xgsaefekwyklqy55", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": false, + "segmentType": "stair", + "attachmentSide": "right" + }, + "sseg_48hziccy5te7wmo6": { + "id": "sseg_48hziccy5te7wmo6", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_jdz2q11qr9rrzrhz", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_496hh416moahlfkz": { + "id": "sseg_496hh416moahlfkz", + "type": "stair-segment", + "width": 1, + "height": 0, + "length": 1, + "object": "node", + "visible": true, + "parentId": "stair_jo3mobjwhln74zc8", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 0, + "thickness": 0.32, + "fillToFloor": false, + "segmentType": "landing", + "attachmentSide": "right" + }, + "sseg_50bt9my1ljet77xf": { + "id": "sseg_50bt9my1ljet77xf", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_jo3mobjwhln74zc8", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": false, + "segmentType": "stair", + "attachmentSide": "right" + }, + "sseg_7z0cc9fno8wre66p": { + "id": "sseg_7z0cc9fno8wre66p", + "type": "stair-segment", + "width": 1, + "height": 2, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_xgsaefekwyklqy55", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 8, + "thickness": 0.25, + "fillToFloor": false, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_efxlb46t5h3s7cua": { + "id": "sseg_efxlb46t5h3s7cua", + "type": "stair-segment", + "width": 1, + "height": 0, + "length": 1, + "object": "node", + "visible": true, + "parentId": "stair_xgsaefekwyklqy55", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 0, + "thickness": 0.32, + "fillToFloor": false, + "segmentType": "landing", + "attachmentSide": "front" + }, + "sseg_j0hfhblfi93e9kgb": { + "id": "sseg_j0hfhblfi93e9kgb", + "type": "stair-segment", + "width": 1, + "height": 2, + "length": 2.6, + "object": "node", + "visible": true, + "parentId": "stair_3b8baqs12xohecvd", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 8, + "thickness": 0.25, + "fillToFloor": false, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_njgb5whikte2oobh": { + "id": "sseg_njgb5whikte2oobh", + "type": "stair-segment", + "width": 1, + "height": 0, + "length": 1, + "object": "node", + "visible": true, + "parentId": "stair_jo3mobjwhln74zc8", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 0, + "thickness": 0.32, + "fillToFloor": false, + "segmentType": "landing", + "attachmentSide": "front" + }, + "sseg_txbz3t540hf51264": { + "id": "sseg_txbz3t540hf51264", + "type": "stair-segment", + "width": 1, + "height": 0, + "length": 1, + "object": "node", + "visible": true, + "parentId": "stair_xgsaefekwyklqy55", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 0, + "thickness": 0.32, + "fillToFloor": false, + "segmentType": "landing", + "attachmentSide": "right" + }, + "sseg_yjte9sjiztcadf7d": { + "id": "sseg_yjte9sjiztcadf7d", + "type": "stair-segment", + "width": 1, + "height": 2, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_jo3mobjwhln74zc8", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 8, + "thickness": 0.25, + "fillToFloor": false, + "segmentType": "stair", + "attachmentSide": "front" + }, + "wall_1dgfh75jenor4e7o": { + "id": "wall_1dgfh75jenor4e7o", + "end": [7.9, -2.7], + "type": "wall", + "start": [7.9, 2.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jjq25jwx1hmqc5i3", + "frontSide": "unknown" + }, + "wall_tzvvq5vc7u0l8gdv": { + "id": "wall_tzvvq5vc7u0l8gdv", + "end": [-0.5, -2.7], + "type": "wall", + "start": [7.9, -2.7], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jjq25jwx1hmqc5i3", + "frontSide": "unknown" + }, + "wall_vcrzmr6alqda3yje": { + "id": "wall_vcrzmr6alqda3yje", + "end": [7.9, 2.5], + "type": "wall", + "start": [-0.5, 2.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jjq25jwx1hmqc5i3", + "frontSide": "unknown" + }, + "level_2bnpew1m74ux64bx": { + "id": "level_2bnpew1m74ux64bx", + "type": "level", + "level": 10, + "object": "node", + "visible": true, + "children": ["stair_jo3mobjwhln74zc8"], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "level_30lqg6d50f0kjszh": { + "id": "level_30lqg6d50f0kjszh", + "type": "level", + "level": 15, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "level_4479lxtre7ytoqa0": { + "id": "level_4479lxtre7ytoqa0", + "type": "level", + "level": 8, + "object": "node", + "visible": true, + "children": ["stair_3b8baqs12xohecvd"], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "level_dpwvxvex3aosei15": { + "id": "level_dpwvxvex3aosei15", + "type": "level", + "level": 2, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "level_f9lmvswci0yaoe3y": { + "id": "level_f9lmvswci0yaoe3y", + "type": "level", + "level": 11, + "object": "node", + "visible": true, + "children": [ + "stair_amun0ctpvmdmernc", + "stair_fv9qmmgyq51wc064", + "stair_xgsaefekwyklqy55" + ], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "level_ilndtni52wkd7z0c": { + "id": "level_ilndtni52wkd7z0c", + "type": "level", + "level": 6, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "level_jjq25jwx1hmqc5i3": { + "id": "level_jjq25jwx1hmqc5i3", + "type": "level", + "level": 3, + "object": "node", + "visible": true, + "children": [ + "wall_vcrzmr6alqda3yje", + "wall_tzvvq5vc7u0l8gdv", + "wall_1dgfh75jenor4e7o", + "stair_jdz2q11qr9rrzrhz", + "slab_wshl8mj112jbo6dw", + "slab_85bhtpk4tc7ycgt1" + ], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "level_vp07reb0vx19bve7": { + "id": "level_vp07reb0vx19bve7", + "type": "level", + "level": 14, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_a3lwlwrdusk5hka2" + }, + "stair_3b8baqs12xohecvd": { + "id": "stair_3b8baqs12xohecvd", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_j0hfhblfi93e9kgb"], + "parentId": "level_4479lxtre7ytoqa0", + "position": [6.7, 0, -2.2], + "rotation": 4.71238898038469, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_2bnpew1m74ux64bx", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_4479lxtre7ytoqa0", + "innerRadius": 0.9, + "railingMode": "left", + "openingOffset": 0.08, + "railingHeight": 0.94, + "topLandingMode": "none", + "slabOpeningMode": "none", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_amun0ctpvmdmernc": { + "id": "stair_amun0ctpvmdmernc", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_f9lmvswci0yaoe3y", + "position": [4.7, 0, -2.2], + "rotation": 1.5707963267948966, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_ur2lhswwmmcyrbvj", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_f9lmvswci0yaoe3y", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.03, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_fv9qmmgyq51wc064": { + "id": "stair_fv9qmmgyq51wc064", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_f9lmvswci0yaoe3y", + "position": [2.9000000000000004, 0, -5.65], + "rotation": 1.5707963267948966, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_ur2lhswwmmcyrbvj", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_f9lmvswci0yaoe3y", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.03, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_jdz2q11qr9rrzrhz": { + "id": "stair_jdz2q11qr9rrzrhz", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_48hziccy5te7wmo6"], + "parentId": "level_jjq25jwx1hmqc5i3", + "position": [5.9, 0, -2.2], + "rotation": -1.5707963267948966, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_ilndtni52wkd7z0c", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_jjq25jwx1hmqc5i3", + "innerRadius": 0.9, + "railingMode": "both", + "openingOffset": 0.05, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_jo3mobjwhln74zc8": { + "id": "stair_jo3mobjwhln74zc8", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": [ + "sseg_yjte9sjiztcadf7d", + "sseg_njgb5whikte2oobh", + "sseg_496hh416moahlfkz", + "sseg_50bt9my1ljet77xf" + ], + "parentId": "level_2bnpew1m74ux64bx", + "position": [4.6000000000000005, 0, -2.2], + "rotation": 1.5707963267948966, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_vp07reb0vx19bve7", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_dpwvxvex3aosei15", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.07, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_xgsaefekwyklqy55": { + "id": "stair_xgsaefekwyklqy55", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": [ + "sseg_7z0cc9fno8wre66p", + "sseg_efxlb46t5h3s7cua", + "sseg_txbz3t540hf51264", + "sseg_32fu35v69hsi670w" + ], + "parentId": "level_f9lmvswci0yaoe3y", + "position": [4.6000000000000005, 0, -2.2], + "rotation": 1.5707963267948966, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_vp07reb0vx19bve7", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_f9lmvswci0yaoe3y", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.07, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "building_a3lwlwrdusk5hka2": { + "id": "building_a3lwlwrdusk5hka2", + "type": "building", + "object": "node", + "visible": true, + "children": [ + "level_dpwvxvex3aosei15", + "level_vp07reb0vx19bve7", + "level_30lqg6d50f0kjszh", + "level_f9lmvswci0yaoe3y", + "level_4479lxtre7ytoqa0", + "level_2bnpew1m74ux64bx", + "level_ilndtni52wkd7z0c", + "level_jjq25jwx1hmqc5i3" + ], + "parentId": null, + "position": [0, 0, 0], + "rotation": [0, 0, 0] + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-22.json b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-22.json new file mode 100644 index 0000000000..4f86071d7a --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/legacy-load/scene-22.json @@ -0,0 +1,628 @@ +{ + "sceneId": "scene-22", + "levelId": "level_hswd4yoqdjljnuvg", + "rootNodeIds": [ + "site_075w2f9ug29lzt4v", + "level_xsxfm073covupgok", + "building_47cv0wd0otma9pps" + ], + "nodes": { + "site_075w2f9ug29lzt4v": { + "id": "site_075w2f9ug29lzt4v", + "type": "site", + "object": "node", + "polygon": { + "type": "polygon", + "points": [[-15, -15], [15, -15], [15, 15], [-15, 15]] + }, + "visible": true, + "children": ["building_47cv0wd0otma9pps"], + "parentId": null + }, + "slab_78816e9y6w8hlla0": { + "id": "slab_78816e9y6w8hlla0", + "type": "slab", + "holes": [[[3.4, 2.4], [4.6, 2.4], [4.6, 5.6], [3.4, 5.6]]], + "object": "node", + "polygon": [[0, 0], [5, 0], [5, 5], [0, 5]], + "visible": true, + "parentId": "level_hswd4yoqdjljnuvg", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "sseg_0dce2vmhhjktdzce": { + "id": "sseg_0dce2vmhhjktdzce", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_2b0mkdicbithmawo", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_44w5vvm8vcm8ekw8": { + "id": "sseg_44w5vvm8vcm8ekw8", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_9v0ccteoliib6w39", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_5nlgej8dnaddma8c": { + "id": "sseg_5nlgej8dnaddma8c", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_s6ix1wsmr7lxc637", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 14, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_cmpsm4qw9uqi9a3x": { + "id": "sseg_cmpsm4qw9uqi9a3x", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_ozf1junzizejkh0n", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_euqs51t3plc7xffq": { + "id": "sseg_euqs51t3plc7xffq", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_v3v4etijoyi9xvq7", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_p2pzxtgtpk4svl12": { + "id": "sseg_p2pzxtgtpk4svl12", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_54biudeuymkcbrue", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "sseg_sica55vjl0zknkjq": { + "id": "sseg_sica55vjl0zknkjq", + "type": "stair-segment", + "width": 1, + "height": 2.5, + "length": 3, + "object": "node", + "visible": true, + "parentId": "stair_mdr7k3yj0ab3obvv", + "position": [0, 0, 0], + "rotation": 0, + "stepCount": 10, + "thickness": 0.25, + "fillToFloor": true, + "segmentType": "stair", + "attachmentSide": "front" + }, + "wall_3w27ehlyzrf5x9kl": { + "id": "wall_3w27ehlyzrf5x9kl", + "end": [5, 5], + "type": "wall", + "start": [5, 0], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_hswd4yoqdjljnuvg", + "frontSide": "interior" + }, + "wall_go820l9a3v9zzuy3": { + "id": "wall_go820l9a3v9zzuy3", + "end": [5, 0], + "type": "wall", + "start": [0, 0], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_hswd4yoqdjljnuvg", + "frontSide": "interior" + }, + "wall_o5c5vqa15f7bzpx6": { + "id": "wall_o5c5vqa15f7bzpx6", + "end": [0, 5], + "type": "wall", + "start": [5, 5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_hswd4yoqdjljnuvg", + "frontSide": "interior" + }, + "wall_yh1m2697ukx482qq": { + "id": "wall_yh1m2697ukx482qq", + "end": [0, 0], + "type": "wall", + "start": [0, 5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_hswd4yoqdjljnuvg", + "frontSide": "interior" + }, + "zone_9m2xofxr19z8ox5x": { + "id": "zone_9m2xofxr19z8ox5x", + "type": "zone", + "color": "#dcfce7", + "object": "node", + "polygon": [[0, 0], [5, 0], [5, 5], [0, 5]], + "visible": true, + "parentId": "level_hswd4yoqdjljnuvg", + "name": "Room" + }, + "level_008nyzkpdq2a2f8g": { + "id": "level_008nyzkpdq2a2f8g", + "type": "level", + "level": -4, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_23pu0tc7x7ajx7tp": { + "id": "level_23pu0tc7x7ajx7tp", + "type": "level", + "level": 6, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_2at01irw7c8h5p3d": { + "id": "level_2at01irw7c8h5p3d", + "type": "level", + "level": 13, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_3oi7e2hfrjk9r1ur": { + "id": "level_3oi7e2hfrjk9r1ur", + "type": "level", + "level": 5, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_3yblm6pz7zfo7814": { + "id": "level_3yblm6pz7zfo7814", + "type": "level", + "level": 9, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_6z96us2bvhv73vk5": { + "id": "level_6z96us2bvhv73vk5", + "type": "level", + "level": -1, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_80byiv8upq8i3151": { + "id": "level_80byiv8upq8i3151", + "type": "level", + "level": 11, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_hswd4yoqdjljnuvg": { + "id": "level_hswd4yoqdjljnuvg", + "type": "level", + "level": 1, + "object": "node", + "visible": true, + "children": [ + "zone_9m2xofxr19z8ox5x", + "slab_78816e9y6w8hlla0", + "ceiling_cookd5bjana5aovn", + "wall_go820l9a3v9zzuy3", + "wall_3w27ehlyzrf5x9kl", + "wall_o5c5vqa15f7bzpx6", + "wall_yh1m2697ukx482qq" + ], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_iu9hp81zpmn9iqlh": { + "id": "level_iu9hp81zpmn9iqlh", + "type": "level", + "level": 10, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_nfrx31kb2dgohe68": { + "id": "level_nfrx31kb2dgohe68", + "type": "level", + "level": 4, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_obf2fc2yijn9yys3": { + "id": "level_obf2fc2yijn9yys3", + "type": "level", + "level": -2, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_sqg7yovap52fala0": { + "id": "level_sqg7yovap52fala0", + "type": "level", + "level": 8, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_t7c2mdsay4d2y7ib": { + "id": "level_t7c2mdsay4d2y7ib", + "type": "level", + "level": 12, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_th83a8v59ifjy18b": { + "id": "level_th83a8v59ifjy18b", + "type": "level", + "level": 3, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_uej9ibnj74vw69h5": { + "id": "level_uej9ibnj74vw69h5", + "type": "level", + "level": 2, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_uojqr4167htjgsbk": { + "id": "level_uojqr4167htjgsbk", + "type": "level", + "level": 7, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_w1o75a8mmqlzkt6n": { + "id": "level_w1o75a8mmqlzkt6n", + "type": "level", + "level": -3, + "object": "node", + "visible": true, + "children": [], + "parentId": "building_47cv0wd0otma9pps" + }, + "level_xsxfm073covupgok": { + "id": "level_xsxfm073covupgok", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "stair_mdr7k3yj0ab3obvv", + "stair_ozf1junzizejkh0n", + "stair_54biudeuymkcbrue", + "stair_9v0ccteoliib6w39", + "stair_2b0mkdicbithmawo", + "stair_v3v4etijoyi9xvq7", + "stair_s6ix1wsmr7lxc637" + ], + "parentId": null + }, + "stair_2b0mkdicbithmawo": { + "id": "stair_2b0mkdicbithmawo", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_0dce2vmhhjktdzce"], + "parentId": "level_xsxfm073covupgok", + "position": [2.5, 0, 2.5], + "rotation": 0, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_xsxfm073covupgok", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_xsxfm073covupgok", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.08, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_54biudeuymkcbrue": { + "id": "stair_54biudeuymkcbrue", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_p2pzxtgtpk4svl12"], + "parentId": "level_xsxfm073covupgok", + "position": [4.5, 0, -3.5], + "rotation": 0, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_xsxfm073covupgok", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_xsxfm073covupgok", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.08, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_9v0ccteoliib6w39": { + "id": "stair_9v0ccteoliib6w39", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_44w5vvm8vcm8ekw8"], + "parentId": "level_xsxfm073covupgok", + "position": [4.5, 0, 0.5], + "rotation": 0, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_xsxfm073covupgok", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_xsxfm073covupgok", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.08, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_mdr7k3yj0ab3obvv": { + "id": "stair_mdr7k3yj0ab3obvv", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_sica55vjl0zknkjq"], + "parentId": "level_xsxfm073covupgok", + "position": [2, 0, 2], + "rotation": 0, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_xsxfm073covupgok", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_xsxfm073covupgok", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.08, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_ozf1junzizejkh0n": { + "id": "stair_ozf1junzizejkh0n", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_cmpsm4qw9uqi9a3x"], + "parentId": "level_xsxfm073covupgok", + "position": [0, 0, -1], + "rotation": 0, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_xsxfm073covupgok", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_xsxfm073covupgok", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.08, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_s6ix1wsmr7lxc637": { + "id": "stair_s6ix1wsmr7lxc637", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_5nlgej8dnaddma8c"], + "parentId": "level_xsxfm073covupgok", + "position": [4, 0, 4], + "rotation": 0, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": null, + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": null, + "innerRadius": 0.9, + "railingMode": "none", + "openingOffset": 0, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "none", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "stair_v3v4etijoyi9xvq7": { + "id": "stair_v3v4etijoyi9xvq7", + "type": "stair", + "width": 1, + "object": "node", + "visible": true, + "children": ["sseg_euqs51t3plc7xffq"], + "parentId": "level_xsxfm073covupgok", + "position": [1.5, 0, 3], + "rotation": 0, + "stairType": "straight", + "stepCount": 10, + "thickness": 0.25, + "toLevelId": "level_xsxfm073covupgok", + "totalRise": 2.5, + "sweepAngle": 1.5707963267948966, + "fillToFloor": true, + "fromLevelId": "level_xsxfm073covupgok", + "innerRadius": 0.9, + "railingMode": "right", + "openingOffset": 0.08, + "railingHeight": 0.92, + "topLandingMode": "none", + "slabOpeningMode": "destination", + "topLandingDepth": 0.9, + "showCenterColumn": true, + "showStepSupports": true + }, + "ceiling_cookd5bjana5aovn": { + "id": "ceiling_cookd5bjana5aovn", + "type": "ceiling", + "holes": [], + "height": 2.5, + "object": "node", + "polygon": [[0, 0], [5, 0], [5, 5], [0, 5]], + "visible": true, + "children": [], + "parentId": "level_hswd4yoqdjljnuvg", + "holeMetadata": [], + "autoFromWalls": false + }, + "building_47cv0wd0otma9pps": { + "id": "building_47cv0wd0otma9pps", + "type": "building", + "object": "node", + "visible": true, + "children": [ + "level_xsxfm073covupgok", + "level_hswd4yoqdjljnuvg", + "level_uej9ibnj74vw69h5", + "level_th83a8v59ifjy18b", + "level_nfrx31kb2dgohe68", + "level_3oi7e2hfrjk9r1ur", + "level_6z96us2bvhv73vk5", + "level_23pu0tc7x7ajx7tp", + "level_uojqr4167htjgsbk", + "level_sqg7yovap52fala0", + "level_obf2fc2yijn9yys3", + "level_3yblm6pz7zfo7814", + "level_w1o75a8mmqlzkt6n", + "level_iu9hp81zpmn9iqlh", + "level_80byiv8upq8i3151", + "level_t7c2mdsay4d2y7ib", + "level_008nyzkpdq2a2f8g", + "level_2at01irw7c8h5p3d" + ], + "parentId": null, + "position": [0, 0, 0], + "rotation": [0, 0, 0] + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/README.md b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/README.md new file mode 100644 index 0000000000..6d3cf3742d --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/README.md @@ -0,0 +1,29 @@ +Trimmed, anonymised levels from the production migration corpus. Each file +retains wall/slab/zone IDs, plan coordinates, construction, materials and holes +after the shared normalization/healing/vertical prefix, before M3–M6–M4–M5; +names and project IDs are neutral. Furniture and unrelated levels are omitted. +The retained level has a null parent and ordinal zero; child lists contain only +retained nodes. One level per distinct legacy case: + +- `scene-23`: a stale small floor overlapping a much larger or moved room. +- `scene-11`: zero visible floor area in a room buried inside thick walls. +- `scene-27`: disconnected miter islands emitted as separate plate components. +- `scene-25` (two levels): stored wall coverage over curved and mitered faces, + stair holes and finish overlays. +- `scene-09`: recessed auto slab preserved verbatim. +- `scene-05`, `scene-08`: legacy string and object materials rejected by the + slab schema. +- `scene-03`: a reverse boundary misclassified as its own hole; an oversized + generic zone must not be adopted over it. +- `scene-01`: no bounded room; unmatched construction is demoted with its + geometry and id intact. +- `scene-12`: snapped junction representatives must not depend on wall + insertion order. +- `scene-20`: a preserved source hole contains a whole detected room. + +`../legacy-load/` contains four levels before healing and vertical migration. +`scene-04` omits legacy slab holes; `scene-13` omits level children; `scene-16` +and `scene-22` retain stairs and their destination levels to reproduce +client-only opening writes. Their tests compare shared migrations plus additive +opening normalization with real client hydration, before/after opening-system +mount and on reload. Non-geometric furniture is omitted. diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-01-level_eodfbqctw101ntkx.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-01-level_eodfbqctw101ntkx.json new file mode 100644 index 0000000000..cf44fc2fd1 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-01-level_eodfbqctw101ntkx.json @@ -0,0 +1,195 @@ +{ + "sceneId": "scene-01", + "levelId": "level_eodfbqctw101ntkx", + "nodes": { + "level_eodfbqctw101ntkx": { + "id": "level_eodfbqctw101ntkx", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_7o6wm0ibt0rd0ye2", + "wall_1sveaax1krz4az03", + "wall_8y2me61vfsxoer8z", + "wall_vym9bs8po1o3ksvx", + "wall_8uia6kkutqro8vnl", + "wall_pyjj20kic89qx9k3", + "wall_30o44thskucert5b", + "wall_xwzn9vvsk2bypuiv", + "wall_lm57fqo36239e2s6", + "slab_do4yte9qjf7cdbjc", + "wall_vp03b9845ysdzffn", + "wall_mavbsb3giha0cxff", + "wall_i1b3bep9opnvkvd2" + ], + "parentId": null, + "height": 2.5 + }, + "slab_do4yte9qjf7cdbjc": { + "id": "slab_do4yte9qjf7cdbjc", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [4, 6.5], + [-2.5, 6.5], + [-2.5, -10.5], + [6, -2], + [6, 2.5], + [3, -0.5], + [4, -1.5] + ], + "visible": true, + "parentId": "level_eodfbqctw101ntkx", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_1sveaax1krz4az03": { + "id": "wall_1sveaax1krz4az03", + "end": [6, 2.5], + "type": "wall", + "start": [3, -0.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "exterior" + }, + "wall_30o44thskucert5b": { + "id": "wall_30o44thskucert5b", + "end": [4, 2], + "type": "wall", + "start": [4, 3.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "exterior" + }, + "wall_7o6wm0ibt0rd0ye2": { + "id": "wall_7o6wm0ibt0rd0ye2", + "end": [3, -0.5], + "type": "wall", + "start": [4, -1.5], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "interior" + }, + "wall_8uia6kkutqro8vnl": { + "id": "wall_8uia6kkutqro8vnl", + "end": [-2.5, 6.5], + "type": "wall", + "start": [-2.5, -10.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "exterior" + }, + "wall_8y2me61vfsxoer8z": { + "id": "wall_8y2me61vfsxoer8z", + "end": [6, -2], + "type": "wall", + "start": [6, 2.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "exterior" + }, + "wall_i1b3bep9opnvkvd2": { + "id": "wall_i1b3bep9opnvkvd2", + "end": [4.5, -3], + "type": "wall", + "start": [1.5, -6], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "unknown" + }, + "wall_lm57fqo36239e2s6": { + "id": "wall_lm57fqo36239e2s6", + "end": [4, 2], + "type": "wall", + "start": [4, 6.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "exterior" + }, + "wall_mavbsb3giha0cxff": { + "id": "wall_mavbsb3giha0cxff", + "end": [1.5, -6], + "type": "wall", + "start": [4, -3.5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "unknown" + }, + "wall_pyjj20kic89qx9k3": { + "id": "wall_pyjj20kic89qx9k3", + "end": [4, 6.5], + "type": "wall", + "start": [-2.5, 6.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "exterior" + }, + "wall_vp03b9845ysdzffn": { + "id": "wall_vp03b9845ysdzffn", + "end": [4, -3.5], + "type": "wall", + "start": [4, 2], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "interior" + }, + "wall_vym9bs8po1o3ksvx": { + "id": "wall_vym9bs8po1o3ksvx", + "end": [-2.5, -10.5], + "type": "wall", + "start": [6, -2], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "exterior" + }, + "wall_xwzn9vvsk2bypuiv": { + "id": "wall_xwzn9vvsk2bypuiv", + "end": [4, -1.5], + "type": "wall", + "start": [4, 2], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_eodfbqctw101ntkx", + "frontSide": "interior" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-03-level_jed5kaoexwb8xvuh.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-03-level_jed5kaoexwb8xvuh.json new file mode 100644 index 0000000000..27cc741915 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-03-level_jed5kaoexwb8xvuh.json @@ -0,0 +1,284 @@ +{ + "sceneId": "scene-03", + "levelId": "level_jed5kaoexwb8xvuh", + "nodes": { + "level_jed5kaoexwb8xvuh": { + "id": "level_jed5kaoexwb8xvuh", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_yuhd63lhd7iiqugv", + "wall_gksncu4tm5tntfar", + "wall_98d6osywwn7w5i73", + "wall_tg8ojdbyom5tqg5y", + "wall_ntg76iphcfmcd3ym", + "wall_yefjr4ee2u3l0zpf", + "wall_wuu8ee64vxd51mpt", + "wall_ec15hubjbu9ik1kb", + "wall_hfvdwqr5jelaxbap", + "wall_ur34m5pb6njl8ht5", + "wall_6d0enwskvali2l2u", + "wall_5murxcpc72s1rsn4", + "slab_brxrvau96os29cp8" + ], + "parentId": null, + "height": 2.5 + }, + "slab_brxrvau96os29cp8": { + "id": "slab_brxrvau96os29cp8", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -6.6000000000000005, + 0.30000000000000004 + ], + [ + -6.6000000000000005, + -4.800000000000001 + ], + [ + 5, + -4.9 + ], + [ + 4.898913199948556, + -0.900023626088075 + ], + [ + -3.6, + -1.1 + ], + [ + -3.6, + 0.4 + ] + ], + "visible": true, + "parentId": "level_jed5kaoexwb8xvuh", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_5murxcpc72s1rsn4": { + "id": "wall_5murxcpc72s1rsn4", + "end": [ + -6.6000000000000005, + 0.30000000000000004 + ], + "type": "wall", + "start": [ + -6.6000000000000005, + -4.800000000000001 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_6d0enwskvali2l2u": { + "id": "wall_6d0enwskvali2l2u", + "end": [ + -6.6000000000000005, + -4.800000000000001 + ], + "type": "wall", + "start": [ + -3.6, + -4.800000000000001 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_98d6osywwn7w5i73": { + "id": "wall_98d6osywwn7w5i73", + "end": [ + -3.6516093229744735, + 0.3982796892341842 + ], + "type": "wall", + "start": [ + -6.6000000000000005, + 0.30000000000000004 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_ec15hubjbu9ik1kb": { + "id": "wall_ec15hubjbu9ik1kb", + "end": [ + 4.89891329691433, + -0.900027462996595 + ], + "type": "wall", + "start": [ + 4.898913199948556, + -0.900023626088075 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_gksncu4tm5tntfar": { + "id": "wall_gksncu4tm5tntfar", + "end": [ + -3.6, + -1.1 + ], + "type": "wall", + "start": [ + -3.6, + 0.4 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_hfvdwqr5jelaxbap": { + "id": "wall_hfvdwqr5jelaxbap", + "end": [ + 5, + -4.9 + ], + "type": "wall", + "start": [ + 4.89891329691433, + -0.900027462996595 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_ntg76iphcfmcd3ym": { + "id": "wall_ntg76iphcfmcd3ym", + "end": [ + 4.9, + -0.9500164284545259 + ], + "type": "wall", + "start": [ + 0.30000000000000004, + -1 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_tg8ojdbyom5tqg5y": { + "id": "wall_tg8ojdbyom5tqg5y", + "end": [ + 0.30000000000000004, + -1 + ], + "type": "wall", + "start": [ + -3.6, + -1.1 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_ur34m5pb6njl8ht5": { + "id": "wall_ur34m5pb6njl8ht5", + "end": [ + -3.6, + -4.800000000000001 + ], + "type": "wall", + "start": [ + 5, + -4.9 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_wuu8ee64vxd51mpt": { + "id": "wall_wuu8ee64vxd51mpt", + "end": [ + 4.9, + -0.9 + ], + "type": "wall", + "start": [ + 4.898913199948556, + -0.900023626088075 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_yefjr4ee2u3l0zpf": { + "id": "wall_yefjr4ee2u3l0zpf", + "end": [ + 4.898913199948556, + -0.900023626088075 + ], + "type": "wall", + "start": [ + 0.30000000000000004, + -1 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + }, + "wall_yuhd63lhd7iiqugv": { + "id": "wall_yuhd63lhd7iiqugv", + "end": [ + -3.6, + 0.4 + ], + "type": "wall", + "start": [ + -3.651609322974473, + 0.3982796892341842 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jed5kaoexwb8xvuh", + "frontSide": "exterior" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-05-level_jkmni52gfrkgddfo.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-05-level_jkmni52gfrkgddfo.json new file mode 100644 index 0000000000..4b0f03e6e8 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-05-level_jkmni52gfrkgddfo.json @@ -0,0 +1,332 @@ +{ + "sceneId": "scene-05", + "levelId": "level_jkmni52gfrkgddfo", + "nodes": { + "level_jkmni52gfrkgddfo": { + "id": "level_jkmni52gfrkgddfo", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "zone_1y65y18ky3zdxyjj", + "slab_62v8vmbt6fxkva94", + "wall_2nz943v2req0sxhd", + "zone_2iqtf438ykwmvh67", + "slab_xa42gky75ad7v57e", + "wall_b8dif9hv3z53vti8", + "wall_cdk3u7n6e5so52w6", + "wall_899skb7x6hzhlhth", + "slab_z90l9hg6o9dlm97i", + "wall_b7fb2elw83c6ku74", + "wall_vskhry0v7572vjk1" + ], + "parentId": null, + "height": 2.5 + }, + "slab_62v8vmbt6fxkva94": { + "id": "slab_62v8vmbt6fxkva94", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 0, + 0 + ], + [ + 2.2, + 0 + ], + [ + 2.2, + 2.2 + ], + [ + 0, + 2.2 + ] + ], + "visible": true, + "material": "tiles", + "parentId": "level_jkmni52gfrkgddfo", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": false, + "thickness": 0.05 + }, + "slab_xa42gky75ad7v57e": { + "id": "slab_xa42gky75ad7v57e", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 2.2, + 0 + ], + [ + 6, + 0 + ], + [ + 6, + 5 + ], + [ + 0, + 5 + ], + [ + 0, + 2.2 + ], + [ + 2.2, + 2.2 + ] + ], + "visible": true, + "material": "tiles", + "parentId": "level_jkmni52gfrkgddfo", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": false, + "thickness": 0.05 + }, + "slab_z90l9hg6o9dlm97i": { + "id": "slab_z90l9hg6o9dlm97i", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 0, + 5 + ], + [ + 0, + 0 + ], + [ + 6, + 0 + ], + [ + 6, + 5 + ] + ], + "visible": true, + "material": "tiles", + "parentId": "level_jkmni52gfrkgddfo", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_2nz943v2req0sxhd": { + "id": "wall_2nz943v2req0sxhd", + "end": [ + 0, + 0 + ], + "type": "wall", + "start": [ + 0, + 5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "material": { + "preset": "concrete" + }, + "parentId": "level_jkmni52gfrkgddfo", + "frontSide": "interior", + "thickness": 0.35, + "exteriorMaterialPreset": "library:wall-wood4", + "interiorMaterialPreset": "library:wall-wood2" + }, + "wall_899skb7x6hzhlhth": { + "id": "wall_899skb7x6hzhlhth", + "end": [ + 0, + 5 + ], + "type": "wall", + "start": [ + 6, + 5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "material": { + "preset": "concrete" + }, + "parentId": "level_jkmni52gfrkgddfo", + "frontSide": "interior", + "thickness": 0.35 + }, + "wall_b7fb2elw83c6ku74": { + "id": "wall_b7fb2elw83c6ku74", + "end": [ + 2.2, + 2.2 + ], + "type": "wall", + "start": [ + 0, + 2.2 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "material": { + "preset": "concrete" + }, + "parentId": "level_jkmni52gfrkgddfo", + "frontSide": "unknown", + "thickness": 0.07 + }, + "wall_b8dif9hv3z53vti8": { + "id": "wall_b8dif9hv3z53vti8", + "end": [ + 6, + 0 + ], + "type": "wall", + "start": [ + 0, + 0 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "material": { + "preset": "concrete" + }, + "parentId": "level_jkmni52gfrkgddfo", + "frontSide": "interior", + "thickness": 0.35, + "exteriorMaterialPreset": "library:wall-wood4" + }, + "wall_cdk3u7n6e5so52w6": { + "id": "wall_cdk3u7n6e5so52w6", + "end": [ + 6, + 5 + ], + "type": "wall", + "start": [ + 6, + 0 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "material": { + "preset": "concrete" + }, + "parentId": "level_jkmni52gfrkgddfo", + "frontSide": "interior", + "thickness": 0.35 + }, + "wall_vskhry0v7572vjk1": { + "id": "wall_vskhry0v7572vjk1", + "end": [ + 2.2, + 0 + ], + "type": "wall", + "start": [ + 2.2, + 2.2 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "material": { + "preset": "concrete" + }, + "parentId": "level_jkmni52gfrkgddfo", + "frontSide": "unknown", + "thickness": 0.07 + }, + "zone_1y65y18ky3zdxyjj": { + "id": "zone_1y65y18ky3zdxyjj", + "type": "zone", + "color": "#06b6d4", + "object": "node", + "polygon": [ + [ + 0, + 0 + ], + [ + 2.2, + 0 + ], + [ + 2.2, + 2.2 + ], + [ + 0, + 2.2 + ] + ], + "visible": true, + "material": { + "preset": "tiles" + }, + "parentId": "level_jkmni52gfrkgddfo", + "name": "Room" + }, + "zone_2iqtf438ykwmvh67": { + "id": "zone_2iqtf438ykwmvh67", + "type": "zone", + "color": "#f97316", + "object": "node", + "polygon": [ + [ + 2.2, + 0 + ], + [ + 6, + 0 + ], + [ + 6, + 5 + ], + [ + 0, + 5 + ], + [ + 0, + 2.2 + ], + [ + 2.2, + 2.2 + ] + ], + "visible": true, + "material": { + "preset": "tiles" + }, + "parentId": "level_jkmni52gfrkgddfo", + "name": "Room" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-08-level_4jr4wmtf6uevuduw.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-08-level_4jr4wmtf6uevuduw.json new file mode 100644 index 0000000000..5f75d5d4a3 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-08-level_4jr4wmtf6uevuduw.json @@ -0,0 +1,458 @@ +{ + "sceneId": "scene-08", + "levelId": "level_4jr4wmtf6uevuduw", + "nodes": { + "level_4jr4wmtf6uevuduw": { + "id": "level_4jr4wmtf6uevuduw", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_akq701buxvufpmm0", + "wall_3pf1t6yo2u14tpq1", + "slab_caxtlu2vctnjxqls", + "zone_sxi0evje0t4erx82", + "slab_vn5wsuj8qivquk9i", + "wall_5v4czr8v7nijra8h", + "wall_xkx7cxpe3zb4t71h", + "wall_axkcc3iav816vywz", + "wall_sgpcldguh3tdhruj", + "wall_rys2up4t0rblr5oi", + "wall_91e7luvuaxsb1px4", + "zone_fxtz9jv9v8vblhh5", + "slab_1om127zunhwmob9c", + "wall_mzd6z6da39bws4dm", + "wall_4xqfcxwphb29ayg7", + "wall_82zv05n904mncuj0", + "wall_ptn4ahycdhw07s3p", + "wall_z775m5v2rr9ldz0r", + "wall_qcy0m8bonit15hw2" + ], + "parentId": null, + "height": 2.55 + }, + "slab_1om127zunhwmob9c": { + "id": "slab_1om127zunhwmob9c", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -6, + 1 + ], + [ + -3, + 1 + ], + [ + -3, + 5 + ], + [ + -6, + 5 + ] + ], + "visible": true, + "material": { + "name": "Material", + "color": "#ffffff", + "preset": "marble", + "texture": "texture.jpg" + }, + "parentId": "level_4jr4wmtf6uevuduw", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": false, + "thickness": 0.05 + }, + "slab_caxtlu2vctnjxqls": { + "id": "slab_caxtlu2vctnjxqls", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -7, + -3 + ], + [ + 1.5, + -3 + ], + [ + 1.5, + 4.5 + ], + [ + -7, + 4.5 + ] + ], + "visible": true, + "material": { + "name": "Material", + "color": "#ffffff", + "preset": "marble", + "texture": "texture.jpg" + }, + "parentId": "level_4jr4wmtf6uevuduw", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_vn5wsuj8qivquk9i": { + "id": "slab_vn5wsuj8qivquk9i", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -0.5, + -2.5 + ], + [ + 1.5, + -2.5 + ], + [ + 1.5, + -0.5 + ], + [ + -0.5, + -0.5 + ] + ], + "visible": true, + "material": { + "name": "Material", + "color": "#ffffff", + "preset": "marble", + "texture": "texture.jpg" + }, + "parentId": "level_4jr4wmtf6uevuduw", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": false, + "thickness": 0.05 + }, + "wall_3pf1t6yo2u14tpq1": { + "id": "wall_3pf1t6yo2u14tpq1", + "end": [ + -7, + 3.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-greige", + "interior": "library:preset-greige" + }, + "start": [ + -7, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "interior" + }, + "wall_4xqfcxwphb29ayg7": { + "id": "wall_4xqfcxwphb29ayg7", + "end": [ + -3, + 4.5 + ], + "type": "wall", + "start": [ + -3, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_5v4czr8v7nijra8h": { + "id": "wall_5v4czr8v7nijra8h", + "end": [ + -0.5, + -1 + ], + "type": "wall", + "start": [ + 1.5, + -1 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_82zv05n904mncuj0": { + "id": "wall_82zv05n904mncuj0", + "end": [ + -6, + 0.5 + ], + "type": "wall", + "start": [ + -6, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_91e7luvuaxsb1px4": { + "id": "wall_91e7luvuaxsb1px4", + "end": [ + 1.5, + 4.5 + ], + "type": "wall", + "start": [ + 1.5, + -1 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_akq701buxvufpmm0": { + "id": "wall_akq701buxvufpmm0", + "end": [ + -7, + -3 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-greige", + "interior": "library:preset-greige" + }, + "start": [ + -7, + 3.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "interior" + }, + "wall_axkcc3iav816vywz": { + "id": "wall_axkcc3iav816vywz", + "end": [ + -0.5, + -3 + ], + "type": "wall", + "start": [ + -7, + -3 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_mzd6z6da39bws4dm": { + "id": "wall_mzd6z6da39bws4dm", + "end": [ + -3, + 0.5 + ], + "type": "wall", + "start": [ + -6, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_ptn4ahycdhw07s3p": { + "id": "wall_ptn4ahycdhw07s3p", + "end": [ + -3, + 4.5 + ], + "type": "wall", + "start": [ + 1.5, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_qcy0m8bonit15hw2": { + "id": "wall_qcy0m8bonit15hw2", + "end": [ + -7, + 4.5 + ], + "type": "wall", + "start": [ + -6, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_rys2up4t0rblr5oi": { + "id": "wall_rys2up4t0rblr5oi", + "end": [ + 1.5, + -1 + ], + "type": "wall", + "start": [ + 1.5, + -3 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_sgpcldguh3tdhruj": { + "id": "wall_sgpcldguh3tdhruj", + "end": [ + 1.5, + -3 + ], + "type": "wall", + "start": [ + -0.5, + -3 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_xkx7cxpe3zb4t71h": { + "id": "wall_xkx7cxpe3zb4t71h", + "end": [ + -0.5, + -3 + ], + "type": "wall", + "start": [ + -0.5, + -1 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "wall_z775m5v2rr9ldz0r": { + "id": "wall_z775m5v2rr9ldz0r", + "end": [ + -6, + 4.5 + ], + "type": "wall", + "start": [ + -3, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_4jr4wmtf6uevuduw", + "frontSide": "unknown" + }, + "zone_fxtz9jv9v8vblhh5": { + "id": "zone_fxtz9jv9v8vblhh5", + "type": "zone", + "color": "#f97316", + "object": "node", + "polygon": [ + [ + -6, + 1 + ], + [ + -3, + 1 + ], + [ + -3, + 5 + ], + [ + -6, + 5 + ] + ], + "visible": true, + "parentId": "level_4jr4wmtf6uevuduw", + "name": "Room" + }, + "zone_sxi0evje0t4erx82": { + "id": "zone_sxi0evje0t4erx82", + "type": "zone", + "color": "#06b6d4", + "object": "node", + "polygon": [ + [ + -0.5, + -2.5 + ], + [ + 1.5, + -2.5 + ], + [ + 1.5, + -0.5 + ], + [ + -0.5, + -0.5 + ] + ], + "visible": true, + "parentId": "level_4jr4wmtf6uevuduw", + "name": "Room" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-09-level_t3oshtg9z9weuhvz.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-09-level_t3oshtg9z9weuhvz.json new file mode 100644 index 0000000000..c8d9ca400c --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-09-level_t3oshtg9z9weuhvz.json @@ -0,0 +1,374 @@ +{ + "sceneId": "scene-09", + "levelId": "level_t3oshtg9z9weuhvz", + "nodes": { + "level_t3oshtg9z9weuhvz": { + "id": "level_t3oshtg9z9weuhvz", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_7q35b3989x0opvre", + "wall_hn1p8iuvlokjhel2", + "wall_vayvzltbmzs07pmh", + "wall_r5065x10blms6dr6", + "wall_um80mzuyeul24ape", + "wall_w3clk9vwq0ty3gtp", + "wall_spqp3rk7hoqj8lki", + "slab_ic2vx143rrzpw38v", + "wall_2knehfyov30012vb", + "wall_at9y4zgr4js78lmz", + "wall_4fsxkmuy92x5s8u6", + "wall_xh39qrdeoyk73d0t", + "wall_q6a3t5mqbrh88e8p", + "slab_7690r5ng1xfcpr5j", + "wall_cke1ij4n6vh1x4vw", + "slab_dqlmd4mtiv033at4" + ], + "parentId": null, + "height": 2.5 + }, + "slab_7690r5ng1xfcpr5j": { + "id": "slab_7690r5ng1xfcpr5j", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -3.5, + -2.5 + ], + [ + -2, + -2.5 + ], + [ + -2, + 0 + ], + [ + -3.5, + 0 + ] + ], + "visible": true, + "parentId": "level_t3oshtg9z9weuhvz", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_dqlmd4mtiv033at4": { + "id": "slab_dqlmd4mtiv033at4", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -2, + 2.5 + ], + [ + -3.5, + 2.5 + ], + [ + -3.5, + 0 + ], + [ + -2, + 0 + ] + ], + "visible": true, + "parentId": "level_t3oshtg9z9weuhvz", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_ic2vx143rrzpw38v": { + "id": "slab_ic2vx143rrzpw38v", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -3, + -4.5 + ], + [ + 1, + -4.5 + ], + [ + 1, + 4.5 + ], + [ + -3, + 4.5 + ], + [ + -3, + 2.5 + ], + [ + -1.5, + 2.5 + ], + [ + -1.5, + -2.5 + ], + [ + -3, + -2.5 + ] + ], + "visible": true, + "parentId": "level_t3oshtg9z9weuhvz", + "elevation": -0.15, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05, + "recessed": true + }, + "wall_2knehfyov30012vb": { + "id": "wall_2knehfyov30012vb", + "end": [ + -2, + 2.5 + ], + "type": "wall", + "start": [ + -3.5, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "interior" + }, + "wall_4fsxkmuy92x5s8u6": { + "id": "wall_4fsxkmuy92x5s8u6", + "end": [ + -3.5, + 2.5 + ], + "type": "wall", + "start": [ + -3.5, + 0 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_7q35b3989x0opvre": { + "id": "wall_7q35b3989x0opvre", + "end": [ + 0.5, + -4.5 + ], + "type": "wall", + "start": [ + -3.5, + -4.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "interior" + }, + "wall_at9y4zgr4js78lmz": { + "id": "wall_at9y4zgr4js78lmz", + "end": [ + -3.5, + 0 + ], + "type": "wall", + "start": [ + -3.5, + -2.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_cke1ij4n6vh1x4vw": { + "id": "wall_cke1ij4n6vh1x4vw", + "end": [ + -3.5, + 0 + ], + "type": "wall", + "start": [ + -2, + 0 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "unknown" + }, + "wall_hn1p8iuvlokjhel2": { + "id": "wall_hn1p8iuvlokjhel2", + "end": [ + -1.5, + 4.5 + ], + "type": "wall", + "start": [ + -3.5, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_q6a3t5mqbrh88e8p": { + "id": "wall_q6a3t5mqbrh88e8p", + "end": [ + -2, + 2.5 + ], + "type": "wall", + "start": [ + -2, + 0 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "unknown" + }, + "wall_r5065x10blms6dr6": { + "id": "wall_r5065x10blms6dr6", + "end": [ + 0.5, + -4.5 + ], + "type": "wall", + "start": [ + 0.5, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_spqp3rk7hoqj8lki": { + "id": "wall_spqp3rk7hoqj8lki", + "end": [ + -3.5, + 4.5 + ], + "type": "wall", + "start": [ + -3.5, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_um80mzuyeul24ape": { + "id": "wall_um80mzuyeul24ape", + "end": [ + -3.5, + -2.5 + ], + "type": "wall", + "start": [ + -3.5, + -4.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_vayvzltbmzs07pmh": { + "id": "wall_vayvzltbmzs07pmh", + "end": [ + 0.5, + 4.5 + ], + "type": "wall", + "start": [ + -1.5, + 4.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_w3clk9vwq0ty3gtp": { + "id": "wall_w3clk9vwq0ty3gtp", + "end": [ + -2, + -2.5 + ], + "type": "wall", + "start": [ + -3.5, + -2.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "exterior" + }, + "wall_xh39qrdeoyk73d0t": { + "id": "wall_xh39qrdeoyk73d0t", + "end": [ + -2, + 0 + ], + "type": "wall", + "start": [ + -2, + -2.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_t3oshtg9z9weuhvz", + "frontSide": "unknown" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-11-level_0xnyuk0r705m454c.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-11-level_0xnyuk0r705m454c.json new file mode 100644 index 0000000000..47bab598c3 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-11-level_0xnyuk0r705m454c.json @@ -0,0 +1,1653 @@ +{ + "sceneId": "scene-11", + "levelId": "level_0xnyuk0r705m454c", + "nodes": { + "level_0xnyuk0r705m454c": { + "id": "level_0xnyuk0r705m454c", + "type": "level", + "level": 0, + "height": 2.5, + "object": "node", + "visible": true, + "children": [ + "wall_1gcskim364wgn24m", + "wall_yqopyvqdi4l8on6v", + "wall_srtiz9bi6lhqvmy1", + "wall_e8ww7ltu1gv7dl78", + "wall_645jt0tuk9v6zdol", + "wall_spbnaonci6fxespi", + "wall_a0rlxw5mnmrcs473", + "wall_rha4lzo7eh3ws82k", + "wall_chwknrty2gn0ll3u", + "wall_al6p4qomw2nv79ke", + "wall_y6bcx6e1lj1wmu9m", + "wall_08h45866jpdcpoxk", + "wall_nkpituv93ae3d168", + "wall_uosn63syg7u24hw3", + "wall_hadjwjqxov1m7mkd", + "wall_245w9h0woyk03ffa", + "wall_uy4h3gi5gmu4f7vq", + "wall_9rhv9xsicyx0kyke", + "wall_k2wlgacc07nd24dq", + "wall_xsygsfzv8ri0lee6", + "wall_wc7xoabyvofp0bjg", + "wall_kdwdxed5474a7ovr", + "wall_1n3kkxqb8gtk7k9g", + "wall_jb2otapj9dh8qhf7", + "wall_yggy9iov0q7kkvze", + "zone_0bib5oli4vnelf3k", + "wall_onkzu7xeh8ygknfd", + "wall_ske1omhb6gdxjx5c", + "wall_eucur8msj0lcc279", + "wall_v1tpjvrhuqu0rj8z", + "wall_gfggcwgerrtue97v", + "wall_vy6zr3mubzidn1xq", + "wall_bzfeioqoktx8aodg", + "wall_8k3pg5njdivce2yc", + "wall_a66wzlr56veg35k0", + "wall_8z91mszxqk4z3ce2", + "wall_stjav7wrp15025st", + "wall_rrgwf1lgecnfqymc", + "wall_vh542hlbe2x7bl7e", + "wall_h1hyroqmbnwlnqxg", + "wall_7ji3co55y1thexcw", + "slab_rje4llgwpt43axe3", + "wall_x5v9qhzdd4n0q768", + "wall_8yxriu0ibk376ri9", + "wall_o1zv4h4fhprw76al", + "wall_6q762j2nodftv57j", + "wall_uwzgvnp40dguvejx", + "wall_lu40749r5itl19r5", + "wall_65hmc026lsm69f6e", + "wall_y80zd8bxdofnz08s", + "wall_z00krd8n90dfiisb", + "wall_rnr9tia73mywzzuy", + "slab_peodurz577287g87", + "wall_ubnf4klxb8azzfq4", + "wall_v3szxpu3r7ahs1dy", + "wall_5mog495q8rsd1ctt", + "wall_nxyxj4nb1lkms814", + "wall_t3b398e82lxedvf2", + "wall_0s7jzrugb29y6yxj", + "wall_thkwbhk528kyecqw", + "wall_da63wgp36d9ke257", + "wall_t34tt1a0tq3w1ent", + "wall_ogajz4vxxec8mm70", + "wall_a3qv1l9khpcob11l", + "wall_48hwocby2etyqf31", + "wall_zu1njz00t1attej3", + "wall_icc1wb2orbitvd2f" + ], + "parentId": null, + "baseElevation": 0 + }, + "slab_peodurz577287g87": { + "id": "slab_peodurz577287g87", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 10.5, + -1.5 + ], + [ + 8.020833333333334, + -1.5 + ], + [ + 8, + -1.75 + ], + [ + 10.5, + -1.75 + ] + ], + "visible": true, + "parentId": "level_0xnyuk0r705m454c", + "recessed": false, + "elevation": 5.050000000000002, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_rje4llgwpt43axe3": { + "id": "slab_rje4llgwpt43axe3", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 10.289020069013336, + 10.240005508086622 + ], + [ + 2.5, + 10 + ], + [ + 10.289020069013336, + 10 + ] + ], + "visible": true, + "parentId": "level_0xnyuk0r705m454c", + "recessed": false, + "elevation": 2.55, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "wall_08h45866jpdcpoxk": { + "id": "wall_08h45866jpdcpoxk", + "end": [ + 10.289020069013336, + 10 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 10.289020069013336, + 10.240005508086622 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "exterior", + "thickness": 0.3 + }, + "wall_0s7jzrugb29y6yxj": { + "id": "wall_0s7jzrugb29y6yxj", + "end": [ + 10.5, + -1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 10.5, + -1.75 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_1gcskim364wgn24m": { + "id": "wall_1gcskim364wgn24m", + "end": [ + 7.789020069013336, + 5.240005508086622 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-beige" + }, + "start": [ + 10.289020069013336, + 5.240005508086622 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_1n3kkxqb8gtk7k9g": { + "id": "wall_1n3kkxqb8gtk7k9g", + "end": [ + 6, + -11.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 12, + -11.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_245w9h0woyk03ffa": { + "id": "wall_245w9h0woyk03ffa", + "end": [ + 2.5, + 8 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 2.5, + 10 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_48hwocby2etyqf31": { + "id": "wall_48hwocby2etyqf31", + "end": [ + 10, + 3 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 10.25, + 1.5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 5.000000000000002, + "supportSlabId": "ground" + }, + "wall_5mog495q8rsd1ctt": { + "id": "wall_5mog495q8rsd1ctt", + "end": [ + 8, + -1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 10.5, + -1.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "interior", + "thickness": 0.3 + }, + "wall_645jt0tuk9v6zdol": { + "id": "wall_645jt0tuk9v6zdol", + "end": [ + 1, + -8.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 1, + -11.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_65hmc026lsm69f6e": { + "id": "wall_65hmc026lsm69f6e", + "end": [ + 10.5, + -1.75 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 10.5, + -1.5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "exterior", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_6q762j2nodftv57j": { + "id": "wall_6q762j2nodftv57j", + "end": [ + 10.5, + -3.25 + ], + "type": "wall", + "start": [ + 10.5, + -3 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_7ji3co55y1thexcw": { + "id": "wall_7ji3co55y1thexcw", + "end": [ + 10.5, + 10.25 + ], + "type": "wall", + "start": [ + 2.5, + 10 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_8k3pg5njdivce2yc": { + "id": "wall_8k3pg5njdivce2yc", + "end": [ + 2.76471331920785, + 4.799996148141359 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-beige" + }, + "start": [ + 2.76545019020785, + 8.99999809214136 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_8yxriu0ibk376ri9": { + "id": "wall_8yxriu0ibk376ri9", + "end": [ + 10, + 3 + ], + "type": "wall", + "start": [ + 10, + 3.25 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_8z91mszxqk4z3ce2": { + "id": "wall_8z91mszxqk4z3ce2", + "end": [ + 10, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 9, + 1.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_9rhv9xsicyx0kyke": { + "id": "wall_9rhv9xsicyx0kyke", + "end": [ + -3.5, + 10 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + -3.5, + 8 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_a0rlxw5mnmrcs473": { + "id": "wall_a0rlxw5mnmrcs473", + "end": [ + -4.5, + -5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + -4.5, + -8.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_a3qv1l9khpcob11l": { + "id": "wall_a3qv1l9khpcob11l", + "end": [ + 10.25, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 10, + 1.5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 5.000000000000002, + "supportSlabId": "ground" + }, + "wall_a66wzlr56veg35k0": { + "id": "wall_a66wzlr56veg35k0", + "end": [ + 2.76545019020785, + 8.99999809214136 + ], + "type": "wall", + "slots": { + "interior": "library:preset-beige" + }, + "start": [ + 2.76545023820785, + 9.799998186141359 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_al6p4qomw2nv79ke": { + "id": "wall_al6p4qomw2nv79ke", + "end": [ + -10, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + -6, + 1.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_bzfeioqoktx8aodg": { + "id": "wall_bzfeioqoktx8aodg", + "end": [ + 10.5, + -3 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-cream" + }, + "start": [ + 7.75, + -3 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_chwknrty2gn0ll3u": { + "id": "wall_chwknrty2gn0ll3u", + "end": [ + -6, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + -6, + -5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_da63wgp36d9ke257": { + "id": "wall_da63wgp36d9ke257", + "end": [ + 9, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 8.5, + 1.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_e8ww7ltu1gv7dl78": { + "id": "wall_e8ww7ltu1gv7dl78", + "end": [ + 10, + 3 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 10, + 1.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_eucur8msj0lcc279": { + "id": "wall_eucur8msj0lcc279", + "end": [ + 10, + 3 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 10.5, + 3.75 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_gfggcwgerrtue97v": { + "id": "wall_gfggcwgerrtue97v", + "end": [ + 12.289020069013336, + -11.759994491913378 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 12, + -11.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_h1hyroqmbnwlnqxg": { + "id": "wall_h1hyroqmbnwlnqxg", + "end": [ + 8, + 5 + ], + "type": "wall", + "start": [ + 2.75, + 4.75 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "supportOffset": 2.499999999999999, + "supportSlabId": "ground" + }, + "wall_hadjwjqxov1m7mkd": { + "id": "wall_hadjwjqxov1m7mkd", + "end": [ + 2.5, + 10 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 10.289020069013336, + 10 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_icc1wb2orbitvd2f": { + "id": "wall_icc1wb2orbitvd2f", + "end": [ + 10.5, + -1.75 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-cream" + }, + "start": [ + 8, + -1.5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_jb2otapj9dh8qhf7": { + "id": "wall_jb2otapj9dh8qhf7", + "end": [ + 1, + -11.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 6, + -11.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_k2wlgacc07nd24dq": { + "id": "wall_k2wlgacc07nd24dq", + "end": [ + -10, + 10 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + -3.5, + 10 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_kdwdxed5474a7ovr": { + "id": "wall_kdwdxed5474a7ovr", + "end": [ + 6, + -10 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-beige" + }, + "start": [ + 6, + -8 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_lu40749r5itl19r5": { + "id": "wall_lu40749r5itl19r5", + "end": [ + 8, + -1.75 + ], + "type": "wall", + "start": [ + 8, + -1.5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "interior", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_nkpituv93ae3d168": { + "id": "wall_nkpituv93ae3d168", + "end": [ + 10.289020069013336, + 5.240005508086622 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 10.289020069013336, + 10 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_nxyxj4nb1lkms814": { + "id": "wall_nxyxj4nb1lkms814", + "end": [ + 8, + -1.5 + ], + "type": "wall", + "slots": { + "interior": "library:preset-cream" + }, + "start": [ + 8, + 1.4655172413793103 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 5.000000000000002, + "supportSlabId": "ground" + }, + "wall_o1zv4h4fhprw76al": { + "id": "wall_o1zv4h4fhprw76al", + "end": [ + 10, + 1.5 + ], + "type": "wall", + "slots": { + "interior": "library:preset-cream" + }, + "start": [ + 10, + 3 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_ogajz4vxxec8mm70": { + "id": "wall_ogajz4vxxec8mm70", + "end": [ + 10, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 9, + 1.5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 5.000000000000002, + "supportSlabId": "ground" + }, + "wall_onkzu7xeh8ygknfd": { + "id": "wall_onkzu7xeh8ygknfd", + "end": [ + 7.75, + 5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-beige" + }, + "start": [ + 2.75, + 4.75 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_rha4lzo7eh3ws82k": { + "id": "wall_rha4lzo7eh3ws82k", + "end": [ + -6, + -5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + -4.5, + -5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_rnr9tia73mywzzuy": { + "id": "wall_rnr9tia73mywzzuy", + "end": [ + 10.75, + -1.75 + ], + "type": "wall", + "start": [ + 10.5, + -1.75 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_rrgwf1lgecnfqymc": { + "id": "wall_rrgwf1lgecnfqymc", + "end": [ + 8, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 8, + 1.4655172413793105 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_ske1omhb6gdxjx5c": { + "id": "wall_ske1omhb6gdxjx5c", + "end": [ + 10.5, + 3.75 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 10.5, + 5.25 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_spbnaonci6fxespi": { + "id": "wall_spbnaonci6fxespi", + "end": [ + -4.5, + -8.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 1, + -8.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_srtiz9bi6lhqvmy1": { + "id": "wall_srtiz9bi6lhqvmy1", + "end": [ + 12.289020069013336, + -11.759994491913378 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 12.289020069013336, + -4.759994491913378 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_stjav7wrp15025st": { + "id": "wall_stjav7wrp15025st", + "end": [ + 8, + 1.4655172413793105 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 8, + -1.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_t34tt1a0tq3w1ent": { + "id": "wall_t34tt1a0tq3w1ent", + "end": [ + 9, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 8.5, + 1.5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 5.000000000000002, + "supportSlabId": "ground" + }, + "wall_t3b398e82lxedvf2": { + "id": "wall_t3b398e82lxedvf2", + "end": [ + 10.5, + -1.75 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 10.5, + -3 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_thkwbhk528kyecqw": { + "id": "wall_thkwbhk528kyecqw", + "end": [ + 8.5, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 8, + 1.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_ubnf4klxb8azzfq4": { + "id": "wall_ubnf4klxb8azzfq4", + "end": [ + 10, + 1.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 8, + 1.4655172413793103 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.5000000000000018, + "supportSlabId": "ground" + }, + "wall_uosn63syg7u24hw3": { + "id": "wall_uosn63syg7u24hw3", + "end": [ + 10.289020069013336, + 10 + ], + "type": "wall", + "start": [ + 10.5, + 10 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_uwzgvnp40dguvejx": { + "id": "wall_uwzgvnp40dguvejx", + "end": [ + 8, + -1.5 + ], + "type": "wall", + "slots": { + "interior": "library:preset-cream" + }, + "start": [ + 8, + 1.4655172413793103 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_uy4h3gi5gmu4f7vq": { + "id": "wall_uy4h3gi5gmu4f7vq", + "end": [ + -3.5, + 8 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-beige" + }, + "start": [ + 2.5, + 8 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_v1tpjvrhuqu0rj8z": { + "id": "wall_v1tpjvrhuqu0rj8z", + "end": [ + 8, + 5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige" + }, + "start": [ + 7.75, + 5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_v3szxpu3r7ahs1dy": { + "id": "wall_v3szxpu3r7ahs1dy", + "end": [ + 10, + 3 + ], + "type": "wall", + "slots": { + "interior": "library:preset-cream" + }, + "start": [ + 10.5, + 5 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.5, + "supportSlabId": "ground" + }, + "wall_vh542hlbe2x7bl7e": { + "id": "wall_vh542hlbe2x7bl7e", + "end": [ + 9, + 1.5 + ], + "type": "wall", + "start": [ + 8, + 1.4655172413793103 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_vy6zr3mubzidn1xq": { + "id": "wall_vy6zr3mubzidn1xq", + "end": [ + 7.75, + -3 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream" + }, + "start": [ + 7.789020069013336, + -4.759994491913378 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_wc7xoabyvofp0bjg": { + "id": "wall_wc7xoabyvofp0bjg", + "end": [ + 6, + -8 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-beige" + }, + "start": [ + 6, + -5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_x5v9qhzdd4n0q768": { + "id": "wall_x5v9qhzdd4n0q768", + "end": [ + 10.5, + 5 + ], + "type": "wall", + "slots": { + "interior": "library:preset-cream" + }, + "start": [ + 10.289020069013336, + 10 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.5, + "supportSlabId": "ground" + }, + "wall_xsygsfzv8ri0lee6": { + "id": "wall_xsygsfzv8ri0lee6", + "end": [ + 6, + -5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-beige" + }, + "start": [ + 8, + -5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_y6bcx6e1lj1wmu9m": { + "id": "wall_y6bcx6e1lj1wmu9m", + "end": [ + -10, + 10 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + -10, + 1.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_y80zd8bxdofnz08s": { + "id": "wall_y80zd8bxdofnz08s", + "end": [ + 10.5, + -3 + ], + "type": "wall", + "slots": { + "interior": "library:preset-cream" + }, + "start": [ + 10.5, + -1.75 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_yggy9iov0q7kkvze": { + "id": "wall_yggy9iov0q7kkvze", + "end": [ + 6, + -11.5 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-beige" + }, + "start": [ + 6, + -10 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown" + }, + "wall_yqopyvqdi4l8on6v": { + "id": "wall_yqopyvqdi4l8on6v", + "end": [ + 12.289020069013336, + -4.759994491913378 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-beige", + "interior": "library:preset-cream" + }, + "start": [ + 7.789020069013336, + -4.759994491913378 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3 + }, + "wall_z00krd8n90dfiisb": { + "id": "wall_z00krd8n90dfiisb", + "end": [ + 10.5, + -1.75 + ], + "type": "wall", + "slots": { + "exterior": "library:preset-cream", + "interior": "library:preset-cream" + }, + "start": [ + 8, + -1.75 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "interior", + "thickness": 0.3, + "supportOffset": 2.4999999999999982, + "supportSlabId": "ground" + }, + "wall_zu1njz00t1attej3": { + "id": "wall_zu1njz00t1attej3", + "end": [ + 10.75, + -3.5 + ], + "type": "wall", + "slots": { + "interior": "library:preset-cream" + }, + "start": [ + 10.5, + -1.75 + ], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_0xnyuk0r705m454c", + "frontSide": "unknown", + "thickness": 0.3, + "supportOffset": 4.999999999999998, + "supportSlabId": "ground" + }, + "zone_0bib5oli4vnelf3k": { + "id": "zone_0bib5oli4vnelf3k", + "type": "zone", + "color": "#ef4444", + "object": "node", + "polygon": [ + [ + 7.750000001, + 9.749999999 + ], + [ + 2.750000001, + 9.750000001 + ], + [ + 2.749999999, + 4.750000001 + ], + [ + 7.749999999, + 4.749999999 + ] + ], + "visible": true, + "parentId": "level_0xnyuk0r705m454c", + "occupancy": "", + "spaceRole": "generic", + "roomNumber": "", + "wallFinish": "", + "floorFinish": "", + "autoFromWalls": false, + "ceilingFinish": "", + "ceilingHeight": 2.7, + "boundaryWallIds": [], + "enclosureStatus": "auto", + "clearDimensionPolicy": "none", + "name": "Room" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-12-level_v7ocab71p8y3f2x9.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-12-level_v7ocab71p8y3f2x9.json new file mode 100644 index 0000000000..05cc797a29 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-12-level_v7ocab71p8y3f2x9.json @@ -0,0 +1,382 @@ +{ + "sceneId": "scene-12", + "levelId": "level_v7ocab71p8y3f2x9", + "nodes": { + "level_v7ocab71p8y3f2x9": { + "id": "level_v7ocab71p8y3f2x9", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_front_diagonal", + "wall_long_side", + "wall_short_back", + "wall_north_closing", + "wall_kantoor_left", + "wall_kantoor_top", + "wall_opslag_wc_left", + "wall_opslag_wc_divider", + "wall_opslag_wc_top", + "wall_w870xc7popsgkznm", + "wall_9kl2dw9nvgf05f74", + "wall_lr51hh174yds8qf0", + "wall_pantry_curve_0", + "wall_pantry_curve_1", + "wall_pantry_curve_2", + "wall_pantry_curve_3", + "wall_pantry_curve_4", + "wall_pantry_curve_5", + "wall_pantry_curve_6", + "wall_pantry_curve_7", + "wall_pantry_curve_8", + "wall_pantry_straight_up", + "wall_entree_bedrijf_divider", + "wall_ieo9uj0cwt81g175", + "wall_fu6locmeulfldl2i", + "wall_7nfm2ln7gcf7qv7m", + "wall_gboq443n36v16ruv", + "slab_zumez0wd9qt49kqo" + ], + "parentId": null, + "height": 2.5 + }, + "slab_zumez0wd9qt49kqo": { + "id": "slab_zumez0wd9qt49kqo", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[11.39, 0], [8.79, 7.4], [0, 7.4], [0, 0]], + "visible": true, + "parentId": "level_v7ocab71p8y3f2x9", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_7nfm2ln7gcf7qv7m": { + "id": "wall_7nfm2ln7gcf7qv7m", + "end": [6.38, 3.03], + "type": "wall", + "start": [6.38, 0], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_9kl2dw9nvgf05f74": { + "id": "wall_9kl2dw9nvgf05f74", + "end": [8, 4.5], + "type": "wall", + "start": [8, 5], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_entree_bedrijf_divider": { + "id": "wall_entree_bedrijf_divider", + "end": [4.89, 4.5], + "type": "wall", + "start": [4.89, 3.03], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_front_diagonal": { + "id": "wall_front_diagonal", + "end": [8.79, 7.4], + "type": "wall", + "start": [11.39, 0], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_fu6locmeulfldl2i": { + "id": "wall_fu6locmeulfldl2i", + "end": [6.38, 1], + "type": "wall", + "start": [4.89, 1], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_gboq443n36v16ruv": { + "id": "wall_gboq443n36v16ruv", + "end": [6.38, 3.03], + "type": "wall", + "start": [4.89, 3.03], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_ieo9uj0cwt81g175": { + "id": "wall_ieo9uj0cwt81g175", + "end": [4.89, 3.03], + "type": "wall", + "start": [4.89, 0], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_kantoor_left": { + "id": "wall_kantoor_left", + "end": [6.38, 3.03], + "type": "wall", + "start": [6.38, 0], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_kantoor_top": { + "id": "wall_kantoor_top", + "end": [10.33, 3.03], + "type": "wall", + "start": [6.38, 3.03], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_long_side": { + "id": "wall_long_side", + "end": [0, 0], + "type": "wall", + "start": [11.39, 0], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "exterior" + }, + "wall_lr51hh174yds8qf0": { + "id": "wall_lr51hh174yds8qf0", + "end": [8, 4.5], + "type": "wall", + "start": [4.89, 4.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_north_closing": { + "id": "wall_north_closing", + "end": [8.79, 7.4], + "type": "wall", + "start": [0, 7.4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "exterior" + }, + "wall_opslag_wc_divider": { + "id": "wall_opslag_wc_divider", + "end": [6.38, 1], + "type": "wall", + "start": [4.89, 1], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_opslag_wc_left": { + "id": "wall_opslag_wc_left", + "end": [4.89, 3.03], + "type": "wall", + "start": [4.89, 0], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_opslag_wc_top": { + "id": "wall_opslag_wc_top", + "end": [6.38, 3.03], + "type": "wall", + "start": [4.89, 3.03], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_curve_0": { + "id": "wall_pantry_curve_0", + "end": [4.57, 4.53], + "type": "wall", + "start": [4.89, 4.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "unknown" + }, + "wall_pantry_curve_1": { + "id": "wall_pantry_curve_1", + "end": [4.26, 4.61], + "type": "wall", + "start": [4.57, 4.53], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_curve_2": { + "id": "wall_pantry_curve_2", + "end": [3.97, 4.75], + "type": "wall", + "start": [4.26, 4.61], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_curve_3": { + "id": "wall_pantry_curve_3", + "end": [3.71, 4.93], + "type": "wall", + "start": [3.97, 4.75], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_curve_4": { + "id": "wall_pantry_curve_4", + "end": [3.49, 5.15], + "type": "wall", + "start": [3.71, 4.93], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_curve_5": { + "id": "wall_pantry_curve_5", + "end": [3.31, 5.42], + "type": "wall", + "start": [3.49, 5.15], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_curve_6": { + "id": "wall_pantry_curve_6", + "end": [3.17, 5.7], + "type": "wall", + "start": [3.31, 5.42], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_curve_7": { + "id": "wall_pantry_curve_7", + "end": [3.09, 6.01], + "type": "wall", + "start": [3.17, 5.7], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "unknown" + }, + "wall_pantry_curve_8": { + "id": "wall_pantry_curve_8", + "end": [3.06, 6.33], + "type": "wall", + "start": [3.09, 6.01], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_pantry_straight_up": { + "id": "wall_pantry_straight_up", + "end": [3.06, 7.4], + "type": "wall", + "start": [3.06, 6.33], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "interior" + }, + "wall_short_back": { + "id": "wall_short_back", + "end": [0, 7.4], + "type": "wall", + "start": [0, 0], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "exterior" + }, + "wall_w870xc7popsgkznm": { + "id": "wall_w870xc7popsgkznm", + "end": [8, 5], + "type": "wall", + "start": [9.25091677503251, 6.088159947984396], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_v7ocab71p8y3f2x9", + "frontSide": "unknown" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-20-level_uqfel9edw0c08f4a.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-20-level_uqfel9edw0c08f4a.json new file mode 100644 index 0000000000..01073733e7 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-20-level_uqfel9edw0c08f4a.json @@ -0,0 +1,272 @@ +{ + "sceneId": "scene-20", + "levelId": "level_uqfel9edw0c08f4a", + "nodes": { + "level_uqfel9edw0c08f4a": { + "id": "level_uqfel9edw0c08f4a", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_ncien6xv4o1w3dfj", + "wall_0tz1q35to1wv5pv6", + "wall_cqth7cnwnfrb6492", + "wall_zhh9qir7zcop0xfp", + "wall_ophxjooa01vkvsm0", + "wall_n68stiluirzeyg61", + "wall_xbxwbm1l28wuhkc5", + "wall_ccc522ajhmx9ky6z", + "wall_i25l409mafg6g72k", + "wall_nsw3fxv2nwengxre", + "wall_qmzuics3ov8o4252", + "slab_ocmsp820vzxdlrkh", + "wall_b20hio6ih5ahwihc", + "wall_9ke4xeg01450ql35", + "wall_k8wikbt4c0xhxx7x", + "wall_9sl40wkygklyuaep", + "wall_vzi3rcs4z9hoh008" + ], + "parentId": null, + "height": 2.55 + }, + "slab_ocmsp820vzxdlrkh": { + "id": "slab_ocmsp820vzxdlrkh", + "type": "slab", + "holes": [ + [[-5, 4], [0, 4], [0, 9], [-5, 9]], + [[-6, 6], [-5, 6], [-5, 9], [-6, 9]], + [ + [-6.068860711814562, 5.8296816001146885], + [-5.068860711814562, 5.8296816001146885], + [-5.068860711814562, 8.82968160011469], + [-6.068860711814562, 8.82968160011469] + ] + ], + "object": "node", + "polygon": [ + [-12, 14], + [-12, -1], + [5, -1], + [5, 12], + [-1, 12], + [-1, 11], + [-4, 11], + [-4, 12], + [-6, 12], + [-6, 13.5], + [-11, 14] + ], + "visible": true, + "parentId": "level_uqfel9edw0c08f4a", + "elevation": 0.05, + "holeMetadata": [ + { + "source": "manual" + }, + { + "source": "stair", + "stairId": "stair_om7h9qv5abttuzog" + }, + { + "source": "stair", + "stairId": "stair_ghpzl1h6uwh4uggg" + } + ], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_0tz1q35to1wv5pv6": { + "id": "wall_0tz1q35to1wv5pv6", + "end": [-6, 12], + "type": "wall", + "start": [-6, 13.5], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_9ke4xeg01450ql35": { + "id": "wall_9ke4xeg01450ql35", + "end": [0, 4], + "type": "wall", + "start": [0, 9], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "unknown" + }, + "wall_9sl40wkygklyuaep": { + "id": "wall_9sl40wkygklyuaep", + "end": [-5, 9], + "type": "wall", + "start": [-5, 4], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "unknown" + }, + "wall_b20hio6ih5ahwihc": { + "id": "wall_b20hio6ih5ahwihc", + "end": [0, 9], + "type": "wall", + "start": [-4, 9], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "unknown" + }, + "wall_ccc522ajhmx9ky6z": { + "id": "wall_ccc522ajhmx9ky6z", + "end": [5, -1], + "type": "wall", + "start": [5, 12], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_cqth7cnwnfrb6492": { + "id": "wall_cqth7cnwnfrb6492", + "end": [-4, 12], + "type": "wall", + "start": [-6, 12], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_i25l409mafg6g72k": { + "id": "wall_i25l409mafg6g72k", + "end": [-12, -1], + "type": "wall", + "start": [5, -1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_k8wikbt4c0xhxx7x": { + "id": "wall_k8wikbt4c0xhxx7x", + "end": [-5, 4], + "type": "wall", + "start": [0, 4], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "unknown" + }, + "wall_n68stiluirzeyg61": { + "id": "wall_n68stiluirzeyg61", + "end": [-1, 12], + "type": "wall", + "start": [-1, 11], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_ncien6xv4o1w3dfj": { + "id": "wall_ncien6xv4o1w3dfj", + "end": [-6, 13.5], + "type": "wall", + "start": [-11, 14], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_nsw3fxv2nwengxre": { + "id": "wall_nsw3fxv2nwengxre", + "end": [-12, 14], + "type": "wall", + "start": [-12, -1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_ophxjooa01vkvsm0": { + "id": "wall_ophxjooa01vkvsm0", + "end": [-1, 11], + "type": "wall", + "start": [-4, 11], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_qmzuics3ov8o4252": { + "id": "wall_qmzuics3ov8o4252", + "end": [-11, 14], + "type": "wall", + "start": [-12, 14], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_vzi3rcs4z9hoh008": { + "id": "wall_vzi3rcs4z9hoh008", + "end": [-4, 9], + "type": "wall", + "start": [-5, 9], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "unknown" + }, + "wall_xbxwbm1l28wuhkc5": { + "id": "wall_xbxwbm1l28wuhkc5", + "end": [5, 12], + "type": "wall", + "start": [-1, 12], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + }, + "wall_zhh9qir7zcop0xfp": { + "id": "wall_zhh9qir7zcop0xfp", + "end": [-4, 11], + "type": "wall", + "start": [-4, 12], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_uqfel9edw0c08f4a", + "frontSide": "exterior" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-23-level_588ekegw4cj0g7zn.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-23-level_588ekegw4cj0g7zn.json new file mode 100644 index 0000000000..cfa7aa1171 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-23-level_588ekegw4cj0g7zn.json @@ -0,0 +1,276 @@ +{ + "sceneId": "scene-23", + "levelId": "level_588ekegw4cj0g7zn", + "nodes": { + "level_588ekegw4cj0g7zn": { + "id": "level_588ekegw4cj0g7zn", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_heffy9lim24uaif0", + "wall_y5trr3z97i1wp8dw", + "wall_zjn4qajgdnklaxae", + "wall_0c3shw5zcb2xi1zw", + "slab_b46cpczut59zpxqp", + "wall_wsx5hvcmoid6umg4", + "wall_1gldjx57j80lrjfm", + "wall_cent2hmha2gty5gi", + "wall_geec5catb66d04md", + "wall_lwt0o04at8kdynm2", + "wall_tszr229prtnr7q8y", + "wall_7bvokfrbiwfthm3e", + "wall_y0oj1xc13nucan20" + ], + "parentId": null, + "height": 2.55 + }, + "slab_b46cpczut59zpxqp": { + "id": "slab_b46cpczut59zpxqp", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 5.5, + 12.5 + ], + [ + 3.5, + 14 + ], + [ + 1.5, + 12 + ], + [ + 4, + 10.5 + ] + ], + "visible": true, + "parentId": "level_588ekegw4cj0g7zn", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_0c3shw5zcb2xi1zw": { + "id": "wall_0c3shw5zcb2xi1zw", + "end": [ + 3.5, + 14 + ], + "type": "wall", + "start": [ + 1.5, + 12 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "exterior" + }, + "wall_1gldjx57j80lrjfm": { + "id": "wall_1gldjx57j80lrjfm", + "end": [ + -8, + 12.035355339059327 + ], + "type": "wall", + "start": [ + 1, + 19 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "unknown" + }, + "wall_7bvokfrbiwfthm3e": { + "id": "wall_7bvokfrbiwfthm3e", + "end": [ + 6.5, + 8.538411063979868 + ], + "type": "wall", + "start": [ + 1.0306001504247313, + 13 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "interior" + }, + "wall_cent2hmha2gty5gi": { + "id": "wall_cent2hmha2gty5gi", + "end": [ + -5.5, + -20 + ], + "type": "wall", + "start": [ + -8, + 12.035355339059327 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "unknown" + }, + "wall_geec5catb66d04md": { + "id": "wall_geec5catb66d04md", + "end": [ + 9.5, + 2 + ], + "type": "wall", + "start": [ + -5.5, + -20 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "unknown" + }, + "wall_heffy9lim24uaif0": { + "id": "wall_heffy9lim24uaif0", + "end": [ + 5.5, + 12.5 + ], + "type": "wall", + "start": [ + 3.5, + 14 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "exterior" + }, + "wall_lwt0o04at8kdynm2": { + "id": "wall_lwt0o04at8kdynm2", + "end": [ + -6.5, + 6.5 + ], + "type": "wall", + "start": [ + 9.5, + 2 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "unknown" + }, + "wall_tszr229prtnr7q8y": { + "id": "wall_tszr229prtnr7q8y", + "end": [ + 1.0306001504247313, + 13 + ], + "type": "wall", + "start": [ + -6.5, + 6.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "unknown" + }, + "wall_wsx5hvcmoid6umg4": { + "id": "wall_wsx5hvcmoid6umg4", + "end": [ + 1, + 19 + ], + "type": "wall", + "start": [ + 3.5, + 14 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "unknown" + }, + "wall_y0oj1xc13nucan20": { + "id": "wall_y0oj1xc13nucan20", + "end": [ + 8, + 11.964644660940673 + ], + "type": "wall", + "start": [ + 6.5, + 8.538411063979868 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "unknown" + }, + "wall_y5trr3z97i1wp8dw": { + "id": "wall_y5trr3z97i1wp8dw", + "end": [ + 4, + 10.5 + ], + "type": "wall", + "start": [ + 5.5, + 12.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "exterior" + }, + "wall_zjn4qajgdnklaxae": { + "id": "wall_zjn4qajgdnklaxae", + "end": [ + 1.5, + 12 + ], + "type": "wall", + "start": [ + 4, + 10.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_588ekegw4cj0g7zn", + "frontSide": "exterior" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_jwi4ovhyra2ayxa5.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_jwi4ovhyra2ayxa5.json new file mode 100644 index 0000000000..e57a46e952 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_jwi4ovhyra2ayxa5.json @@ -0,0 +1,1310 @@ +{ + "sceneId": "scene-25", + "levelId": "level_jwi4ovhyra2ayxa5", + "nodes": { + "level_jwi4ovhyra2ayxa5": { + "id": "level_jwi4ovhyra2ayxa5", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_ggq4ktwq1dux6fyt", + "wall_wtol3dwpvti9e46r", + "wall_da9oykth6374xc04", + "wall_pas1to84v9n0m95x", + "wall_l3915ls9pmo121yd", + "wall_kgc359p91o9vu4jf", + "wall_0gb1d6ahxgp413zc", + "wall_tqgmqh6h4ua4csss", + "wall_vfbzoo2jfrx4um5v", + "wall_6kahn8f9drv85wf3", + "wall_zzckoo3l2qz8j4il", + "wall_ovpjmscb9a1b9a2t", + "wall_ed7diphapsqo8s61", + "wall_0e9fl70a13qct144", + "wall_86ewze93o1ltt97e", + "wall_x9ypfzv087srj3sa", + "wall_c783g0mjvk11z4he", + "slab_6bz49p0t54lhed0b", + "wall_mllg8azs8a6ioawp", + "wall_68ubh6h97o5p7uy1", + "slab_cobke98zzw6s1nn4", + "wall_yw7se4h029auzwpp", + "wall_56m0cuwykjwedx2y", + "wall_sx5zae3ghhwcqwgj", + "wall_grk3h1cdzdwzqwq0", + "wall_kboist75tx0yclsj", + "wall_6p6q7ojfk0w3rb2j", + "wall_ksadcg2ce927liir", + "wall_zjgzjefvm0lq42lz", + "wall_4dnlh79bzdiae0sq", + "wall_f7xrwr89tabb5efe", + "wall_mwyxv9b3rfowofji", + "wall_26boz82osancl83q", + "wall_anht1qu7cogpkuwm", + "wall_mmre8pc5z97n50qq", + "wall_2imfqx9i7jz0f395", + "wall_2em2iq7conys010y", + "wall_3pgmxyzcrh8fm98n", + "wall_enlotq535xb2wr1n", + "wall_sb1htk6ldsnww2rs", + "wall_0x6pyd7f9i0pkovy", + "slab_2nwb8q0ftk36nbf7", + "wall_ewwsw5poeuvm0tx1", + "wall_ajpub52u40uarw15", + "wall_3dnorvmxttkul8tq", + "slab_nw3emd6bf39suew0", + "wall_6ncyul3cne6oe6dd", + "wall_5wkkedxs0q3txdj4", + "wall_p9w2qs46hq94ryrc", + "wall_qiicjv7etfiqy4mu", + "wall_5z51yd0bpjpuammm", + "slab_y1lif8w12nbrd26c", + "wall_yeg1kiodxdswfdw6", + "wall_kn8qrdj8iiaamqg7", + "slab_ntnpya4cchpb6zoc", + "wall_3ikgawurktd6eblq", + "slab_s7i7vt5t75qk3sly", + "slab_qpp5xmqvhbnm0qe7", + "wall_fyzlbqnl1k7obrfe", + "slab_970excfvw4z2e4xb" + ], + "parentId": null, + "height": 3.0999999999999996 + }, + "slab_2nwb8q0ftk36nbf7": { + "id": "slab_2nwb8q0ftk36nbf7", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -9.000000000000187, + 2.8108541965484406 + ], + [ + -9.000000000000059, + 0.8869842290878014 + ], + [ + -7.223806858062903, + 0.8869842290887842 + ], + [ + -7.223806858038787, + -0.7007928773076871 + ], + [ + -6.11591425221425, + -0.7025892717503204 + ], + [ + -6.11591425221425, + -0.27700793743133545 + ], + [ + -5.761000063419633, + -0.6319596084139787 + ], + [ + -4.734156851237435, + 0.3996799170438435 + ], + [ + -5.126632743238916, + 0.7921558090453247 + ], + [ + -4.6000000000000005, + 0.7921558090453247 + ], + [ + -4.6000000000000005, + 2.810854196548462 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_6bz49p0t54lhed0b": { + "id": "slab_6bz49p0t54lhed0b", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -8.8, + -2.4000000000000004 + ], + [ + -12.100000000000001, + -2.4000000000000004 + ], + [ + -12.100000000000001, + -6.8500000000000005 + ], + [ + -8.8, + -6.8500000000000005 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_970excfvw4z2e4xb": { + "id": "slab_970excfvw4z2e4xb", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -7.223806858062903, + 0.8869842290887842 + ], + [ + -9.058632850646973, + 0.8869842290878223 + ], + [ + -9.076211929321289, + -0.7000000000000001 + ], + [ + -7.223806858038787, + -0.7007928773076871 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_cobke98zzw6s1nn4": { + "id": "slab_cobke98zzw6s1nn4", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -11.200000000000001, + -2.4000000000000004 + ], + [ + -7.814762020111084, + -2.4000000000000004 + ], + [ + -7.814762020111084, + -0.7000000000000001 + ], + [ + -11.200000000000001, + -0.7000000000000002 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_ntnpya4cchpb6zoc": { + "id": "slab_ntnpya4cchpb6zoc", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 7.091630935668945, + -5.7688798904418945 + ], + [ + 11.55, + -5.767512321472168 + ], + [ + 11.55, + -1.8537885665893552 + ], + [ + 7.091630935668945, + -1.8537885665893554 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_nw3emd6bf39suew0": { + "id": "slab_nw3emd6bf39suew0", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -4.599999999999999, + 12.85 + ], + [ + -12.200000000000001, + 12.850000000000001 + ], + [ + -12.231832478518283, + 2.810854195235583 + ], + [ + -4.6000000000000005, + 2.810854196548462 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_qpp5xmqvhbnm0qe7": { + "id": "slab_qpp5xmqvhbnm0qe7", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -9.000000000000187, + 2.8108541965484406 + ], + [ + -11.2000000000133, + 2.8108541956175594 + ], + [ + -11.200000000000001, + -0.7000000000000002 + ], + [ + -9.076211929321289, + -0.7000000000000001 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_s7i7vt5t75qk3sly": { + "id": "slab_s7i7vt5t75qk3sly", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 4.783884525299086, + -8.999448004653555 + ], + [ + 9.759352516125972, + -8.998549529499122 + ], + [ + 9.75935388950353, + -5.768076699732677 + ], + [ + 4.783884525299072, + -5.7688798904418945 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "slab_y1lif8w12nbrd26c": { + "id": "slab_y1lif8w12nbrd26c", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 9.759352516125972, + -8.998549529499122 + ], + [ + 11.55, + -8.998152923583985 + ], + [ + 11.55, + -5.767512321472168 + ], + [ + 9.75935388950353, + -5.768076699732677 + ] + ], + "visible": true, + "parentId": "level_jwi4ovhyra2ayxa5", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_0e9fl70a13qct144": { + "id": "wall_0e9fl70a13qct144", + "end": [ + 1.9000000000000001, + -10.8 + ], + "type": "wall", + "start": [ + -4.65, + -10.8 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_0gb1d6ahxgp413zc": { + "id": "wall_0gb1d6ahxgp413zc", + "end": [ + -8.8, + -2.4000000000000004 + ], + "type": "wall", + "start": [ + -11.200000000000001, + -2.4000000000000004 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_0x6pyd7f9i0pkovy": { + "id": "wall_0x6pyd7f9i0pkovy", + "end": [ + -5.126632743238916, + 0.7921558090453247 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 0.7921558090453247 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_26boz82osancl83q": { + "id": "wall_26boz82osancl83q", + "end": [ + -5.486989659835972, + -0.7035478371444067 + ], + "type": "wall", + "start": [ + -7.814762020111084, + -0.7000000000000001 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_2em2iq7conys010y": { + "id": "wall_2em2iq7conys010y", + "end": [ + -5.831732471724514, + -0.7030224028819513 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 0.5344634056091311 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_2imfqx9i7jz0f395": { + "id": "wall_2imfqx9i7jz0f395", + "end": [ + -9.000000000000059, + 0.8869842290878014 + ], + "type": "wall", + "start": [ + -7.223806858062903, + 0.8869842290887842 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "unknown" + }, + "wall_3dnorvmxttkul8tq": { + "id": "wall_3dnorvmxttkul8tq", + "end": [ + -12.231832478518283, + 2.810854195235583 + ], + "type": "wall", + "start": [ + -9.000000000000187, + 2.8108541965484406 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "unknown" + }, + "wall_3ikgawurktd6eblq": { + "id": "wall_3ikgawurktd6eblq", + "end": [ + 4.783884525299086, + -8.999448004653555 + ], + "type": "wall", + "start": [ + 4.783884525299072, + -5.7688798904418945 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior", + "height": 2.5 + }, + "wall_3pgmxyzcrh8fm98n": { + "id": "wall_3pgmxyzcrh8fm98n", + "end": [ + -6.11591425221425, + -0.27700793743133545 + ], + "type": "wall", + "start": [ + -6.11591425221425, + -0.7025892717503204 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior", + "height": 2.5 + }, + "wall_4dnlh79bzdiae0sq": { + "id": "wall_4dnlh79bzdiae0sq", + "end": [ + -1.148022018724731, + 2.19981793740085 + ], + "type": "wall", + "start": [ + 2.7, + 2.2 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_56m0cuwykjwedx2y": { + "id": "wall_56m0cuwykjwedx2y", + "end": [ + 1.9000000000000001, + -9 + ], + "type": "wall", + "slots": { + "exterior": "library:flooring-greenlabradorite" + }, + "start": [ + 11.55, + -8.998152923583985 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_5wkkedxs0q3txdj4": { + "id": "wall_5wkkedxs0q3txdj4", + "end": [ + 4.783884525299072, + -5.7688798904418945 + ], + "type": "wall", + "start": [ + 6.529563903808594, + -5.7688798904418945 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior", + "height": 2.5 + }, + "wall_5z51yd0bpjpuammm": { + "id": "wall_5z51yd0bpjpuammm", + "end": [ + 9.759352516125972, + -8.998549529499122 + ], + "type": "wall", + "start": [ + 9.75935388950353, + -5.768076699732677 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior", + "height": 2.5 + }, + "wall_68ubh6h97o5p7uy1": { + "id": "wall_68ubh6h97o5p7uy1", + "end": [ + -7.814762020111084, + -2.4000000000000004 + ], + "type": "wall", + "start": [ + -7.814762020111084, + -0.7000000000000001 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_6kahn8f9drv85wf3": { + "id": "wall_6kahn8f9drv85wf3", + "end": [ + -8.8, + -10.6 + ], + "type": "wall", + "slots": {}, + "start": [ + -8.8, + -6.850000000000001 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_6ncyul3cne6oe6dd": { + "id": "wall_6ncyul3cne6oe6dd", + "end": [ + 11.55, + -5.767512321472168 + ], + "type": "wall", + "start": [ + 6.529563903808594, + -5.7688798904418945 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior", + "height": 2.5 + }, + "wall_6p6q7ojfk0w3rb2j": { + "id": "wall_6p6q7ojfk0w3rb2j", + "end": [ + -3.7828824995228247, + 2.9499636829170583 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_86ewze93o1ltt97e": { + "id": "wall_86ewze93o1ltt97e", + "end": [ + 2.7, + -1.8537885665893556 + ], + "type": "wall", + "start": [ + 2.7, + 2.2 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_ajpub52u40uarw15": { + "id": "wall_ajpub52u40uarw15", + "end": [ + -9.058632850646973, + 0.8869842290878223 + ], + "type": "wall", + "start": [ + -9.000000000000059, + 0.8869842290878014 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_anht1qu7cogpkuwm": { + "id": "wall_anht1qu7cogpkuwm", + "end": [ + -5.486989659835972, + -0.7035478371444067 + ], + "type": "wall", + "start": [ + -4.5726423548447475, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior", + "curveOffset": 0.15090909119238677 + }, + "wall_c783g0mjvk11z4he": { + "id": "wall_c783g0mjvk11z4he", + "end": [ + 11.55, + -1.8537885665893552 + ], + "type": "wall", + "start": [ + 2.7, + -1.8537885665893556 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_da9oykth6374xc04": { + "id": "wall_da9oykth6374xc04", + "end": [ + -11.200000000000001, + -2.4000000000000004 + ], + "type": "wall", + "start": [ + -11.200000000000001, + -0.7000000000000002 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_ed7diphapsqo8s61": { + "id": "wall_ed7diphapsqo8s61", + "end": [ + -4.65, + -10.8 + ], + "type": "wall", + "start": [ + -4.65, + -10.6 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_enlotq535xb2wr1n": { + "id": "wall_enlotq535xb2wr1n", + "end": [ + -6.11591425221425, + -0.27700793743133545 + ], + "type": "wall", + "start": [ + -5.761000063419633, + -0.6319596084139787 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_ewwsw5poeuvm0tx1": { + "id": "wall_ewwsw5poeuvm0tx1", + "end": [ + -9.000000000000059, + 0.8869842290878014 + ], + "type": "wall", + "start": [ + -9.000000000000187, + 2.8108541965484406 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_f7xrwr89tabb5efe": { + "id": "wall_f7xrwr89tabb5efe", + "end": [ + -1.15, + 0.2025934915056129 + ], + "type": "wall", + "start": [ + -1.1500000000000001, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_fyzlbqnl1k7obrfe": { + "id": "wall_fyzlbqnl1k7obrfe", + "end": [ + -9.076211929321289, + -0.7000000000000001 + ], + "type": "wall", + "start": [ + -9.058632850646973, + 0.8869842290878223 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_ggq4ktwq1dux6fyt": { + "id": "wall_ggq4ktwq1dux6fyt", + "end": [ + -4.599999999999999, + 12.85 + ], + "type": "wall", + "start": [ + -12.200000000000001, + 12.850000000000001 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_grk3h1cdzdwzqwq0": { + "id": "wall_grk3h1cdzdwzqwq0", + "end": [ + -4.599999999999999, + 12.85 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_kboist75tx0yclsj": { + "id": "wall_kboist75tx0yclsj", + "end": [ + -4.5726423548447475, + 0.5 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_kgc359p91o9vu4jf": { + "id": "wall_kgc359p91o9vu4jf", + "end": [ + -8.8, + -6.8500000000000005 + ], + "type": "wall", + "start": [ + -12.100000000000001, + -6.8500000000000005 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_kn8qrdj8iiaamqg7": { + "id": "wall_kn8qrdj8iiaamqg7", + "end": [ + 7.091630935668945, + -1.8537885665893554 + ], + "type": "wall", + "start": [ + 7.091630935668945, + -5.7688798904418945 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior", + "height": 2.5 + }, + "wall_ksadcg2ce927liir": { + "id": "wall_ksadcg2ce927liir", + "end": [ + -1.9504812955856323, + 2.9499636829170583 + ], + "type": "wall", + "start": [ + -3.7828824995228247, + 2.9499636829170583 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_l3915ls9pmo121yd": { + "id": "wall_l3915ls9pmo121yd", + "end": [ + -12.100000000000001, + -6.8500000000000005 + ], + "type": "wall", + "start": [ + -12.100000000000001, + -2.4000000000000004 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_mllg8azs8a6ioawp": { + "id": "wall_mllg8azs8a6ioawp", + "end": [ + -7.814762020111084, + -0.7000000000000001 + ], + "type": "wall", + "start": [ + -11.200000000000001, + -0.7000000000000002 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_mmre8pc5z97n50qq": { + "id": "wall_mmre8pc5z97n50qq", + "end": [ + -7.223806858038787, + -0.7007928773076871 + ], + "type": "wall", + "start": [ + -7.223806858062903, + 0.8869842290887842 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "unknown" + }, + "wall_mwyxv9b3rfowofji": { + "id": "wall_mwyxv9b3rfowofji", + "end": [ + -9.000000000000187, + 2.8108541965484406 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 2.810854196548462 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_ovpjmscb9a1b9a2t": { + "id": "wall_ovpjmscb9a1b9a2t", + "end": [ + -4.65, + -10.6 + ], + "type": "wall", + "start": [ + -8.8, + -10.6 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_p9w2qs46hq94ryrc": { + "id": "wall_p9w2qs46hq94ryrc", + "end": [ + 1.8887628627977606, + -5.80003946087802 + ], + "type": "wall", + "start": [ + 1.9000000000000001, + -9 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "unknown" + }, + "wall_pas1to84v9n0m95x": { + "id": "wall_pas1to84v9n0m95x", + "end": [ + -12.100000000000001, + -2.4000000000000004 + ], + "type": "wall", + "start": [ + -11.200000000000001, + -2.4000000000000004 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_qiicjv7etfiqy4mu": { + "id": "wall_qiicjv7etfiqy4mu", + "end": [ + -0.23728897082305372, + -4.722300492978068 + ], + "type": "wall", + "start": [ + -1.15, + 0.2025934915056129 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "unknown", + "curveOffset": -0.9278769448361599 + }, + "wall_sb1htk6ldsnww2rs": { + "id": "wall_sb1htk6ldsnww2rs", + "end": [ + -5.126632743238916, + 0.7921558090453247 + ], + "type": "wall", + "start": [ + -4.734156851237435, + 0.3996799170438435 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_sx5zae3ghhwcqwgj": { + "id": "wall_sx5zae3ghhwcqwgj", + "end": [ + 11.55, + -8.998152923583985 + ], + "type": "wall", + "slots": { + "exterior": "library:wood-floorplank1" + }, + "start": [ + 11.55, + -1.8537885665893552 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior", + "curveOffset": 0 + }, + "wall_tqgmqh6h4ua4csss": { + "id": "wall_tqgmqh6h4ua4csss", + "end": [ + -7.814762020111084, + -2.4000000000000004 + ], + "type": "wall", + "start": [ + -8.8, + -2.4000000000000004 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_vfbzoo2jfrx4um5v": { + "id": "wall_vfbzoo2jfrx4um5v", + "end": [ + -8.8, + -2.4000000000000004 + ], + "type": "wall", + "start": [ + -8.8, + -6.8500000000000005 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_wtol3dwpvti9e46r": { + "id": "wall_wtol3dwpvti9e46r", + "end": [ + -11.2000000000133, + 2.8108541956175594 + ], + "type": "wall", + "start": [ + -11.200000000000001, + -0.7000000000000002 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_x9ypfzv087srj3sa": { + "id": "wall_x9ypfzv087srj3sa", + "end": [ + -12.231832478518283, + 2.810854195235583 + ], + "type": "wall", + "start": [ + -12.200000000000001, + 12.850000000000001 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "interior" + }, + "wall_yeg1kiodxdswfdw6": { + "id": "wall_yeg1kiodxdswfdw6", + "end": [ + -0.034882090985774994, + -1.2649297505617147 + ], + "type": "wall", + "start": [ + 2.7, + -1.2649297505617143 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "unknown" + }, + "wall_yw7se4h029auzwpp": { + "id": "wall_yw7se4h029auzwpp", + "end": [ + 1.9000000000000001, + -10.8 + ], + "type": "wall", + "start": [ + 1.9000000000000001, + -9 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_zjgzjefvm0lq42lz": { + "id": "wall_zjgzjefvm0lq42lz", + "end": [ + -1.1500000000000001, + 2.478200674057007 + ], + "type": "wall", + "start": [ + -1.9504812955856323, + 2.9499636829170583 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + }, + "wall_zzckoo3l2qz8j4il": { + "id": "wall_zzckoo3l2qz8j4il", + "end": [ + 2.7, + -0.6760709345340729 + ], + "type": "wall", + "start": [ + 2.7, + -1.8537885665893556 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_jwi4ovhyra2ayxa5", + "frontSide": "exterior" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_tf1ug5dswkkzfhqa.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_tf1ug5dswkkzfhqa.json new file mode 100644 index 0000000000..3a0c8428bd --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-25-level_tf1ug5dswkkzfhqa.json @@ -0,0 +1,1618 @@ +{ + "sceneId": "scene-25", + "levelId": "level_tf1ug5dswkkzfhqa", + "nodes": { + "level_tf1ug5dswkkzfhqa": { + "id": "level_tf1ug5dswkkzfhqa", + "type": "level", + "level": 0, + "object": "node", + "visible": true, + "children": [ + "wall_zgt30hblc7v8tpgm", + "wall_hr0630nj7o336vix", + "wall_e71f2dnudh7lpb9v", + "wall_5ld53lqd7tpg14f9", + "wall_ennfhed1hm0ozhch", + "wall_bajfw4fffv5qrf1m", + "wall_7q0igcgudqsf4mr6", + "wall_gyt1819erxgrqv3o", + "wall_x1eelmdpg7hie8kj", + "wall_ag4xz82fkzfty3lt", + "wall_twjrbha7gdx24q8c", + "wall_c8lo4kz4h0mef9yv", + "wall_a22dlcqask9o3nol", + "wall_bvgcs7isi2dii2f7", + "wall_ufsbh2cunaf4y1e0", + "wall_s66g0kh4jhxlsyq0", + "slab_psj8d6m16r1qmo1m", + "wall_d9ubvuzym6v4hhgh", + "wall_za20294gpb6ma8jv", + "wall_ard5a93tnt3wzzh6", + "wall_nqx2se3a3eksgajk", + "wall_t5r91noa0eqdilf0", + "wall_jwjfg77bupgbeu5g", + "wall_5e74bbgfng06ij2v", + "wall_quidxtcw6lptgpwy", + "wall_l8qn4aqt4icpw6ns", + "wall_ug8avwqdyx3b3b4g", + "wall_10gbw3k0x20sn9cl", + "slab_7izk7ggo5220wpog", + "slab_7936g4twb2b0xwgv", + "wall_05rljsjpvpxg0lge", + "wall_c49yron9q7wp47gy", + "wall_c5weyuht6kkyqsqg", + "slab_4jl17grwbmfn2yys", + "wall_mf2tvbp1smse6ky8", + "wall_2g8ek360ils5c6zv", + "wall_l367nzmgae9uy0x9", + "slab_kcv6gjb1ixdq6ynv", + "slab_s0223sj8ugjhndz4", + "wall_jwqeqwq5umuy1gvb", + "wall_cam2tmtozlfrbqk5", + "wall_mxzqxt9rr1aj40vk", + "slab_4fjk88w8ijnamdew", + "wall_t55sg3hswku5lyn1", + "wall_zn79e6063xs4hvcx", + "wall_d3wyhmj78a494vn8", + "wall_5n6y2car6g6iqu9q", + "wall_bx0jgl87dfzvr5gm", + "slab_5ze6c8k4v8o1qax6", + "wall_jws800cwpjvjof8c", + "wall_9vcv6ze2rar0kllo", + "slab_axv0fq90ynuhloou", + "wall_53nehkzmn7sbp3xo", + "wall_xw95gtjcz7sa1l83", + "wall_zh5et7jn3upvz0ah", + "slab_fz3dmbmcovgmfxlk" + ], + "parentId": null, + "height": 3.3400000000000003 + }, + "slab_4fjk88w8ijnamdew": { + "id": "slab_4fjk88w8ijnamdew", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -10.475817298889162, + 0.39999999999999725 + ], + [ + -8.8, + 0.3999999999999977 + ], + [ + -8.8, + 3.572127914428711 + ], + [ + -10.475817298889162, + 3.572127914428711 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_4jl17grwbmfn2yys": { + "id": "slab_4jl17grwbmfn2yys", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 11.55, + -1.8474719047546384 + ], + [ + 9.178149236673338, + -1.8491648063585198 + ], + [ + 9.178149236673104, + -8.998606912144322 + ], + [ + 11.55, + -8.998152923583985 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_5ze6c8k4v8o1qax6": { + "id": "slab_5ze6c8k4v8o1qax6", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -4.6000000000000005, + 3.572127914428711 + ], + [ + -8.8, + 3.572127914428711 + ], + [ + -8.8, + -0.7000000000000001 + ], + [ + -6.9500020088242245, + -0.7000000000000001 + ], + [ + -8.8, + -0.7000000000000001 + ], + [ + -8.8, + -3.4439198970794678 + ], + [ + -6.9500020088242245, + -3.443919897079468 + ], + [ + -6.9500020088242245, + -0.701318010189226 + ], + [ + -5.499983667651276, + -0.703364993579402 + ], + [ + -5.194731124407848, + 0.02039822004501335 + ], + [ + -4.5726423548447475, + 0.5 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_7936g4twb2b0xwgv": { + "id": "slab_7936g4twb2b0xwgv", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 9.178149236673104, + -8.998606912144322 + ], + [ + 9.178149236673338, + -1.8491648063585198 + ], + [ + 2.7, + -1.8537885665893556 + ], + [ + 2.7213549137115485, + -5.712312030792238 + ], + [ + 4.061796402931213, + -5.712312030792238 + ], + [ + 4.539406940462225, + -5.516841135700492 + ], + [ + 4.720740795135498, + -5.03368616104126 + ], + [ + 4.720740795135498, + -3.2969822883605957 + ], + [ + 4.978945255279541, + -3.0387778282165527 + ], + [ + 5.237149715423584, + -3.2969822883605957 + ], + [ + 5.2395019531248375, + -8.999406881716078 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_7izk7ggo5220wpog": { + "id": "slab_7izk7ggo5220wpog", + "type": "slab", + "holes": [ + [ + [ + -4.65, + -10.8 + ], + [ + 1.9000000000000001, + -10.8 + ], + [ + 1.888454794883728, + -5.712312030792238 + ], + [ + 1.0504575729370131, + -5.639963388442993 + ], + [ + 0.25, + -5.7 + ], + [ + -0.4, + -5.9 + ], + [ + -0.9, + -6.1000000000000005 + ], + [ + -1.4500000000000002, + -6.25 + ], + [ + -2.35, + -6.3500000000000005 + ], + [ + -3, + -6.300000000000001 + ], + [ + -3.6, + -6.1000000000000005 + ], + [ + -4.05, + -5.8500000000000005 + ], + [ + -4.5, + -5.5 + ], + [ + -4.7, + -5.295473098754882 + ] + ], + [ + [ + -5.25, + -2.1 + ], + [ + -5, + -2.4000000000000004 + ], + [ + -4.6000000000000005, + -2.6500000000000004 + ], + [ + -4.2, + -2.8000000000000003 + ], + [ + -3.8000000000000003, + -2.9000000000000004 + ], + [ + -3.4000000000000004, + -2.95 + ], + [ + -2.95, + -3 + ], + [ + -2.952427019579382, + -4.290802001953125 + ], + [ + -2.6500000000000004, + -4.55 + ], + [ + -2.3000000000000003, + -4.65 + ], + [ + -1.85, + -4.65 + ], + [ + -1.4000000000000001, + -4.6000000000000005 + ], + [ + -1, + -4.4 + ], + [ + -0.5468195625920773, + -4.085269206992964 + ], + [ + -0.03872905485332012, + -3.5111807584762573 + ], + [ + 0.1671898514032364, + -2.9824981689453125 + ], + [ + 0.1659151115939861, + -1.8690499744137683 + ], + [ + -0.029356737354590212, + -1.198872945986159 + ], + [ + -0.5343491296711487, + -0.36435131529304643 + ], + [ + -1.15, + 0.2025934915056129 + ], + [ + -1.1500000000000001, + 2.478200674057007 + ], + [ + -1.9504812955856323, + 2.9499636829170583 + ], + [ + -3.7828824995228247, + 2.9499636829170583 + ], + [ + -4.6000000000000005, + 2.478200674057007 + ], + [ + -4.5, + 0.5 + ], + [ + -4.91472662430504, + 0.30046076974568714 + ], + [ + -5.4, + -0.2 + ], + [ + -5.5, + -0.5 + ], + [ + -5.5, + -0.5 + ], + [ + -5.499983667651276, + -0.703364993579402 + ], + [ + -5.5, + -1.1500000000000001 + ], + [ + -5.45, + -1.6500000000000001 + ] + ] + ], + "object": "node", + "polygon": [ + [ + -3.7828824995228247, + 2.9499636829170583 + ], + [ + -4.6000000000000005, + 2.478200674057007 + ], + [ + -4.5726423548447475, + 0.5 + ], + [ + -5.194731124407848, + 0.02039822004501335 + ], + [ + -5.499983667651276, + -0.703364993579402 + ], + [ + -6.9500020088242245, + -0.701318010189226 + ], + [ + -6.9500020088242245, + -4 + ], + [ + -5.612636566162109, + -4 + ], + [ + -5.2918501380099014, + -4.767024116009944 + ], + [ + -4.65, + -5.295473098754882 + ], + [ + -4.65, + -10.8 + ], + [ + 1.9000000000000001, + -10.8 + ], + [ + 1.888454794883728, + -5.712312030792238 + ], + [ + 2.7213549137115485, + -5.712312030792238 + ], + [ + 2.7, + -1.8537885665893556 + ], + [ + 0.1659151115939861, + -1.8690499744137683 + ], + [ + 2.7, + -1.8537885665893556 + ], + [ + 2.7, + 0.8478581309318545 + ], + [ + -1.138415994959748, + 0.8478581299369649 + ], + [ + -1.15, + 0.2025934915056129 + ], + [ + -0.49007946927991863, + -0.41849826556080094 + ], + [ + -0.029356737354590212, + -1.198872945986159 + ], + [ + 0.1956745759049392, + -2.076717457055409 + ], + [ + 0.1671898514032364, + -2.9824981689453125 + ], + [ + 0.1956745759049392, + -2.076717457055409 + ], + [ + -0.029356737354590212, + -1.198872945986159 + ], + [ + -0.49007946927991863, + -0.41849826556080094 + ], + [ + -1.15, + 0.2025934915056129 + ], + [ + -1.1500000000000001, + 2.478200674057007 + ], + [ + -1.9504812955856323, + 2.9499636829170583 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [ + { + "source": "manual" + }, + { + "source": "manual" + } + ], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_axv0fq90ynuhloou": { + "id": "slab_axv0fq90ynuhloou", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -8.8, + 0.3999999999999977 + ], + [ + -10.475817298889162, + 0.39999999999999725 + ], + [ + -10.475817298889162, + -3.4439198970794678 + ], + [ + -8.8, + -3.4439198970794678 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_fz3dmbmcovgmfxlk": { + "id": "slab_fz3dmbmcovgmfxlk", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -8.8, + -3.4439198970794678 + ], + [ + -8.8, + -8.924649810791015 + ], + [ + -4.65, + -8.924649810791015 + ], + [ + -4.65, + -5.295473098754882 + ], + [ + -5.2918501380099014, + -4.767024116009944 + ], + [ + -5.612636566162109, + -4 + ], + [ + -6.9500020088242245, + -4 + ], + [ + -6.9500020088242245, + -3.443919897079468 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_kcv6gjb1ixdq6ynv": { + "id": "slab_kcv6gjb1ixdq6ynv", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 1.888454794883728, + -5.712312030792238 + ], + [ + 1.9000000000000001, + -9 + ], + [ + 5.2395019531248375, + -8.999406881716078 + ], + [ + 5.237149715423584, + -5.712312030792238 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_psj8d6m16r1qmo1m": { + "id": "slab_psj8d6m16r1qmo1m", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -10.475817298889162, + -3.4439198970794678 + ], + [ + -10.475817298889162, + -6.8500000000000005 + ], + [ + -8.8, + -6.8500000000000005 + ], + [ + -8.8, + -3.4439198970794678 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.6, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.6 + }, + "slab_s0223sj8ugjhndz4": { + "id": "slab_s0223sj8ugjhndz4", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 4.061796402931213, + -5.712312030792238 + ], + [ + 5.237149715423584, + -5.712312030792238 + ], + [ + 5.237149715423584, + -3.2969822883605957 + ], + [ + 4.978945255279541, + -3.0387778282165527 + ], + [ + 4.720740795135498, + -3.2969822883605957 + ], + [ + 4.680509638192011, + -5.294192797688352 + ], + [ + 4.539406940462225, + -5.516841135700492 + ] + ], + "visible": true, + "parentId": "level_tf1ug5dswkkzfhqa", + "elevation": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "thickness": 0.05 + }, + "wall_05rljsjpvpxg0lge": { + "id": "wall_05rljsjpvpxg0lge", + "end": [ + 5.237149715423584, + -5.712312030792238 + ], + "type": "wall", + "start": [ + 2.7213549137115485, + -5.712312030792238 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_10gbw3k0x20sn9cl": { + "id": "wall_10gbw3k0x20sn9cl", + "end": [ + 0.1659151115939861, + -1.8690499744137683 + ], + "type": "wall", + "start": [ + 2.7, + -1.8537885665893556 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_2g8ek360ils5c6zv": { + "id": "wall_2g8ek360ils5c6zv", + "end": [ + 4.720740795135498, + -3.2969822883605957 + ], + "type": "wall", + "start": [ + 4.720740795135498, + -5.03368616104126 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior", + "height": 2.5 + }, + "wall_53nehkzmn7sbp3xo": { + "id": "wall_53nehkzmn7sbp3xo", + "end": [ + -5.612636566162109, + -4 + ], + "type": "wall", + "start": [ + -6.9500020088242245, + -4 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_5e74bbgfng06ij2v": { + "id": "wall_5e74bbgfng06ij2v", + "end": [ + -1.138415994959748, + 0.8478581299369649 + ], + "type": "wall", + "start": [ + -1.1500000000000001, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior", + "height": 2.5 + }, + "wall_5ld53lqd7tpg14f9": { + "id": "wall_5ld53lqd7tpg14f9", + "end": [ + -4.65, + -10.8 + ], + "type": "wall", + "start": [ + -4.65, + -8.924649810791015 + ], + "height": 2.74, + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_5n6y2car6g6iqu9q": { + "id": "wall_5n6y2car6g6iqu9q", + "end": [ + -6.9500020088242245, + -3.443919897079468 + ], + "type": "wall", + "start": [ + -6.9500020088242245, + -0.701318010189226 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_7q0igcgudqsf4mr6": { + "id": "wall_7q0igcgudqsf4mr6", + "end": [ + 1.9000000000000001, + -10.8 + ], + "type": "wall", + "start": [ + 1.9000000000000001, + -9 + ], + "height": 2.74, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_9vcv6ze2rar0kllo": { + "id": "wall_9vcv6ze2rar0kllo", + "end": [ + -8.8, + -0.7000000000000001 + ], + "type": "wall", + "start": [ + -8.8, + 0.3999999999999977 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_a22dlcqask9o3nol": { + "id": "wall_a22dlcqask9o3nol", + "end": [ + -10.475817298889162, + 3.572127914428711 + ], + "type": "wall", + "start": [ + -10.475817298889162, + -6.8500000000000005 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_ag4xz82fkzfty3lt": { + "id": "wall_ag4xz82fkzfty3lt", + "end": [ + -3.7828824995228247, + 2.9499636829170583 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_ard5a93tnt3wzzh6": { + "id": "wall_ard5a93tnt3wzzh6", + "end": [ + 2.7, + 0.8478581309318545 + ], + "type": "wall", + "start": [ + 2.7, + -1.8537885665893556 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_bajfw4fffv5qrf1m": { + "id": "wall_bajfw4fffv5qrf1m", + "end": [ + 11.55, + -1.8474719047546384 + ], + "type": "wall", + "start": [ + 2.7, + -1.8537885665893556 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_bvgcs7isi2dii2f7": { + "id": "wall_bvgcs7isi2dii2f7", + "end": [ + -4.65, + -5.295473098754882 + ], + "type": "wall", + "start": [ + -4.65, + -8.924649810791015 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_bx0jgl87dfzvr5gm": { + "id": "wall_bx0jgl87dfzvr5gm", + "end": [ + -8.8, + -3.4439198970794678 + ], + "type": "wall", + "start": [ + -6.9500020088242245, + -3.443919897079468 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_c49yron9q7wp47gy": { + "id": "wall_c49yron9q7wp47gy", + "end": [ + 5.2395019531248375, + -8.999406881716078 + ], + "type": "wall", + "start": [ + 5.237149715423584, + -3.2969822883605957 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_c5weyuht6kkyqsqg": { + "id": "wall_c5weyuht6kkyqsqg", + "end": [ + 9.178149236673104, + -8.998606912144322 + ], + "type": "wall", + "start": [ + 9.178149236673338, + -1.8491648063585198 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_c8lo4kz4h0mef9yv": { + "id": "wall_c8lo4kz4h0mef9yv", + "end": [ + -1.1500000000000001, + 2.478200674057007 + ], + "type": "wall", + "start": [ + -1.9504812955856323, + 2.9499636829170583 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_cam2tmtozlfrbqk5": { + "id": "wall_cam2tmtozlfrbqk5", + "end": [ + -4.5726423548447475, + 0.5 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_d3wyhmj78a494vn8": { + "id": "wall_d3wyhmj78a494vn8", + "end": [ + -6.9500020088242245, + -0.701318010189226 + ], + "type": "wall", + "start": [ + -5.499983667651276, + -0.703364993579402 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_d9ubvuzym6v4hhgh": { + "id": "wall_d9ubvuzym6v4hhgh", + "end": [ + 1.888454794883728, + -5.712312030792238 + ], + "type": "wall", + "start": [ + 1.9000000000000001, + -9 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_e71f2dnudh7lpb9v": { + "id": "wall_e71f2dnudh7lpb9v", + "end": [ + -4.65, + -8.924649810791015 + ], + "type": "wall", + "start": [ + -8.8, + -8.924649810791015 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_ennfhed1hm0ozhch": { + "id": "wall_ennfhed1hm0ozhch", + "end": [ + 1.9000000000000001, + -10.8 + ], + "type": "wall", + "start": [ + -4.65, + -10.8 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_gyt1819erxgrqv3o": { + "id": "wall_gyt1819erxgrqv3o", + "end": [ + 1.9000000000000001, + -9 + ], + "type": "wall", + "start": [ + 11.55, + -8.998152923583985 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_hr0630nj7o336vix": { + "id": "wall_hr0630nj7o336vix", + "end": [ + -8.8, + -8.924649810791015 + ], + "type": "wall", + "slots": {}, + "start": [ + -8.8, + -6.850000000000001 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_jwjfg77bupgbeu5g": { + "id": "wall_jwjfg77bupgbeu5g", + "end": [ + -4.6000000000000005, + 3.572127914428711 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 2.478200674057007 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_jwqeqwq5umuy1gvb": { + "id": "wall_jwqeqwq5umuy1gvb", + "end": [ + -8.8, + 0.3999999999999977 + ], + "type": "wall", + "start": [ + -10.475817298889162, + 0.39999999999999725 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_jws800cwpjvjof8c": { + "id": "wall_jws800cwpjvjof8c", + "end": [ + -6.9500020088242245, + -0.7000000000000001 + ], + "type": "wall", + "start": [ + -8.8, + -0.7000000000000001 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_l367nzmgae9uy0x9": { + "id": "wall_l367nzmgae9uy0x9", + "end": [ + 4.061796402931213, + -5.712312030792238 + ], + "type": "wall", + "start": [ + 4.720740795135498, + -5.03368616104126 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "curveOffset": -0.20648365700569207, + "height": 2.5 + }, + "wall_l8qn4aqt4icpw6ns": { + "id": "wall_l8qn4aqt4icpw6ns", + "end": [ + -1.15, + 0.2025934915056129 + ], + "type": "wall", + "start": [ + -1.138415994959748, + 0.8478581299369649 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_mf2tvbp1smse6ky8": { + "id": "wall_mf2tvbp1smse6ky8", + "end": [ + 4.720740795135498, + -3.2969822883605957 + ], + "type": "wall", + "start": [ + 5.237149715423584, + -3.2969822883605957 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "curveOffset": 0.2719228267669678, + "height": 2.5 + }, + "wall_mxzqxt9rr1aj40vk": { + "id": "wall_mxzqxt9rr1aj40vk", + "end": [ + -8.8, + 3.572127914428711 + ], + "type": "wall", + "start": [ + -8.8, + 0.3999999999999977 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_nqx2se3a3eksgajk": { + "id": "wall_nqx2se3a3eksgajk", + "end": [ + -1.138415994959748, + 0.8478581299369649 + ], + "type": "wall", + "start": [ + 2.7, + 0.8478581309318545 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_quidxtcw6lptgpwy": { + "id": "wall_quidxtcw6lptgpwy", + "end": [ + 2.7213549137115485, + -5.712312030792238 + ], + "type": "wall", + "start": [ + 1.888454794883728, + -5.712312030792238 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior", + "height": 2.5 + }, + "wall_s66g0kh4jhxlsyq0": { + "id": "wall_s66g0kh4jhxlsyq0", + "end": [ + -8.8, + -3.4439198970794678 + ], + "type": "wall", + "start": [ + -8.8, + -6.8500000000000005 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown" + }, + "wall_t55sg3hswku5lyn1": { + "id": "wall_t55sg3hswku5lyn1", + "end": [ + -8.8, + -0.7000000000000001 + ], + "type": "wall", + "start": [ + -8.8, + -3.4439198970794678 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_t5r91noa0eqdilf0": { + "id": "wall_t5r91noa0eqdilf0", + "end": [ + -4.6000000000000005, + 3.572127914428711 + ], + "type": "wall", + "start": [ + -10.475817298889162, + 3.572127914428711 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_twjrbha7gdx24q8c": { + "id": "wall_twjrbha7gdx24q8c", + "end": [ + -1.9504812955856323, + 2.9499636829170583 + ], + "type": "wall", + "start": [ + -3.7828824995228247, + 2.9499636829170583 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_ufsbh2cunaf4y1e0": { + "id": "wall_ufsbh2cunaf4y1e0", + "end": [ + -8.8, + -3.4439198970794678 + ], + "type": "wall", + "start": [ + -10.475817298889162, + -3.4439198970794678 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown" + }, + "wall_ug8avwqdyx3b3b4g": { + "id": "wall_ug8avwqdyx3b3b4g", + "end": [ + -1.15, + 0.2025934915056129 + ], + "type": "wall", + "start": [ + 0.1671898514032364, + -2.9824981689453125 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "curveOffset": 0.5, + "height": 2.5 + }, + "wall_x1eelmdpg7hie8kj": { + "id": "wall_x1eelmdpg7hie8kj", + "end": [ + 11.55, + -8.998152923583985 + ], + "type": "wall", + "start": [ + 11.55, + -1.8474719047546384 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior", + "curveOffset": 0 + }, + "wall_xw95gtjcz7sa1l83": { + "id": "wall_xw95gtjcz7sa1l83", + "end": [ + -6.9500020088242245, + -4 + ], + "type": "wall", + "start": [ + -6.9500020088242245, + -3.443919897079468 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "height": 2.5 + }, + "wall_za20294gpb6ma8jv": { + "id": "wall_za20294gpb6ma8jv", + "end": [ + 2.7213549137115485, + -5.712312030792238 + ], + "type": "wall", + "start": [ + 2.7, + -1.8537885665893556 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "exterior" + }, + "wall_zgt30hblc7v8tpgm": { + "id": "wall_zgt30hblc7v8tpgm", + "end": [ + -8.8, + -6.8500000000000005 + ], + "type": "wall", + "start": [ + -10.475817298889162, + -6.8500000000000005 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "interior" + }, + "wall_zh5et7jn3upvz0ah": { + "id": "wall_zh5et7jn3upvz0ah", + "end": [ + -4.65, + -5.295473098754882 + ], + "type": "wall", + "start": [ + -5.612636566162109, + -4 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "curveOffset": 0.2, + "height": 2.5 + }, + "wall_zn79e6063xs4hvcx": { + "id": "wall_zn79e6063xs4hvcx", + "end": [ + -5.499983667651276, + -0.703364993579402 + ], + "type": "wall", + "start": [ + -4.5726423548447475, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_tf1ug5dswkkzfhqa", + "frontSide": "unknown", + "curveOffset": 0.2, + "height": 2.5 + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-27-level_q5k3omsgkch1zjp1.json b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-27-level_q5k3omsgkch1zjp1.json new file mode 100644 index 0000000000..251f15867a --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/migrations/scene-27-level_q5k3omsgkch1zjp1.json @@ -0,0 +1,1519 @@ +{ + "sceneId": "scene-27", + "levelId": "level_q5k3omsgkch1zjp1", + "nodes": { + "level_q5k3omsgkch1zjp1": { + "id": "level_q5k3omsgkch1zjp1", + "type": "level", + "level": 0, + "height": 2.55, + "object": "node", + "visible": true, + "children": [ + "wall_u1g1qz1ki01wy0a2", + "wall_2ncbx1amwrmoi66c", + "wall_9gqwmnef1r20b4zx", + "wall_j6bced29zcq1unrz", + "wall_i5qcaspo35rfocaa", + "wall_ozv3ur9ukeyovibc", + "wall_7mve519kscoiysdw", + "wall_37wg4s8epl93j5g3", + "wall_u7khmazq98plzwz0", + "wall_c7jxm2lm1p9ahq4k", + "wall_j9xcnno442l0jejb", + "wall_u62ix7mfye95ejwc", + "wall_sxy82u42c7pmjksv", + "wall_z5db30ggotc4bhlf", + "slab_orr8aubqhyhle97y", + "wall_gxjox1ebgrp0n4os", + "wall_q6ohi15eon4ftbh0", + "wall_bzdngt230a81i8gl", + "wall_kjov6asdxd4x18z5", + "wall_0akun1ns9jll8ido", + "wall_0hk594k2zim9ws4u", + "wall_oy7vwph1nlp3vqmz", + "wall_hfqw3andkmg8r2gz", + "wall_w3m0tzv59ddoyi2u", + "slab_d9nmzj1uc2cswylf", + "wall_yy9f3fe53hmz40t8", + "wall_io67rh5922e1joia", + "slab_neypao1jmv5q02s0", + "wall_ewlcxbtlawsih7qp", + "wall_aa3rgl0dzgupe9n7", + "wall_0rxremkbkqrf6ala", + "zone_temmcw3420p554n0", + "zone_6hd42lwyics79yg5", + "zone_xx7afvqiogfbybc5", + "zone_3m7pr7ypdkrpzz0q", + "zone_egfu5jd3e794pp78", + "wall_uvuzktxhugqbmbt7", + "wall_wr4f0kbh5iwo2vcd", + "wall_nb069eotr2lk7hxz", + "wall_5eps4ajnk9dso3ui", + "wall_krubytgxm02hqc8k", + "wall_6ops6wjucw323xs6", + "slab_jzwzjxb1vhtkf39b", + "slab_ro4oj6qy7kpe6f1o", + "slab_y5zodksu1hzwfy2g", + "wall_4kub37uu2l85g62r", + "slab_brpobynpanbvyjxc", + "wall_yndljg07ynkz6iki", + "wall_tef4qctnjoi1joog", + "wall_udxsust6knfrvia4", + "wall_6lc7tx7gic466hfx", + "wall_zcmla08zwaetkumw", + "slab_zzvhklohqbokxugp", + "wall_xwekjh6mz63a3d15", + "wall_kdtjb1ajicdfjdcx", + "wall_9bzlvfyrb5296n1i", + "slab_u95v9yhtgwpg31og" + ], + "parentId": null, + "baseElevation": 0 + }, + "slab_brpobynpanbvyjxc": { + "id": "slab_brpobynpanbvyjxc", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 1.75, + -7 + ], + [ + 1.75, + -5 + ], + [ + 0, + -5 + ], + [ + 0, + 0.5 + ], + [ + -2.525, + 0.5 + ], + [ + -2.525, + -0.8595930435954162 + ], + [ + -6, + -0.8595930435954164 + ], + [ + -6, + -7 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_d9nmzj1uc2cswylf": { + "id": "slab_d9nmzj1uc2cswylf", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + 6.75, + -5 + ], + [ + 6.75, + 7.5 + ], + [ + -4.6000000000000005, + 7.5 + ], + [ + -4.6000000000000005, + 6 + ], + [ + -6, + 6 + ], + [ + -6, + 2.5 + ], + [ + -2.1136363636363638, + 2.5 + ], + [ + -2.2045454545454546, + 0.5 + ], + [ + 0, + 0.5 + ], + [ + 0, + -5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_jzwzjxb1vhtkf39b": { + "id": "slab_jzwzjxb1vhtkf39b", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -2.1136363636363638, + 2.5 + ], + [ + -5.05, + 2.5 + ], + [ + -5.05, + 0.5 + ], + [ + -2.2045454545454546, + 0.5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_neypao1jmv5q02s0": { + "id": "slab_neypao1jmv5q02s0", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -1, + 4 + ], + [ + -2, + 4 + ], + [ + -2, + 2.5 + ], + [ + -1, + 2.5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_orr8aubqhyhle97y": { + "id": "slab_orr8aubqhyhle97y", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -6, + 6 + ], + [ + -4.6000000000000005, + 6 + ], + [ + -4.6000000000000005, + 7.5 + ], + [ + -6, + 7.5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_ro4oj6qy7kpe6f1o": { + "id": "slab_ro4oj6qy7kpe6f1o", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -6, + 0.5 + ], + [ + -6, + -0.8595930435954164 + ], + [ + -2.525, + -0.8595930435954162 + ], + [ + -2.525, + 0.5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_u95v9yhtgwpg31og": { + "id": "slab_u95v9yhtgwpg31og", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -10.940918830920369, + -15.586431816442575 + ], + [ + -10.34615159739105, + -15.573849452800486 + ], + [ + -9.78675961334978, + -15.371397023461368 + ], + [ + -9.321703296374574, + -15.00041319632547 + ], + [ + -9, + -14.5 + ], + [ + -8.32987738439551, + -14.260333622043166 + ], + [ + -7.743381132497885, + -13.85718794219829 + ], + [ + -7.279555295719229, + -13.317401052950201 + ], + [ + -6.9692775476318065, + -12.676907484122731 + ], + [ + -6.833203604805263, + -11.978345980208303 + ], + [ + -6.880392140679333, + -11.268220966742637 + ], + [ + -7.107701734290508, + -10.59380667172816 + ], + [ + -7.5, + -10 + ], + [ + -7.104605983736301, + -9.289463101666787 + ], + [ + -6.874704707805869, + -8.509498669583063 + ], + [ + -6.821495018295284, + -7.698099975393635 + ], + [ + -6.947568841329061, + -6.894791502180653 + ], + [ + -7.246784926346551, + -6.1387036458723205 + ], + [ + -7.704567995897996, + -5.466666613245264 + ], + [ + -8.298618729911334, + -4.911416365691661 + ], + [ + -9, + -4.5 + ], + [ + -9.1957525226473, + -3.9665782328976937 + ], + [ + -9.561811677574394, + -3.5319996705693253 + ], + [ + -10.054214777827028, + -3.2484559903312986 + ], + [ + -10.613825579821782, + -3.1500000000000004 + ], + [ + -11.173436381816536, + -3.2484559903312986 + ], + [ + -11.66583948206917, + -3.5319996705693244 + ], + [ + -12.031898636996264, + -3.9665782328976937 + ], + [ + -12.227651159643566, + -4.5 + ], + [ + -11.391006948784343, + -6.825059385718546 + ], + [ + -11.154079826969657, + -9.284681352938463 + ], + [ + -11.53152836691167, + -11.7266902149981 + ], + [ + -12.5, + -14 + ], + [ + -12.33128053045154, + -14.570473591457333 + ], + [ + -11.988701937753396, + -15.05683383426085 + ], + [ + -11.508372313288728, + -15.40781792195796 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_y5zodksu1hzwfy2g": { + "id": "slab_y5zodksu1hzwfy2g", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -5.05, + 0.5 + ], + [ + -5.05, + 2.5 + ], + [ + -6, + 2.5 + ], + [ + -6, + 0.5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_zzvhklohqbokxugp": { + "id": "slab_zzvhklohqbokxugp", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [ + -12.5, + -14 + ], + [ + -11.53152836691167, + -11.7266902149981 + ], + [ + -11.154079826969657, + -9.284681352938463 + ], + [ + -11.391006948784343, + -6.825059385718546 + ], + [ + -11.736756619770933, + -5.636415389062275 + ], + [ + -12.363825579821782, + -4.363825579821783 + ], + [ + -13.082051303087555, + -5.605595567353202 + ], + [ + -13.505946662125979, + -6.780941474974725 + ], + [ + -13.763573134087803, + -8.003542750502225 + ], + [ + -13.85, + -9.250000000000002 + ], + [ + -13.763573134087803, + -10.496457249497777 + ], + [ + -13.505946662125977, + -11.719058525025277 + ], + [ + -13.082051303087555, + -12.8944044326468 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "wall_0akun1ns9jll8ido": { + "id": "wall_0akun1ns9jll8ido", + "end": [ + -5.05, + 2.5 + ], + "type": "wall", + "start": [ + -2, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_0hk594k2zim9ws4u": { + "id": "wall_0hk594k2zim9ws4u", + "end": [ + -6, + 2.5 + ], + "type": "wall", + "start": [ + -5.05, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_0rxremkbkqrf6ala": { + "id": "wall_0rxremkbkqrf6ala", + "end": [ + -6, + -0.8595930435954164 + ], + "type": "wall", + "start": [ + -2.525, + -0.8595930435954162 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_2ncbx1amwrmoi66c": { + "id": "wall_2ncbx1amwrmoi66c", + "end": [ + 6.75, + -5 + ], + "type": "wall", + "start": [ + 1.75, + -5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_37wg4s8epl93j5g3": { + "id": "wall_37wg4s8epl93j5g3", + "end": [ + -2, + 2.5 + ], + "type": "wall", + "start": [ + -1, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_4kub37uu2l85g62r": { + "id": "wall_4kub37uu2l85g62r", + "end": [ + 1.75, + -7 + ], + "type": "wall", + "start": [ + -6, + -7 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_5eps4ajnk9dso3ui": { + "id": "wall_5eps4ajnk9dso3ui", + "end": [ + 0, + 0.5 + ], + "type": "wall", + "start": [ + -2.2045454545454546, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_6lc7tx7gic466hfx": { + "id": "wall_6lc7tx7gic466hfx", + "end": [ + -12.227651159643566, + -4.5 + ], + "type": "wall", + "start": [ + -12.5, + -4.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior", + "curveOffset": -1.35 + }, + "wall_6ops6wjucw323xs6": { + "id": "wall_6ops6wjucw323xs6", + "end": [ + -2.2045454545454546, + 0.5 + ], + "type": "wall", + "start": [ + -2.1136363636363638, + 2.5 + ], + "height": 2.55, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "supportOffset": 2.5500000000000016, + "supportSlabId": "ground" + }, + "wall_7mve519kscoiysdw": { + "id": "wall_7mve519kscoiysdw", + "end": [ + -2, + 4 + ], + "type": "wall", + "start": [ + -1, + 4 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_9bzlvfyrb5296n1i": { + "id": "wall_9bzlvfyrb5296n1i", + "end": [ + -12.5, + -14 + ], + "type": "wall", + "start": [ + -9, + -14.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "curveOffset": -1.35 + }, + "wall_9gqwmnef1r20b4zx": { + "id": "wall_9gqwmnef1r20b4zx", + "end": [ + 2, + 7.5 + ], + "type": "wall", + "start": [ + 6.75, + 7.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_aa3rgl0dzgupe9n7": { + "id": "wall_aa3rgl0dzgupe9n7", + "end": [ + -2.525, + -0.8595930435954162 + ], + "type": "wall", + "start": [ + -2.525, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_bzdngt230a81i8gl": { + "id": "wall_bzdngt230a81i8gl", + "end": [ + -6, + -7 + ], + "type": "wall", + "start": [ + -6, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_c7jxm2lm1p9ahq4k": { + "id": "wall_c7jxm2lm1p9ahq4k", + "end": [ + -6, + 7.5 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 7.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_ewlcxbtlawsih7qp": { + "id": "wall_ewlcxbtlawsih7qp", + "end": [ + -2.525, + 0.5 + ], + "type": "wall", + "start": [ + -5.05, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_gxjox1ebgrp0n4os": { + "id": "wall_gxjox1ebgrp0n4os", + "end": [ + 1.75, + -5 + ], + "type": "wall", + "start": [ + 0, + -5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_hfqw3andkmg8r2gz": { + "id": "wall_hfqw3andkmg8r2gz", + "end": [ + 6.75, + 1.25 + ], + "type": "wall", + "start": [ + 6.75, + -5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_i5qcaspo35rfocaa": { + "id": "wall_i5qcaspo35rfocaa", + "end": [ + -2, + 7.5 + ], + "type": "wall", + "start": [ + 2, + 7.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_io67rh5922e1joia": { + "id": "wall_io67rh5922e1joia", + "end": [ + -1, + 2.5 + ], + "type": "wall", + "start": [ + -1, + 4 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_j6bced29zcq1unrz": { + "id": "wall_j6bced29zcq1unrz", + "end": [ + 2, + 7.5 + ], + "type": "wall", + "start": [ + 2, + 6.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_j9xcnno442l0jejb": { + "id": "wall_j9xcnno442l0jejb", + "end": [ + -4.6000000000000005, + 6 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 7.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_kdtjb1ajicdfjdcx": { + "id": "wall_kdtjb1ajicdfjdcx", + "end": [ + -9, + -14.5 + ], + "type": "wall", + "start": [ + -7.5, + -10 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "curveOffset": -1.35 + }, + "wall_kjov6asdxd4x18z5": { + "id": "wall_kjov6asdxd4x18z5", + "end": [ + -5.05, + 0.5 + ], + "type": "wall", + "start": [ + -6, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_krubytgxm02hqc8k": { + "id": "wall_krubytgxm02hqc8k", + "end": [ + -2.1136363636363638, + 2.5 + ], + "type": "wall", + "start": [ + -2, + 5 + ], + "height": 2.55, + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "supportOffset": 2.5500000000000016, + "supportSlabId": "ground" + }, + "wall_nb069eotr2lk7hxz": { + "id": "wall_nb069eotr2lk7hxz", + "end": [ + -2.2045454545454546, + 0.5 + ], + "type": "wall", + "start": [ + -2.525, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_oy7vwph1nlp3vqmz": { + "id": "wall_oy7vwph1nlp3vqmz", + "end": [ + -5.05, + 0.5 + ], + "type": "wall", + "start": [ + -5.05, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_ozv3ur9ukeyovibc": { + "id": "wall_ozv3ur9ukeyovibc", + "end": [ + -2, + 4 + ], + "type": "wall", + "start": [ + -2, + 2.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_q6ohi15eon4ftbh0": { + "id": "wall_q6ohi15eon4ftbh0", + "end": [ + 0, + -5 + ], + "type": "wall", + "start": [ + 0, + 0.5 + ], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "exterior" + }, + "wall_sxy82u42c7pmjksv": { + "id": "wall_sxy82u42c7pmjksv", + "end": [ + -6, + 2.5 + ], + "type": "wall", + "start": [ + -6, + 6 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_tef4qctnjoi1joog": { + "id": "wall_tef4qctnjoi1joog", + "end": [ + -12.227651159643566, + -4.5 + ], + "type": "wall", + "start": [ + -12.5, + -4 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "curveOffset": -0.004079826969656187 + }, + "wall_u1g1qz1ki01wy0a2": { + "id": "wall_u1g1qz1ki01wy0a2", + "end": [ + 1.75, + -5 + ], + "type": "wall", + "start": [ + 1.75, + -7 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_u62ix7mfye95ejwc": { + "id": "wall_u62ix7mfye95ejwc", + "end": [ + -6, + 6 + ], + "type": "wall", + "start": [ + -6, + 7.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_u7khmazq98plzwz0": { + "id": "wall_u7khmazq98plzwz0", + "end": [ + -4.6000000000000005, + 7.5 + ], + "type": "wall", + "start": [ + -2, + 7.5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_udxsust6knfrvia4": { + "id": "wall_udxsust6knfrvia4", + "end": [ + -12.5, + -14 + ], + "type": "wall", + "start": [ + -12.227651159643566, + -4.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "curveOffset": -1.210242778447943 + }, + "wall_uvuzktxhugqbmbt7": { + "id": "wall_uvuzktxhugqbmbt7", + "end": [ + -2, + 5 + ], + "type": "wall", + "start": [ + -2, + 4 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_w3m0tzv59ddoyi2u": { + "id": "wall_w3m0tzv59ddoyi2u", + "end": [ + 6.75, + 7.5 + ], + "type": "wall", + "start": [ + 6.75, + 1.25 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_wr4f0kbh5iwo2vcd": { + "id": "wall_wr4f0kbh5iwo2vcd", + "end": [ + -2, + 7.5 + ], + "type": "wall", + "start": [ + -2, + 5 + ], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "interior" + }, + "wall_xwekjh6mz63a3d15": { + "id": "wall_xwekjh6mz63a3d15", + "end": [ + -7.5, + -10 + ], + "type": "wall", + "start": [ + -9, + -4.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "curveOffset": -1.35 + }, + "wall_yndljg07ynkz6iki": { + "id": "wall_yndljg07ynkz6iki", + "end": [ + -12.5, + -4.5 + ], + "type": "wall", + "start": [ + -12.5, + -14 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "curveOffset": -1.35 + }, + "wall_yy9f3fe53hmz40t8": { + "id": "wall_yy9f3fe53hmz40t8", + "end": [ + 5.75, + 1.25 + ], + "type": "wall", + "start": [ + 6.75, + 1.25 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_z5db30ggotc4bhlf": { + "id": "wall_z5db30ggotc4bhlf", + "end": [ + -6, + 6 + ], + "type": "wall", + "start": [ + -4.6000000000000005, + 6 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown" + }, + "wall_zcmla08zwaetkumw": { + "id": "wall_zcmla08zwaetkumw", + "end": [ + -9, + -4.5 + ], + "type": "wall", + "start": [ + -12.227651159643566, + -4.5 + ], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "parentId": "level_q5k3omsgkch1zjp1", + "frontSide": "unknown", + "curveOffset": -1.35 + }, + "zone_3m7pr7ypdkrpzz0q": { + "id": "zone_3m7pr7ypdkrpzz0q", + "type": "zone", + "color": "#a855f7", + "object": "node", + "polygon": [ + [ + -2, + 4 + ], + [ + -2, + 2.5 + ], + [ + -1, + 2.5 + ], + [ + -1, + 4 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "occupancy": "", + "spaceRole": "generic", + "roomNumber": "", + "wallFinish": "", + "floorFinish": "", + "autoFromWalls": true, + "ceilingFinish": "", + "ceilingHeight": 2.7, + "boundaryWallIds": [ + "wall_7mve519kscoiysdw", + "wall_ozv3ur9ukeyovibc", + "wall_37wg4s8epl93j5g3", + "wall_io67rh5922e1joia" + ], + "enclosureStatus": "auto", + "clearDimensionPolicy": "none", + "name": "Room" + }, + "zone_6hd42lwyics79yg5": { + "id": "zone_6hd42lwyics79yg5", + "type": "zone", + "color": "#f59e0b", + "object": "node", + "polygon": [ + [ + 7, + 1.5 + ], + [ + 0, + 1.5 + ], + [ + 0, + -5 + ], + [ + 7, + -5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "name": "Room" + }, + "zone_egfu5jd3e794pp78": { + "id": "zone_egfu5jd3e794pp78", + "type": "zone", + "color": "#10b981", + "object": "node", + "polygon": [ + [ + -2, + 7.5 + ], + [ + -4.5, + 7.5 + ], + [ + -4.5, + 6 + ], + [ + -6, + 6 + ], + [ + -6, + 2.5 + ], + [ + -2, + 2.5 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "name": "Room" + }, + "zone_temmcw3420p554n0": { + "id": "zone_temmcw3420p554n0", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [ + -2, + 7.5 + ], + [ + 7, + 7.5 + ], + [ + 7, + 1.5 + ], + [ + -1, + 1.5 + ], + [ + -1, + 4 + ], + [ + -2, + 4 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "name": "Room" + }, + "zone_xx7afvqiogfbybc5": { + "id": "zone_xx7afvqiogfbybc5", + "type": "zone", + "color": "#ef4444", + "object": "node", + "polygon": [ + [ + 2, + -5 + ], + [ + 0, + -5 + ], + [ + 0, + 0.5 + ], + [ + -6, + 0.5 + ], + [ + -6, + -7 + ], + [ + 2, + -7 + ] + ], + "visible": true, + "parentId": "level_q5k3omsgkch1zjp1", + "name": "Room" + } + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/review/legacy-terrace-pad.json b/packages/core/src/lib/__fixtures__/plate-corpus/review/legacy-terrace-pad.json new file mode 100644 index 0000000000..2b61e9aab6 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/review/legacy-terrace-pad.json @@ -0,0 +1,2477 @@ +{ + "nodes": { + "site_t0flznd65l9tu3a0": { + "id": "site_t0flznd65l9tu3a0", + "type": "site", + "object": "node", + "visible": true, + "children": ["building_eptuyxdfmohgin94"], + "parentId": null, + "metadata": {} + }, + "slab_0v814k5ut07aug28": { + "id": "slab_0v814k5ut07aug28", + "name": "Slab 1", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-6.4, 3.75], + [-4.7, 3.75], + [-4.7, -1.2000000000000002], + [-4.55, -1.8], + [-4.3500000000000005, -2.3000000000000003], + [-4, -2.6], + [-3.7, -2.8000000000000003], + [-3.35, -2.95], + [-2.95, -3], + [-2.95, -4.15], + [2, -4.15], + [2, -5.5], + [-6.4, -5.5] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.15, + "thickness": 0.15, + "holeMetadata": [], + "autoFromWalls": false, + "metadata": {} + }, + "slab_16d6d5w2s2aninah": { + "id": "slab_16d6d5w2s2aninah", + "name": "Slab 2", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [7.25, -5.300000000000001], + [1.9000000000000001, -5.300000000000001], + [1.9000000000000001, -9], + [7.25, -9] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_1otds1gkd2nsqbyg": { + "id": "slab_1otds1gkd2nsqbyg", + "name": "Slab 3", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-10.65, -3.5000000000000018], [-6.4, -3.5], [-6.4, -1.55], [-10.65, -1.55]], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_3i30zvxb4fr7ex82": { + "id": "slab_3i30zvxb4fr7ex82", + "name": "Slab 4", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [2.75, -4.1000000000000005], + [2.75, -0.6000000000000001], + [-1.1500000000000001, -0.5999999999999996], + [-1.15, -4.1000000000000005] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_5hy9p72gdb0m2f1f": { + "id": "slab_5hy9p72gdb0m2f1f", + "name": "Slab 5", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [2, -7], + [4.8500000000000005, -7], + [4.8500000000000005, -5.300000000000001], + [2, -5.300000000000001] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_5nurv3do0357hcz9": { + "id": "slab_5nurv3do0357hcz9", + "name": "Slab 6", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[4.8500000000000005, -7], [2, -7], [2, -9], [4.8500000000000005, -9]], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_7pa8krrc3l8ximvy": { + "id": "slab_7pa8krrc3l8ximvy", + "name": "Slab 7", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.8, -10.850000000000001], + [-4.65, -10.850000000000001], + [-4.65, -9.099999999999998], + [-8.8, -9.099999999999998] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_7wkiq3j1hagqs2r6": { + "id": "slab_7wkiq3j1hagqs2r6", + "name": "Slab 8", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-1.1500000000000001, 2.7], + [-1.1500000000000001, -0.5999999999999996], + [2.75, -0.6000000000000001], + [2.75, 2.7] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_8c6hj3s05zq2a6nv": { + "id": "slab_8c6hj3s05zq2a6nv", + "name": "Slab 9", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-4.6000000000000005, 2.6], + [-4.599999999999999, 12.85], + [-12.200000000000001, 12.850000000000001], + [-12.200000000000001, 2.6] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_8fe9i0rab3gkqx6v": { + "id": "slab_8fe9i0rab3gkqx6v", + "name": "Slab 10", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-1.1500000000000001, 2.0500000000000003], + [-1.1500000000000001, 0.046331338584423065], + [-0.6788815994909346, -0.24862096295763747], + [-0.3545262813568115, -0.7000000000000004], + [2.7, -0.6999999999999995], + [2.7, 2.0500000000000003] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_93ch0zszrvd25dqh": { + "id": "slab_93ch0zszrvd25dqh", + "name": "Slab 11", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-6.4, -3.5], [-8.8, -3.500000000000001], [-8.8, -5.5], [-6.4, -5.5]], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_bve5a81ey998z2x4": { + "id": "slab_bve5a81ey998z2x4", + "name": "Slab 12", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [10.500000000000002, -4.1000000000000005], + [11.55, -4.1000000000000005], + [11.55, -2.1999999999999997], + [10.500000000000002, -2.2] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_edqefr7kc95fjqya": { + "id": "slab_edqefr7kc95fjqya", + "name": "Slab 13", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.58468999862671, 0.3328427970409398], + [-8.58468999862671, -0.7000000000000001], + [-6.222509860992432, -0.7000000000000001], + [-6.222509860992432, 0.3328427970409398] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_fi4tbwv3mf7q3coa": { + "id": "slab_fi4tbwv3mf7q3coa", + "name": "Slab 14", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [7.3500000000000005, -9], + [7.3500000000000005, -7], + [4.8500000000000005, -7], + [4.8500000000000005, -9] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_h8pdakankbh7nu0n": { + "id": "slab_h8pdakankbh7nu0n", + "name": "Slab 15", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-4.600000000000002, 12.85], + [-12.2, 12.85], + [-12.200000000000001, 2.5], + [-10.65, 2.5], + [-10.65, 3.7], + [-4.600000000000002, 3.700000000000001] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_icuk9ja7lb9yco3w": { + "id": "slab_icuk9ja7lb9yco3w", + "name": "Slab 16", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-11.200000000000001, -0.7000000000000002], + [-11.200000000000001, -2.4000000000000004], + [-7.814762020111084, -2.4000000000000004], + [-7.814762020111084, -0.7000000000000001] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_k10vjdavfbkblcar": { + "id": "slab_k10vjdavfbkblcar", + "name": "Slab 17", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-10.65, 0.0999999999999992], + [-6.4, 0.10000000000000009], + [-6.4, 3.7], + [-10.65, 3.7] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_l25hzcqh95xfyahj": { + "id": "slab_l25hzcqh95xfyahj", + "name": "Slab 18", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[7.3500000000000005, -7], [7.3500000000000005, -9], [11.65, -9], [11.65, -7]], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_lxyzotdbs7qyikwj": { + "id": "slab_lxyzotdbs7qyikwj", + "name": "Slab 19", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.8, -6.8500000000000005], + [-8.8, -2.4000000000000004], + [-12.100000000000001, -2.4000000000000004], + [-12.100000000000001, -6.8500000000000005] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_lyxyjxzp6vfrfqra": { + "id": "slab_lyxyjxzp6vfrfqra", + "name": "Slab 20", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.8, 0.09999999999999955], + [-10.65, 0.0999999999999992], + [-10.65, -1.55], + [-8.8, -1.5500000000000003] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_o29p9hn5ky4vtljm": { + "id": "slab_o29p9hn5ky4vtljm", + "name": "Slab 21", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [1.4500000000000002, -2.2], + [2.7, -2.2], + [2.7, -0.6999999999999995], + [1.4500000000000002, -0.6999999999999997] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_ovdx0dr2t9mrx7p1": { + "id": "slab_ovdx0dr2t9mrx7p1", + "name": "Slab 22", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-12.100000000000001, -6.8500000000000005], + [-12.100000000000001, -11.8], + [-8.8, -11.8], + [-8.8, -6.8500000000000005] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.15, + "thickness": 0.15, + "holeMetadata": [], + "autoFromWalls": false, + "metadata": {} + }, + "slab_rgb0fbygk7pe0mx9": { + "id": "slab_rgb0fbygk7pe0mx9", + "name": "Slab 23", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.8, -5.5], + [-8.8, -9.099999999999998], + [-4.65, -9.099999999999998], + [-4.65, -5.5] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_srszhqarv69ftxcp": { + "id": "slab_srszhqarv69ftxcp", + "name": "Slab 24", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.8, -3.500000000000001], + [-10.65, -3.5000000000000018], + [-10.65, -6.8500000000000005], + [-8.8, -6.8500000000000005] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_ssjc0k843ljb7djq": { + "id": "slab_ssjc0k843ljb7djq", + "name": "Slab 25", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [2, -5.300000000000001], + [4.8500000000000005, -5.300000000000001], + [4.8500000000000005, -7], + [11.65, -7], + [11.65, -2.1999999999999997], + [4.8500000000000005, -2.2000000000000006], + [4.8500000000000005, -4.1000000000000005], + [2, -4.1000000000000005] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_tnpnlsfjmbfvvgcy": { + "id": "slab_tnpnlsfjmbfvvgcy", + "name": "Slab 26", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [2.75, -2.2000000000000006], + [2.75, -4.1000000000000005], + [4.8500000000000005, -4.1000000000000005], + [4.8500000000000005, -2.2000000000000006] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_tv8otyj1dlo8jw89": { + "id": "slab_tv8otyj1dlo8jw89", + "name": "Slab 27", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [4.800000000000001, -4.1000000000000005], + [7.65, -4.1000000000000005], + [7.65, -2.2], + [4.800000000000001, -2.2000000000000006] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_tys0vvdtv9uvf79j": { + "id": "slab_tys0vvdtv9uvf79j", + "name": "Slab 28", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.8, -1.5500000000000003], + [-6.4, -1.5499999999999996], + [-6.4, 0.1], + [-8.8, 0.09999999999999955] + ], + "visible": true, + "parentId": "level_3xsbeo3c6y50zj52", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_uoix7n2xs9z4w9yp": { + "id": "slab_uoix7n2xs9z4w9yp", + "name": "Slab 29", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.58468999862671, 2.6], + [-11.200000000000001, 2.6], + [-11.200000000000001, -0.7000000000000002], + [-8.58468999862671, -0.7000000000000001] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_xmqxds2r7q53o0ad": { + "id": "slab_xmqxds2r7q53o0ad", + "name": "Slab 30", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [10.500000000000002, -4.1000000000000005], + [10.500000000000002, -2.2], + [7.65, -2.2], + [7.65, -4.1000000000000005] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_y00qwmm7b0bfptwl": { + "id": "slab_y00qwmm7b0bfptwl", + "name": "Slab 31", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [4.800000000000001, -4.1000000000000005], + [4.800000000000001, -5.300000000000001], + [7.25, -5.300000000000001], + [7.25, -8.950000000000001], + [11.55, -8.950000000000001], + [11.55, -4.1000000000000005] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_yx1lw111nbjz1g6k": { + "id": "slab_yx1lw111nbjz1g6k", + "name": "Slab 32", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-8.58468999862671, 2.6], + [-8.58468999862671, 0.3328427970409398], + [-6.222509860992432, 0.3328427970409398], + [-6.222509860992432, -0.7000000000000001], + [-5.362346649169922, -0.7000000000000001], + [-5.086107489974147, -0.21964841309696181], + [-4.6000000000000005, 0.04633133858442264], + [-4.6000000000000005, 2.6] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "slab_zfmvjc8vx1r7yy94": { + "id": "slab_zfmvjc8vx1r7yy94", + "name": "Slab 33", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [4.800000000000001, -2.2000000000000006], + [1.4500000000000002, -2.2], + [1.4500000000000002, -0.7000000000000006], + [-0.3545262813568115, -0.7000000000000004], + [-0.6788815994909346, -0.24862096295763747], + [-1.1500000000000001, 0.046331338584423065], + [-1.1500000000000001, 2.478200674057007], + [-1.9504812955856323, 2.9499636829170583], + [-3.7828824995228247, 2.9499636829170583], + [-4.6000000000000005, 2.478200674057007], + [-4.6000000000000005, 0.04633133858442264], + [-5.086107489974147, -0.21964841309696181], + [-5.362346649169922, -0.7000000000000001], + [-7.814762020111084, -0.7000000000000001], + [-7.814762020111084, -2.4000000000000004], + [-8.8, -2.4000000000000004], + [-8.8, -10.6], + [-4.65, -10.6], + [-4.65, -10.8], + [1.9000000000000001, -10.8], + [1.9000000000000001, -5.300000000000001], + [4.800000000000001, -5.300000000000001] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true, + "metadata": {} + }, + "wall_004xqitnygtz8po2": { + "id": "wall_004xqitnygtz8po2", + "end": [-0.3545262813568115, -0.7000000000000004], + "name": "Wall 1", + "type": "wall", + "start": [-1.1500000000000001, 0.046331338584423065], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "curveOffset": -0.10724822367698647, + "metadata": {} + }, + "wall_0jkp9omzwb3gnx49": { + "id": "wall_0jkp9omzwb3gnx49", + "end": [-10.65, 2.5], + "name": "Wall 2", + "type": "wall", + "start": [-10.65, 3.7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_0nug08l14z8ay1qi": { + "id": "wall_0nug08l14z8ay1qi", + "end": [-5.362346649169922, -0.7000000000000001], + "name": "Wall 3", + "type": "wall", + "start": [-4.6000000000000005, 0.04633133858442264], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "curveOffset": 0.15000000000000002, + "metadata": {} + }, + "wall_11wljyr3yx5wmcjz": { + "id": "wall_11wljyr3yx5wmcjz", + "end": [11.55, -4.1000000000000005], + "name": "Wall 4", + "type": "wall", + "start": [10.500000000000002, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_17qu7aft5i74sh6e": { + "id": "wall_17qu7aft5i74sh6e", + "end": [7.3500000000000005, -9], + "name": "Wall 5", + "type": "wall", + "start": [7.3500000000000005, -7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_1f5xy4zsjuwew7kp": { + "id": "wall_1f5xy4zsjuwew7kp", + "end": [-6.4, -5.5], + "name": "Wall 6", + "type": "wall", + "start": [-6.4, -3.5], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_1hvhcnagt0h3mavo": { + "id": "wall_1hvhcnagt0h3mavo", + "end": [-8.8, 0.09999999999999955], + "name": "Wall 7", + "type": "wall", + "start": [-8.8, -1.5500000000000003], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_1kfnfkeabjndptr1": { + "id": "wall_1kfnfkeabjndptr1", + "end": [10.500000000000002, -4.1000000000000005], + "name": "Wall 8", + "type": "wall", + "start": [10.500000000000002, -2.2], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_1sm7luej94sbqhh1": { + "id": "wall_1sm7luej94sbqhh1", + "end": [10.500000000000002, -2.2], + "name": "Wall 9", + "type": "wall", + "start": [7.65, -2.2], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_1z7b8yjkeqz6a8zv": { + "id": "wall_1z7b8yjkeqz6a8zv", + "end": [4.800000000000001, -2.2000000000000006], + "name": "Wall 10", + "type": "wall", + "start": [4.800000000000001, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_2h0cu6e19qnem55k": { + "id": "wall_2h0cu6e19qnem55k", + "end": [-6.4, 0.10000000000000009], + "name": "Wall 11", + "type": "wall", + "start": [-6.4, 3.7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_2q1g6ej5zhdeim5a": { + "id": "wall_2q1g6ej5zhdeim5a", + "end": [-6.4, -1.5499999999999996], + "name": "Wall 12", + "type": "wall", + "start": [-6.4, 0.1], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_2rwmin5i5b36sply": { + "id": "wall_2rwmin5i5b36sply", + "end": [-12.200000000000001, 2.5], + "name": "Wall 13", + "type": "wall", + "start": [-10.65, 2.5], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_2ui76g9d7m1lry4r": { + "id": "wall_2ui76g9d7m1lry4r", + "end": [11.65, -9], + "name": "Wall 14", + "type": "wall", + "start": [11.65, -7], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_2yuniixkeuggttjq": { + "id": "wall_2yuniixkeuggttjq", + "end": [-11.200000000000001, 2.6], + "name": "Wall 15", + "type": "wall", + "start": [-8.58468999862671, 2.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_30a8ksc63pweh8is": { + "id": "wall_30a8ksc63pweh8is", + "end": [-8.8, -10.850000000000001], + "name": "Wall 16", + "type": "wall", + "start": [-4.65, -10.850000000000001], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_3lr2au8fkvlhftx3": { + "id": "wall_3lr2au8fkvlhftx3", + "end": [-1.15, -4.1000000000000005], + "name": "Wall 17", + "type": "wall", + "start": [2, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_3nzlcr50iii7d7jn": { + "id": "wall_3nzlcr50iii7d7jn", + "end": [-8.8, -5.5], + "name": "Wall 18", + "type": "wall", + "start": [-8.8, -6.8500000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_4av6d0oa9nnk0j8b": { + "id": "wall_4av6d0oa9nnk0j8b", + "end": [-10.65, 0.0999999999999992], + "name": "Wall 19", + "type": "wall", + "start": [-10.65, 2.5], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_4xg3dvyuqp9ewlpq": { + "id": "wall_4xg3dvyuqp9ewlpq", + "end": [2, -7], + "name": "Wall 20", + "type": "wall", + "start": [4.8500000000000005, -7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_5q4v1c6bveqd9jpy": { + "id": "wall_5q4v1c6bveqd9jpy", + "end": [11.55, -4.1000000000000005], + "name": "Wall 21", + "type": "wall", + "start": [11.55, -2.1999999999999997], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "curveOffset": 0, + "metadata": {} + }, + "wall_5repmbaa8v3d0yma": { + "id": "wall_5repmbaa8v3d0yma", + "end": [-4.65, -10.850000000000001], + "name": "Wall 22", + "type": "wall", + "start": [-4.65, -9.1], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_66at0a2mbvetvok1": { + "id": "wall_66at0a2mbvetvok1", + "end": [-4.6000000000000005, 3.7], + "name": "Wall 23", + "type": "wall", + "start": [-4.6000000000000005, 2.7489473819732666], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_6vuxw1jkte7hc2wc": { + "id": "wall_6vuxw1jkte7hc2wc", + "end": [-8.58468999862671, -0.7000000000000001], + "name": "Wall 24", + "type": "wall", + "start": [-8.58468999862671, 2.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_6wxm2rp5ttawnjqv": { + "id": "wall_6wxm2rp5ttawnjqv", + "end": [11.55, -8.950000000000001], + "name": "Wall 25", + "type": "wall", + "start": [11.55, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "curveOffset": 0, + "metadata": {} + }, + "wall_72j4dhw3w70fuq15": { + "id": "wall_72j4dhw3w70fuq15", + "end": [-3.7828824995228247, 2.9499636829170583], + "name": "Wall 26", + "type": "wall", + "start": [-4.6000000000000005, 2.478200674057007], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_74dkbkdfrygvnfa0": { + "id": "wall_74dkbkdfrygvnfa0", + "end": [-12.2, 12.85], + "name": "Wall 27", + "type": "wall", + "start": [-12.2, 3.700000000000001], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_7avku9vio7cqwt3s": { + "id": "wall_7avku9vio7cqwt3s", + "end": [2, -4.1000000000000005], + "name": "Wall 28", + "type": "wall", + "start": [2, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_7db1eoza5wt17d7x": { + "id": "wall_7db1eoza5wt17d7x", + "end": [11.65, -2.1999999999999997], + "name": "Wall 29", + "type": "wall", + "start": [4.8500000000000005, -2.2000000000000006], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_7r3uzx0brx1a4b4q": { + "id": "wall_7r3uzx0brx1a4b4q", + "end": [-1.1500000000000001, -0.5999999999999996], + "name": "Wall 30", + "type": "wall", + "start": [-1.1500000000000001, 2.7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_80tg5elrfwtc7oz7": { + "id": "wall_80tg5elrfwtc7oz7", + "end": [-1.15, -4.1000000000000005], + "name": "Wall 31", + "type": "wall", + "start": [-1.1500000000000001, -0.5999999999999996], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_83wyzk7rwzofwzf3": { + "id": "wall_83wyzk7rwzofwzf3", + "end": [-11.200000000000001, -2.4000000000000004], + "name": "Wall 32", + "type": "wall", + "start": [-11.200000000000001, -0.7000000000000002], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_9a728a2ysjptr881": { + "id": "wall_9a728a2ysjptr881", + "end": [4.8500000000000005, -5.300000000000001], + "name": "Wall 33", + "type": "wall", + "start": [4.4, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_9abpqqezx64troz3": { + "id": "wall_9abpqqezx64troz3", + "end": [2.75, -4.1000000000000005], + "name": "Wall 34", + "type": "wall", + "start": [2.75, -2.2000000000000006], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_9k31uc8jk2u7uqpn": { + "id": "wall_9k31uc8jk2u7uqpn", + "end": [-8.8, -2.4000000000000004], + "name": "Wall 35", + "type": "wall", + "start": [-8.8, -6.8500000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_9vt8dh8qsr8juy75": { + "id": "wall_9vt8dh8qsr8juy75", + "end": [4.8500000000000005, -7], + "name": "Wall 36", + "type": "wall", + "start": [7.3500000000000005, -7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_9wy4ffrq8arn7n4u": { + "id": "wall_9wy4ffrq8arn7n4u", + "end": [-6.222509860992432, 0.3328427970409398], + "name": "Wall 37", + "type": "wall", + "start": [-8.58468999862671, 0.3328427970409398], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_arv9bgdk57g8dqz1": { + "id": "wall_arv9bgdk57g8dqz1", + "end": [-4.600000000000002, 3.700000000000001], + "name": "Wall 38", + "type": "wall", + "start": [-4.600000000000002, 12.85], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_bcyrsdo7zqnc3s21": { + "id": "wall_bcyrsdo7zqnc3s21", + "end": [-8.8, -10.850000000000001], + "name": "Wall 39", + "type": "wall", + "start": [-8.8, -9.099999999999998], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_bflxf13uzw2xb4l2": { + "id": "wall_bflxf13uzw2xb4l2", + "end": [7.25, -8.950000000000001], + "name": "Wall 40", + "type": "wall", + "start": [11.55, -8.950000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_bi7h35j9ge67ykji": { + "id": "wall_bi7h35j9ge67ykji", + "end": [7.65, -2.2], + "name": "Wall 41", + "type": "wall", + "start": [7.65, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_bko5rt2dtym70za9": { + "id": "wall_bko5rt2dtym70za9", + "end": [-8.8, -3.500000000000001], + "name": "Wall 42", + "type": "wall", + "start": [-10.65, -3.5000000000000018], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_bsar86a3l1wpskgf": { + "id": "wall_bsar86a3l1wpskgf", + "end": [-4.65, -9.099999999999998], + "name": "Wall 43", + "type": "wall", + "start": [-8.8, -9.099999999999998], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_bx6ymi0g0dl4x6o1": { + "id": "wall_bx6ymi0g0dl4x6o1", + "end": [11.55, -2.1999999999999997], + "name": "Wall 44", + "type": "wall", + "start": [10.500000000000002, -2.2], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_bxwzvhr8l4hsr47z": { + "id": "wall_bxwzvhr8l4hsr47z", + "end": [-7.814762020111084, -2.4000000000000004], + "name": "Wall 45", + "type": "wall", + "start": [-8.8, -2.4000000000000004], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_cb0ax07tzuung5tf": { + "id": "wall_cb0ax07tzuung5tf", + "end": [-1.9504812955856323, 2.9499636829170583], + "name": "Wall 46", + "type": "wall", + "start": [-3.7828824995228247, 2.9499636829170583], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_cemxdd3k9dbs6sed": { + "id": "wall_cemxdd3k9dbs6sed", + "end": [-8.8, -3.500000000000001], + "name": "Wall 47", + "type": "wall", + "start": [-8.8, -5.5], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_clve8apgc7b2p69f": { + "id": "wall_clve8apgc7b2p69f", + "end": [-8.8, -2.4000000000000004], + "name": "Wall 48", + "type": "wall", + "start": [-11.200000000000001, -2.4000000000000004], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_d0vwa6yyw2zvwqdm": { + "id": "wall_d0vwa6yyw2zvwqdm", + "end": [7.65, -2.2], + "name": "Wall 49", + "type": "wall", + "start": [4.800000000000001, -2.2000000000000006], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_d2mm3w3ywi51y1n2": { + "id": "wall_d2mm3w3ywi51y1n2", + "end": [-12.100000000000001, -6.8500000000000005], + "name": "Wall 50", + "type": "wall", + "start": [-12.100000000000001, -2.4000000000000004], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_de5ljzue19kk9uqp": { + "id": "wall_de5ljzue19kk9uqp", + "end": [-8.8, -10.6], + "name": "Wall 51", + "type": "wall", + "start": [-8.8, -6.850000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_dhd67j1jey4bdzq8": { + "id": "wall_dhd67j1jey4bdzq8", + "end": [-10.65, 0.0999999999999992], + "name": "Wall 52", + "type": "wall", + "start": [-8.8, 0.09999999999999955], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_dkyi80b41rxc2w5t": { + "id": "wall_dkyi80b41rxc2w5t", + "end": [-12.2, 3.700000000000001], + "name": "Wall 53", + "type": "wall", + "start": [-12.200000000000001, 2.5], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_e1dah0rxo0ux85ab": { + "id": "wall_e1dah0rxo0ux85ab", + "end": [-4.65, -5.5], + "name": "Wall 54", + "type": "wall", + "start": [-4.65, -9.099999999999998], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_eg8ddtxhylgdmfvr": { + "id": "wall_eg8ddtxhylgdmfvr", + "end": [-6.4, -3.5], + "name": "Wall 55", + "type": "wall", + "start": [-8.8, -3.500000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_esp9np5asorngq8r": { + "id": "wall_esp9np5asorngq8r", + "end": [7.25, -8.950000000000001], + "name": "Wall 56", + "type": "wall", + "start": [7.25, -9], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_fgrxy0ud4kb8r3do": { + "id": "wall_fgrxy0ud4kb8r3do", + "end": [-12.200000000000001, 2.6], + "name": "Wall 57", + "type": "wall", + "start": [-11.200000000000001, 2.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_fzewqha8iks5e9n2": { + "id": "wall_fzewqha8iks5e9n2", + "end": [4.800000000000001, -2.2000000000000006], + "name": "Wall 58", + "type": "wall", + "start": [2.7, -2.2], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_g45kaayl64w6gwty": { + "id": "wall_g45kaayl64w6gwty", + "end": [-1.1500000000000001, 0.046331338584423065], + "name": "Wall 59", + "type": "wall", + "start": [-1.1500000000000001, 2.0500000000000003], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_gelii8915cpricn2": { + "id": "wall_gelii8915cpricn2", + "end": [-7.814762020111084, -2.4000000000000004], + "name": "Wall 60", + "type": "wall", + "start": [-7.814762020111084, -0.7000000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_giq6o2jv191f4c04": { + "id": "wall_giq6o2jv191f4c04", + "end": [7.25, -8.950000000000001], + "name": "Wall 61", + "type": "wall", + "start": [7.25, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_h3g5me7ycwtckkdp": { + "id": "wall_h3g5me7ycwtckkdp", + "end": [-6.4, -3.5], + "name": "Wall 62", + "type": "wall", + "start": [-6.4, -1.55], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_hf1hnv98l7zi1a2e": { + "id": "wall_hf1hnv98l7zi1a2e", + "end": [11.65, -7], + "name": "Wall 63", + "type": "wall", + "start": [11.65, -2.1999999999999997], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "curveOffset": 0, + "metadata": {} + }, + "wall_hj4od1lq7ee115vp": { + "id": "wall_hj4od1lq7ee115vp", + "end": [-1.1500000000000001, -0.5999999999999996], + "name": "Wall 64", + "type": "wall", + "start": [2.75, -0.6000000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_hlrb1lfhyn47ge9l": { + "id": "wall_hlrb1lfhyn47ge9l", + "end": [-6.4, 3.7], + "name": "Wall 65", + "type": "wall", + "start": [-4.6000000000000005, 3.7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_i2bfoghv3php76h8": { + "id": "wall_i2bfoghv3php76h8", + "end": [-12.200000000000001, 2.6], + "name": "Wall 66", + "type": "wall", + "start": [-12.200000000000001, 12.850000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_i2ux2hcxqwqujyoc": { + "id": "wall_i2ux2hcxqwqujyoc", + "end": [-10.65, -1.55], + "name": "Wall 67", + "type": "wall", + "start": [-8.8, -1.5500000000000003], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_inzfl4yi21uph0ao": { + "id": "wall_inzfl4yi21uph0ao", + "end": [1.4500000000000002, -2.2], + "name": "Wall 68", + "type": "wall", + "start": [2.7, -2.2], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_j0l3mahx57xxnhqq": { + "id": "wall_j0l3mahx57xxnhqq", + "end": [2, -7], + "name": "Wall 69", + "type": "wall", + "start": [2, -9], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_jns4zro6kz7sqldv": { + "id": "wall_jns4zro6kz7sqldv", + "end": [4.8500000000000005, -4.1000000000000005], + "name": "Wall 70", + "type": "wall", + "start": [2.75, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_k071rw8oo526au7d": { + "id": "wall_k071rw8oo526au7d", + "end": [-4.65, -10.6], + "name": "Wall 71", + "type": "wall", + "start": [-8.8, -10.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_kk2nwb3btc6iu4w3": { + "id": "wall_kk2nwb3btc6iu4w3", + "end": [-4.65, -5.5], + "name": "Wall 72", + "type": "wall", + "start": [-6.4, -5.5], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_kv4jpp0jwlzce5kr": { + "id": "wall_kv4jpp0jwlzce5kr", + "end": [-4.65, -10.8], + "name": "Wall 73", + "type": "wall", + "start": [-4.65, -10.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_lfgxwdm8qae14chx": { + "id": "wall_lfgxwdm8qae14chx", + "end": [-4.599999999999999, 12.85], + "name": "Wall 74", + "type": "wall", + "start": [-4.6000000000000005, 2.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_lx2bbjephzhlwlit": { + "id": "wall_lx2bbjephzhlwlit", + "end": [4.800000000000001, -5.300000000000001], + "name": "Wall 75", + "type": "wall", + "start": [4.800000000000001, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_m5tugtlndhttk09d": { + "id": "wall_m5tugtlndhttk09d", + "end": [-10.65, -6.8500000000000005], + "name": "Wall 76", + "type": "wall", + "start": [-10.65, -3.5000000000000018], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_mtksisg7659kkdn4": { + "id": "wall_mtksisg7659kkdn4", + "end": [-1.1500000000000001, 2.7], + "name": "Wall 77", + "type": "wall", + "start": [2.75, 2.7], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_n7sbrl3tk4pg09kt": { + "id": "wall_n7sbrl3tk4pg09kt", + "end": [2, -9], + "name": "Wall 78", + "type": "wall", + "start": [2, -10.850000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_nek4upjurlh9nxf8": { + "id": "wall_nek4upjurlh9nxf8", + "end": [-10.65, -1.55], + "name": "Wall 79", + "type": "wall", + "start": [-10.65, 0.0999999999999992], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_nekwddigmgj41xly": { + "id": "wall_nekwddigmgj41xly", + "end": [2, -10.850000000000001], + "name": "Wall 80", + "type": "wall", + "start": [-4.65, -10.850000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_ny4bn42a3j2y9oqn": { + "id": "wall_ny4bn42a3j2y9oqn", + "end": [-4.6000000000000005, 2.6], + "name": "Wall 81", + "type": "wall", + "start": [-8.58468999862671, 2.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_o1f1wr438jg06osc": { + "id": "wall_o1f1wr438jg06osc", + "end": [-8.8, -5.5], + "name": "Wall 82", + "type": "wall", + "start": [-6.4, -5.5], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_okbabynvp1ox8k8e": { + "id": "wall_okbabynvp1ox8k8e", + "end": [10.500000000000002, -4.1000000000000005], + "name": "Wall 83", + "type": "wall", + "start": [7.65, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_oumanwmgne53ij81": { + "id": "wall_oumanwmgne53ij81", + "end": [2, -4.1000000000000005], + "name": "Wall 84", + "type": "wall", + "start": [2.75, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_oyd52368liwh43kq": { + "id": "wall_oyd52368liwh43kq", + "end": [-10.65, -3.5000000000000018], + "name": "Wall 85", + "type": "wall", + "start": [-10.65, -1.55], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_p67hweyoxonva0bw": { + "id": "wall_p67hweyoxonva0bw", + "end": [4.800000000000001, -5.300000000000001], + "name": "Wall 86", + "type": "wall", + "start": [1.9000000000000001, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_pm1fq2nbz9tqav9j": { + "id": "wall_pm1fq2nbz9tqav9j", + "end": [2.7, -0.6999999999999995], + "name": "Wall 87", + "type": "wall", + "start": [2.7, 2.0500000000000003], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_pto2lk1jmln8hq5d": { + "id": "wall_pto2lk1jmln8hq5d", + "end": [1.9000000000000001, -10.8], + "name": "Wall 88", + "type": "wall", + "start": [1.9000000000000001, -9], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_pvztprq1mnr5h8cs": { + "id": "wall_pvztprq1mnr5h8cs", + "end": [-8.8, -9.099999999999998], + "name": "Wall 89", + "type": "wall", + "start": [-8.8, -6.850000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_pz2x1y3st9p8ypww": { + "id": "wall_pz2x1y3st9p8ypww", + "end": [4.8500000000000005, -9], + "name": "Wall 90", + "type": "wall", + "start": [7.3500000000000005, -9], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_q447bsxozcoqvh0l": { + "id": "wall_q447bsxozcoqvh0l", + "end": [4.8500000000000005, -9], + "name": "Wall 91", + "type": "wall", + "start": [4.8500000000000005, -7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_q5tdio97jcu6wo5m": { + "id": "wall_q5tdio97jcu6wo5m", + "end": [-8.8, -6.8500000000000005], + "name": "Wall 92", + "type": "wall", + "start": [-10.65, -6.8500000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_qavc0v0zjyiv5bz5": { + "id": "wall_qavc0v0zjyiv5bz5", + "end": [1.9000000000000001, -9], + "name": "Wall 93", + "type": "wall", + "start": [1.9000000000000001, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_qgif8rd24j89dj6x": { + "id": "wall_qgif8rd24j89dj6x", + "end": [7.25, -5.300000000000001], + "name": "Wall 94", + "type": "wall", + "start": [4.800000000000001, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_qimltm9wal10niug": { + "id": "wall_qimltm9wal10niug", + "end": [-1.1500000000000001, 2.478200674057007], + "name": "Wall 95", + "type": "wall", + "start": [-1.1500000000000001, 2.0500000000000003], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_qlf6256c007rwfd0": { + "id": "wall_qlf6256c007rwfd0", + "end": [-1.1500000000000001, 2.478200674057007], + "name": "Wall 96", + "type": "wall", + "start": [-1.9504812955856323, 2.9499636829170583], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_qp1gvxgf72shys6i": { + "id": "wall_qp1gvxgf72shys6i", + "end": [4.8500000000000005, -2.2000000000000006], + "name": "Wall 97", + "type": "wall", + "start": [4.8500000000000005, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_qvuprki6cdsqs169": { + "id": "wall_qvuprki6cdsqs169", + "end": [-4.600000000000002, 12.85], + "name": "Wall 98", + "type": "wall", + "start": [-12.2, 12.85], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_qyn0nhtk0nnxawen": { + "id": "wall_qyn0nhtk0nnxawen", + "end": [-12.100000000000001, -2.4000000000000004], + "name": "Wall 99", + "type": "wall", + "start": [-11.200000000000001, -2.4000000000000004], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_rewbpncg7vmeaop7": { + "id": "wall_rewbpncg7vmeaop7", + "end": [-8.8, -6.8500000000000005], + "name": "Wall 100", + "type": "wall", + "start": [-12.100000000000001, -6.8500000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_rssuy6dz7dtrctmp": { + "id": "wall_rssuy6dz7dtrctmp", + "end": [1.4500000000000002, -0.6999999999999997], + "name": "Wall 101", + "type": "wall", + "start": [1.4500000000000002, -2.2], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_s48sxetpi7o3gvrs": { + "id": "wall_s48sxetpi7o3gvrs", + "end": [2.7, -2.2], + "name": "Wall 102", + "type": "wall", + "start": [2.7, -0.6999999999999995], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_s7blgpxwcpio9m2n": { + "id": "wall_s7blgpxwcpio9m2n", + "end": [11.65, -9], + "name": "Wall 103", + "type": "wall", + "start": [7.3500000000000005, -9], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_t6gg8azj7kxdnvtw": { + "id": "wall_t6gg8azj7kxdnvtw", + "end": [2, -5.300000000000001], + "name": "Wall 104", + "type": "wall", + "start": [2, -7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_th8zrsiev9gxbs1l": { + "id": "wall_th8zrsiev9gxbs1l", + "end": [1.9000000000000001, -9], + "name": "Wall 105", + "type": "wall", + "start": [7.25, -9], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_txipcza97lx8zpf7": { + "id": "wall_txipcza97lx8zpf7", + "end": [11.65, -7], + "name": "Wall 106", + "type": "wall", + "start": [7.350000000000001, -7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_ujbxn3nw8801fpp8": { + "id": "wall_ujbxn3nw8801fpp8", + "end": [4.8500000000000005, -2.2000000000000006], + "name": "Wall 107", + "type": "wall", + "start": [2.75, -2.2000000000000006], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_ul5fqt3uvowe7fqx": { + "id": "wall_ul5fqt3uvowe7fqx", + "end": [-4.6000000000000005, 0.04633133858442264], + "name": "Wall 108", + "type": "wall", + "start": [-4.6000000000000005, 2.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_un4inmlt4dl4nmq7": { + "id": "wall_un4inmlt4dl4nmq7", + "end": [4.4, -5.300000000000001], + "name": "Wall 109", + "type": "wall", + "start": [2, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_uoip3gdsvljb23po": { + "id": "wall_uoip3gdsvljb23po", + "end": [2.75, -2.2000000000000006], + "name": "Wall 110", + "type": "wall", + "start": [2.75, -0.6000000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_vcvzkm9zad9xmfuq": { + "id": "wall_vcvzkm9zad9xmfuq", + "end": [-11.200000000000001, -0.7000000000000002], + "name": "Wall 111", + "type": "wall", + "start": [-11.200000000000001, 2.6], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_vpkdgmumbxs5027j": { + "id": "wall_vpkdgmumbxs5027j", + "end": [-6.222509860992432, -0.7000000000000001], + "name": "Wall 112", + "type": "wall", + "start": [-6.222509860992432, 0.3328427970409398], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "curveOffset": 0, + "metadata": {} + }, + "wall_vqxt7k1275t6up0o": { + "id": "wall_vqxt7k1275t6up0o", + "end": [-1.1500000000000001, 2.0500000000000003], + "name": "Wall 113", + "type": "wall", + "start": [2.7, 2.0500000000000003], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_wjouuk2cqjsrygvg": { + "id": "wall_wjouuk2cqjsrygvg", + "end": [1.9000000000000001, -10.8], + "name": "Wall 114", + "type": "wall", + "start": [-4.65, -10.8], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_wl71xgc4r1l586t4": { + "id": "wall_wl71xgc4r1l586t4", + "end": [-5.362346649169922, -0.7000000000000001], + "name": "Wall 115", + "type": "wall", + "start": [-7.814762020111084, -0.7000000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_x8d9dtpcogghzqnx": { + "id": "wall_x8d9dtpcogghzqnx", + "end": [-8.58468999862671, -0.7000000000000001], + "name": "Wall 116", + "type": "wall", + "start": [-11.200000000000001, -0.7000000000000002], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_xgy27t8le1opjn3g": { + "id": "wall_xgy27t8le1opjn3g", + "end": [7.65, -4.1000000000000005], + "name": "Wall 117", + "type": "wall", + "start": [4.800000000000001, -4.1000000000000005], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_xk4wf946frjxim30": { + "id": "wall_xk4wf946frjxim30", + "end": [-8.58468999862671, -0.7000000000000001], + "name": "Wall 118", + "type": "wall", + "start": [-7.814762020111084, -0.7000000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_xn4izbntnbhbf4jv": { + "id": "wall_xn4izbntnbhbf4jv", + "end": [2.7, -0.6999999999999995], + "name": "Wall 119", + "type": "wall", + "start": [1.4500000000000002, -0.6999999999999997], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_xtkgw1j3a2fvapsg": { + "id": "wall_xtkgw1j3a2fvapsg", + "end": [-1.1500000000000001, 2.7], + "name": "Wall 120", + "type": "wall", + "start": [-4.6000000000000005, 2.7489473819732666], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_xx35bid80e7y7gc0": { + "id": "wall_xx35bid80e7y7gc0", + "end": [-8.8, 0.09999999999999955], + "name": "Wall 121", + "type": "wall", + "start": [-6.4, 0.1], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_y1a4ynmtfl3yb83j": { + "id": "wall_y1a4ynmtfl3yb83j", + "end": [-8.8, -1.5500000000000003], + "name": "Wall 122", + "type": "wall", + "start": [-6.4, -1.55], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_ypibpadbjjse5pya": { + "id": "wall_ypibpadbjjse5pya", + "end": [2.75, -0.6000000000000001], + "name": "Wall 123", + "type": "wall", + "start": [2.75, 2.7], + "height": 0.1, + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_z2nx8u8ngagp8un2": { + "id": "wall_z2nx8u8ngagp8un2", + "end": [4.8500000000000005, -7], + "name": "Wall 124", + "type": "wall", + "start": [4.8500000000000005, -5.300000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_zecc9dzj41id81tu": { + "id": "wall_zecc9dzj41id81tu", + "end": [2, -9], + "name": "Wall 125", + "type": "wall", + "start": [4.8500000000000005, -9], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "wall_zm3i4g3rmmw1mgrg": { + "id": "wall_zm3i4g3rmmw1mgrg", + "end": [-4.599999999999999, 12.85], + "name": "Wall 126", + "type": "wall", + "start": [-12.200000000000001, 12.850000000000001], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_zpcv29o5x5svptyz": { + "id": "wall_zpcv29o5x5svptyz", + "end": [1.4500000000000002, -0.7000000000000006], + "name": "Wall 127", + "type": "wall", + "start": [-0.3545262813568115, -0.7000000000000004], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "wall_zucern9u1g4572vl": { + "id": "wall_zucern9u1g4572vl", + "end": [-10.65, 3.7], + "name": "Wall 128", + "type": "wall", + "start": [-6.4, 3.7], + "object": "node", + "visible": true, + "children": [], + "parentId": "level_3xsbeo3c6y50zj52", + "metadata": {} + }, + "zone_n9k4mfvcwjh1tqx2": { + "id": "zone_n9k4mfvcwjh1tqx2", + "name": "Zone 1", + "type": "zone", + "color": "#f97316", + "object": "node", + "polygon": [ + [-12.200000000000001, -2.3000000000000003], + [-8.85, -2.3000000000000003], + [-8.85, -6.800000000000001], + [-12.200000000000001, -6.800000000000001] + ], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "zone_s4z1nrumghxthivq": { + "id": "zone_s4z1nrumghxthivq", + "name": "Zone 2", + "type": "zone", + "color": "#10b981", + "object": "node", + "polygon": [[-12.200000000000001, 12.9], [-4.65, 12.9], [-4.65, 2.5], [-12.25, 2.5]], + "visible": true, + "parentId": "level_fkoejbpxrc8pfko1", + "metadata": {} + }, + "level_3xsbeo3c6y50zj52": { + "id": "level_3xsbeo3c6y50zj52", + "name": "Level 2", + "type": "level", + "level": 1, + "height": 2.55, + "object": "node", + "visible": true, + "children": [ + "wall_pvztprq1mnr5h8cs", + "wall_oumanwmgne53ij81", + "wall_bsar86a3l1wpskgf", + "wall_nekwddigmgj41xly", + "wall_mtksisg7659kkdn4", + "wall_9abpqqezx64troz3", + "wall_jns4zro6kz7sqldv", + "wall_ujbxn3nw8801fpp8", + "wall_qp1gvxgf72shys6i", + "slab_tnpnlsfjmbfvvgcy", + "wall_7db1eoza5wt17d7x", + "wall_7avku9vio7cqwt3s", + "wall_t6gg8azj7kxdnvtw", + "wall_17qu7aft5i74sh6e", + "wall_hf1hnv98l7zi1a2e", + "wall_un4inmlt4dl4nmq7", + "wall_9a728a2ysjptr881", + "wall_n7sbrl3tk4pg09kt", + "wall_j0l3mahx57xxnhqq", + "wall_9vt8dh8qsr8juy75", + "wall_4xg3dvyuqp9ewlpq", + "wall_z2nx8u8ngagp8un2", + "slab_5hy9p72gdb0m2f1f", + "wall_pz2x1y3st9p8ypww", + "wall_zecc9dzj41id81tu", + "slab_5nurv3do0357hcz9", + "wall_q447bsxozcoqvh0l", + "slab_fi4tbwv3mf7q3coa", + "wall_3lr2au8fkvlhftx3", + "wall_7r3uzx0brx1a4b4q", + "wall_80tg5elrfwtc7oz7", + "wall_ypibpadbjjse5pya", + "wall_uoip3gdsvljb23po", + "slab_3i30zvxb4fr7ex82", + "wall_hj4od1lq7ee115vp", + "slab_7wkiq3j1hagqs2r6", + "wall_xtkgw1j3a2fvapsg", + "wall_66at0a2mbvetvok1", + "wall_q5tdio97jcu6wo5m", + "wall_hlrb1lfhyn47ge9l", + "wall_zucern9u1g4572vl", + "wall_kk2nwb3btc6iu4w3", + "wall_3nzlcr50iii7d7jn", + "wall_o1f1wr438jg06osc", + "wall_1f5xy4zsjuwew7kp", + "wall_m5tugtlndhttk09d", + "wall_2h0cu6e19qnem55k", + "slab_srszhqarv69ftxcp", + "wall_bko5rt2dtym70za9", + "wall_eg8ddtxhylgdmfvr", + "wall_xx35bid80e7y7gc0", + "wall_dhd67j1jey4bdzq8", + "wall_cemxdd3k9dbs6sed", + "slab_93ch0zszrvd25dqh", + "wall_5repmbaa8v3d0yma", + "wall_e1dah0rxo0ux85ab", + "slab_rgb0fbygk7pe0mx9", + "wall_30a8ksc63pweh8is", + "wall_bcyrsdo7zqnc3s21", + "slab_7pa8krrc3l8ximvy", + "slab_0v814k5ut07aug28", + "wall_2q1g6ej5zhdeim5a", + "wall_1hvhcnagt0h3mavo", + "wall_h3g5me7ycwtckkdp", + "slab_1otds1gkd2nsqbyg", + "wall_y1a4ynmtfl3yb83j", + "slab_tys0vvdtv9uvf79j", + "wall_nek4upjurlh9nxf8", + "wall_oyd52368liwh43kq", + "wall_i2ux2hcxqwqujyoc", + "slab_lyxyjxzp6vfrfqra", + "wall_74dkbkdfrygvnfa0", + "wall_qvuprki6cdsqs169", + "wall_arv9bgdk57g8dqz1", + "slab_h8pdakankbh7nu0n", + "wall_0jkp9omzwb3gnx49", + "wall_4av6d0oa9nnk0j8b", + "slab_k10vjdavfbkblcar", + "wall_2rwmin5i5b36sply", + "wall_dkyi80b41rxc2w5t", + "wall_txipcza97lx8zpf7", + "slab_ssjc0k843ljb7djq", + "wall_s7blgpxwcpio9m2n", + "wall_2ui76g9d7m1lry4r", + "slab_l25hzcqh95xfyahj" + ], + "parentId": "building_eptuyxdfmohgin94", + "baseElevation": 0, + "metadata": {} + }, + "level_fkoejbpxrc8pfko1": { + "id": "level_fkoejbpxrc8pfko1", + "name": "Level 1", + "type": "level", + "level": 0, + "height": 2.55, + "object": "node", + "visible": true, + "children": [ + "wall_2yuniixkeuggttjq", + "wall_fgrxy0ud4kb8r3do", + "wall_zm3i4g3rmmw1mgrg", + "wall_vcvzkm9zad9xmfuq", + "wall_83wyzk7rwzofwzf3", + "wall_ny4bn42a3j2y9oqn", + "wall_qyn0nhtk0nnxawen", + "wall_d2mm3w3ywi51y1n2", + "wall_rewbpncg7vmeaop7", + "wall_clve8apgc7b2p69f", + "wall_bxwzvhr8l4hsr47z", + "wall_9k31uc8jk2u7uqpn", + "wall_de5ljzue19kk9uqp", + "wall_inzfl4yi21uph0ao", + "wall_k071rw8oo526au7d", + "wall_kv4jpp0jwlzce5kr", + "wall_wjouuk2cqjsrygvg", + "wall_g45kaayl64w6gwty", + "wall_rssuy6dz7dtrctmp", + "wall_pm1fq2nbz9tqav9j", + "wall_xn4izbntnbhbf4jv", + "wall_vqxt7k1275t6up0o", + "wall_i2bfoghv3php76h8", + "wall_s48sxetpi7o3gvrs", + "slab_o29p9hn5ky4vtljm", + "wall_fzewqha8iks5e9n2", + "wall_1z7b8yjkeqz6a8zv", + "wall_xgy27t8le1opjn3g", + "wall_d0vwa6yyw2zvwqdm", + "wall_bi7h35j9ge67ykji", + "slab_tv8otyj1dlo8jw89", + "wall_bflxf13uzw2xb4l2", + "wall_giq6o2jv191f4c04", + "wall_p67hweyoxonva0bw", + "wall_qgif8rd24j89dj6x", + "wall_lx2bbjephzhlwlit", + "slab_lxyzotdbs7qyikwj", + "slab_uoix7n2xs9z4w9yp", + "wall_x8d9dtpcogghzqnx", + "wall_wl71xgc4r1l586t4", + "wall_6vuxw1jkte7hc2wc", + "wall_gelii8915cpricn2", + "slab_icuk9ja7lb9yco3w", + "zone_s4z1nrumghxthivq", + "zone_n9k4mfvcwjh1tqx2", + "wall_qavc0v0zjyiv5bz5", + "wall_pto2lk1jmln8hq5d", + "wall_th8zrsiev9gxbs1l", + "slab_16d6d5w2s2aninah", + "wall_5q4v1c6bveqd9jpy", + "wall_6wxm2rp5ttawnjqv", + "slab_y00qwmm7b0bfptwl", + "wall_okbabynvp1ox8k8e", + "wall_11wljyr3yx5wmcjz", + "slab_xmqxds2r7q53o0ad", + "wall_1sm7luej94sbqhh1", + "wall_bx6ymi0g0dl4x6o1", + "wall_1kfnfkeabjndptr1", + "slab_bve5a81ey998z2x4", + "wall_lfgxwdm8qae14chx", + "slab_8c6hj3s05zq2a6nv", + "wall_xk4wf946frjxim30", + "wall_9wy4ffrq8arn7n4u", + "wall_vpkdgmumbxs5027j", + "slab_edqefr7kc95fjqya", + "wall_zpcv29o5x5svptyz", + "wall_004xqitnygtz8po2", + "slab_8fe9i0rab3gkqx6v", + "wall_ul5fqt3uvowe7fqx", + "wall_0nug08l14z8ay1qi", + "slab_yx1lw111nbjz1g6k", + "wall_72j4dhw3w70fuq15", + "wall_cb0ax07tzuung5tf", + "wall_qimltm9wal10niug", + "wall_qlf6256c007rwfd0", + "slab_zfmvjc8vx1r7yy94", + "wall_esp9np5asorngq8r", + "slab_ovdx0dr2t9mrx7p1" + ], + "parentId": "building_eptuyxdfmohgin94", + "baseElevation": 0, + "metadata": {} + }, + "building_eptuyxdfmohgin94": { + "id": "building_eptuyxdfmohgin94", + "type": "building", + "object": "node", + "visible": true, + "children": ["level_fkoejbpxrc8pfko1", "level_3xsbeo3c6y50zj52"], + "parentId": "site_t0flznd65l9tu3a0", + "position": [0, 0, 0], + "rotation": [0, 0, 0], + "metadata": {} + } + }, + "rootNodeIds": ["site_t0flznd65l9tu3a0"] +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-06.json b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-06.json new file mode 100644 index 0000000000..d2df51bcf4 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-06.json @@ -0,0 +1,826 @@ +{ + "door_2aqtp3bbhh4w2nfq": { + "id": "door_2aqtp3bbhh4w2nfq", + "name": "Door 4", + "side": "front", + "type": "door", + "width": 1.5, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_o0nelm7kpx6ug0z8", + "visible": true, + "doorType": "double", + "metadata": {}, + "panicBar": false, + "parentId": "wall_o0nelm7kpx6ug0z8", + "position": [2.5, 1.05, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 2, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_hevuqxh71i5bal3j": { + "id": "door_hevuqxh71i5bal3j", + "name": "Door 4", + "side": "front", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_xby1k4v6ia77afnk", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_xby1k4v6ia77afnk", + "position": [0.5, 1.05, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_ir7oqtz6sqlozxko": { + "id": "door_ir7oqtz6sqlozxko", + "name": "Door 4", + "side": "front", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_smy179n53jxfx2lj", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_smy179n53jxfx2lj", + "position": [2, 1.05, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_k0ae7ahamiva2nxj": { + "id": "door_k0ae7ahamiva2nxj", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_q1qi6afm0aochz9p", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_q1qi6afm0aochz9p", + "position": [1, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_sewdhekqvtodswrn": { + "id": "door_sewdhekqvtodswrn", + "name": "Door 4", + "side": "front", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_i3tbng9xrzrivns7", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_i3tbng9xrzrivns7", + "position": [1, 1.05, 0], + "rotation": [0, 0, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "door_tncm6mua2azni0ge": { + "id": "door_tncm6mua2azni0ge", + "name": "Door 4", + "side": "back", + "type": "door", + "width": 0.9, + "handle": true, + "height": 2.1, + "object": "node", + "wallId": "wall_z7zvosbuwgj2qve1", + "visible": true, + "doorType": "hinged", + "metadata": {}, + "panicBar": false, + "parentId": "wall_z7zvosbuwgj2qve1", + "position": [1, 1.05, 0], + "rotation": [0, 3.141592653589793, 0], + "segments": [ + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.4, + "columnRatios": [1], + "dividerThickness": 0.03 + }, + { + "type": "panel", + "panelDepth": 0.01, + "panelInset": 0.04, + "heightRatio": 0.6, + "columnRatios": [1], + "dividerThickness": 0.03 + } + ], + "leafCount": 1, + "threshold": true, + "archHeight": 0.45, + "doorCloser": false, + "frameDepth": 0.07, + "handleSide": "right", + "hingesSide": "left", + "swingAngle": 0, + "trackStyle": "none", + "openingKind": "door", + "cornerRadius": 0.15, + "doorCategory": "interior", + "handleHeight": 1.05, + "openingShape": "rectangle", + "contentPadding": [0.04, 0.04], + "frameThickness": 0.05, + "operationState": 0, + "panicBarHeight": 1, + "slideDirection": "left", + "swingDirection": "inward", + "openingTopRadii": [0.15, 0.15], + "thresholdHeight": 0.02, + "constructionType": "framed", + "garagePanelCount": 4, + "openingRadiusMode": "all", + "dimensionReference": "nominal", + "openingRevealRadius": 0.025 + }, + "site_0f12j15blguckrgx": { + "id": "site_0f12j15blguckrgx", + "type": "site", + "object": "node", + "polygon": { + "type": "polygon", + "points": [[-15, -15], [15, -15], [15, 15], [-15, 15]] + }, + "visible": true, + "children": ["building_12m3u1alysc4l0yc"], + "metadata": {}, + "parentId": null + }, + "slab_6pg5mnzx1t93kbnl": { + "id": "slab_6pg5mnzx1t93kbnl", + "name": "Room 4 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-1.5, 1], [2, 1], [2, 4], [-1.5, 4]], + "visible": true, + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_ks9zda58338aztoc": { + "id": "slab_ks9zda58338aztoc", + "name": "Room 5 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-1.5, -6], [-1.5, -1], [-4.5, -1], [-4.5, -6]], + "visible": true, + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "recessed": false, + "elevation": 2.5500000476837155, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_pqxe3rn1l2bcxhwq": { + "id": "slab_pqxe3rn1l2bcxhwq", + "name": "Room 3 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[4, 1], [4, 4], [2, 4], [2, 1]], + "visible": true, + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_tzcuoq1941bcs7il": { + "id": "slab_tzcuoq1941bcs7il", + "name": "Room 1 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[4, -6], [4, -1], [-1.5, -1], [-1.5, -6]], + "visible": true, + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_w2l135zz4wsfqyn7": { + "id": "slab_w2l135zz4wsfqyn7", + "name": "Room 6 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[-1.5, 4], [-4.5, 4], [-4.5, -1], [-3, -1], [-3, 1], [-1.5, 1]], + "visible": true, + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_xwmumkn5sw078iop": { + "id": "slab_xwmumkn5sw078iop", + "name": "Room 2 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [[4, -1], [4, 1], [-3, 1], [-3, -1]], + "visible": true, + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "wall_05z9wfz6fhh7mukw": { + "id": "wall_05z9wfz6fhh7mukw", + "end": [-4.5, 4], + "name": "Wall 18", + "type": "wall", + "start": [-4.5, -1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "exterior" + }, + "wall_16v517ndn18j5sxc": { + "id": "wall_16v517ndn18j5sxc", + "end": [4, -1], + "name": "Wall 1", + "type": "wall", + "start": [4, -6], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_1hdehjz2jh9j9w9k": { + "id": "wall_1hdehjz2jh9j9w9k", + "end": [-4.5, -6], + "name": "Wall 16", + "type": "wall", + "start": [-1.5, -6], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "exterior", + "supportOffset": 2.5000000476837156, + "supportSlabId": "ground" + }, + "wall_22p9eqz8eathvpu5": { + "id": "wall_22p9eqz8eathvpu5", + "end": [-3, 1], + "name": "Wall 20", + "type": "wall", + "start": [-3, -1], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "unknown" + }, + "wall_dnyf1h4nr39rfdou": { + "id": "wall_dnyf1h4nr39rfdou", + "end": [2, 4], + "name": "Wall 9", + "type": "wall", + "start": [4, 4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_g5heiurfy2ob9shg": { + "id": "wall_g5heiurfy2ob9shg", + "end": [-1.5, 1], + "name": "Wall 13", + "type": "wall", + "start": [-1.5, 4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_ht5be5pjorfff0z2": { + "id": "wall_ht5be5pjorfff0z2", + "end": [4, -6], + "name": "Wall 4", + "type": "wall", + "start": [-1.5, -6], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_i3tbng9xrzrivns7": { + "id": "wall_i3tbng9xrzrivns7", + "end": [-3, -1], + "name": "Wall 14", + "type": "wall", + "start": [-1.5, -1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_sewdhekqvtodswrn"], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "exterior" + }, + "wall_jnjulmfyo4qvnn0n": { + "id": "wall_jnjulmfyo4qvnn0n", + "end": [-1.5, 4], + "name": "Wall 19", + "type": "wall", + "start": [-4.5, 4], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "exterior" + }, + "wall_kho22k8abdxcrak0": { + "id": "wall_kho22k8abdxcrak0", + "end": [-1.5, -6], + "name": "Wall 3", + "type": "wall", + "start": [-1.5, -1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_o0nelm7kpx6ug0z8": { + "id": "wall_o0nelm7kpx6ug0z8", + "end": [-1.5, -1], + "name": "Wall 2", + "type": "wall", + "start": [4, -1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_2aqtp3bbhh4w2nfq"], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_q1qi6afm0aochz9p": { + "id": "wall_q1qi6afm0aochz9p", + "end": [2, 1], + "name": "Wall 6", + "type": "wall", + "start": [4, 1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_k0ae7ahamiva2nxj"], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_s2uuv48ybmsykl8u": { + "id": "wall_s2uuv48ybmsykl8u", + "end": [-4.5, -1], + "name": "Wall 17", + "type": "wall", + "start": [-4.5, -6], + "height": 2.5, + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "exterior", + "supportOffset": 2.5000000476837156, + "supportSlabId": "ground" + }, + "wall_shy54y5v8izj58kg": { + "id": "wall_shy54y5v8izj58kg", + "end": [-1.5, 4], + "name": "Wall 12", + "type": "wall", + "start": [2, 4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_smy179n53jxfx2lj": { + "id": "wall_smy179n53jxfx2lj", + "end": [-1.5, 1], + "name": "Wall 6", + "type": "wall", + "start": [2, 1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_ir7oqtz6sqlozxko"], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_vqup0zu0vkv81jq2": { + "id": "wall_vqup0zu0vkv81jq2", + "end": [2, 1], + "name": "Wall 10", + "type": "wall", + "start": [2, 4], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_xby1k4v6ia77afnk": { + "id": "wall_xby1k4v6ia77afnk", + "end": [-1.5, 1], + "name": "Wall 16", + "type": "wall", + "start": [-3, 1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_hevuqxh71i5bal3j"], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "exterior" + }, + "wall_xfx9zh61ceiqa1n9": { + "id": "wall_xfx9zh61ceiqa1n9", + "end": [-4.5, -1], + "name": "Wall 14", + "type": "wall", + "start": [-3, -1], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "exterior" + }, + "wall_yiakvteghkmop0r0": { + "id": "wall_yiakvteghkmop0r0", + "end": [4, 4], + "name": "Wall 8", + "type": "wall", + "start": [4, 1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "wall_z7zvosbuwgj2qve1": { + "id": "wall_z7zvosbuwgj2qve1", + "end": [4, 1], + "name": "Wall 5", + "type": "wall", + "start": [4, -1], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_tncm6mua2azni0ge"], + "metadata": {}, + "parentId": "level_f09pnxcaqxl909qh", + "frontSide": "interior" + }, + "level_f09pnxcaqxl909qh": { + "id": "level_f09pnxcaqxl909qh", + "name": "Level 0", + "type": "level", + "level": 0, + "height": 2.5, + "object": "node", + "visible": true, + "children": [ + "wall_16v517ndn18j5sxc", + "wall_o0nelm7kpx6ug0z8", + "wall_kho22k8abdxcrak0", + "wall_ht5be5pjorfff0z2", + "slab_tzcuoq1941bcs7il", + "wall_z7zvosbuwgj2qve1", + "slab_xwmumkn5sw078iop", + "wall_yiakvteghkmop0r0", + "wall_dnyf1h4nr39rfdou", + "wall_q1qi6afm0aochz9p", + "wall_smy179n53jxfx2lj", + "wall_vqup0zu0vkv81jq2", + "slab_pqxe3rn1l2bcxhwq", + "wall_shy54y5v8izj58kg", + "wall_g5heiurfy2ob9shg", + "slab_6pg5mnzx1t93kbnl", + "wall_1hdehjz2jh9j9w9k", + "wall_s2uuv48ybmsykl8u", + "slab_ks9zda58338aztoc", + "wall_05z9wfz6fhh7mukw", + "wall_jnjulmfyo4qvnn0n", + "slab_w2l135zz4wsfqyn7", + "wall_i3tbng9xrzrivns7", + "wall_xfx9zh61ceiqa1n9", + "wall_xby1k4v6ia77afnk", + "wall_22p9eqz8eathvpu5" + ], + "metadata": {}, + "parentId": "building_12m3u1alysc4l0yc", + "baseElevation": 0 + }, + "building_12m3u1alysc4l0yc": { + "id": "building_12m3u1alysc4l0yc", + "type": "building", + "object": "node", + "visible": true, + "children": ["level_f09pnxcaqxl909qh"], + "metadata": {}, + "parentId": "site_0f12j15blguckrgx", + "position": [0, 0, 0], + "rotation": [0, 0, 0] + } +} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-07.json b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-07.json new file mode 100644 index 0000000000..32571fd0b2 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-07.json @@ -0,0 +1 @@ +{"site_tkuvu0spmm7izov4":{"id":"site_tkuvu0spmm7izov4","type":"site","object":"node","polygon":{"type":"polygon","points":[[-16.213369369506836,-26.351043701171875],[7.894474983215332,-26.900115966796875],[6.56522133375319,-14.661209053979553],[7.299164772033691,-13.522894859313965],[9.905318975448608,-13.523709297180176],[12.011350631713867,-13.343928337097168],[13.464799880981445,-13.34479808807373],[13.666626802052095,-12.099548694339665],[13.628530502319336,-9.279840469360352],[13.801105499267578,-9.481746673583984],[13.720145225524902,-9.449895858764648],[13.792357921600342,3.481708526611328],[13.864570617675781,16.413312911987305],[-16.48482894897461,15.874007225036621]]},"terrain":{"cols":65,"rows":65,"step":0.01,"type":"heightfield","origin":[-16,-16],"heights":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAlACEAFwAQAAsABgADAAEAAAAAAAAAAAAAAAAAAAAAAAAAGAB4AG0AOwBKACAADwALAAQAAgAFAF8AlgC9ALwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAsAHgAfACsAMgAtAFoAdwCRAJgAmQCXAJEAnACsAJAAggB6AHUAbACGALYA1QC4AJIAngCtAJwAvQCfAJQAqACkALQA0ADMAKkAuQH3AWMAYgBcAFAAMwAaAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAHwBHAFAAQgBSAEIAPABOAGoApQDTAMgAtwCaAMEAxADbAO0A6QDdAOIA8ADxAO4A8QDvAPAA8AD1APoAAQEFARoBNAFAATEBBQHgACsB/wBvAHIAdAB4AIIAfwB/AJ0A0wDoAOgA3wDGAJoAXwAAAAAAAAAVAB0AIQApADsATABNAEgAVQBXAFsAfQCSAKMAogB2AJwA0wDZANQAyADAAL4AvwDpAPwA+gD9AAQBAgH+APwA+wD6APoA+QD6APsA/AD+AAsBKgEvAS0BmgGsARcBcgB3AHoAgwCPAJMAmgC3AOcA8ADwAPAA4wC+AIAAAAAAAAAAHgAiACQALAA5AEoASABQAFQAWgBhAHUAjACKAIwAlQDcAN0A0ADOAMAAvgC4AMIA3QD2AAQBAwECAQIBAgEAAf8A/gD+AP4A/wAAAQEBAgENAR4BIQEhAVgBYQFUAZIAhQCJAJEAlgCaAKEAuQDhAO8A8ADwAO8A0wCSAAAAAAAAACMAJgAnAC0APwBHAEQAQwBQAGEAmACSAIkAbQCLALIA5ADmANsAvgC3ALUAvwDPAOEA/wAJAQ8BDQEKAQcBBwEJAQgBCgEIAQgBCgEKARABHAEwATABKAFAAUYBPwHVAL4AoACaAJoAtwABATcB4QDuAPAA8ADwANkAlAAAAAAAAAAiACYAJwArADQAPgA2ADYAPQBaAHAAgwCEAIUAgwDQAOQA4AC+AIkAjwCfAKcA1QD2AAsBDwETARMBFQEWARcBFgEXARcBFgEYARgBGQEkASsBMgE0ATMBOgE8AUEB2gDLAKwAmwCcAB0BOgE9AT4BQAFDAfAA7wDYAJUAAAAAAAAAJgAnACgAKQAwADcAOABQAF0AagBzAHMAgwCHAJAAkADBANwAngB7AJkAoACjANUA9AAMAQ4BEQEVARYBFwEZARkBGQEYARgBGwEfASYBLgExATEBLwEyATYBNAErAR8BLgEtASABNwE9AT0BPQE+AT8BQgH2APMA2gCVAAAAAAAAACkAKQApACoAMABDAEYATgBWAFQAXgBmAHsAgQCTAJcA1wC8AKEAkACZAJEAmQDAAOMA9gAKAQsBDgEQARABEQESARMBFQEYARwBLgEwATMBNQEzATIBMAE1ATcBOAE4ATUBMwE1ATwBPAE9AT4BPgE+AUIBTAH8AOQApAAAAAAAAAAoACoAKwAsADEAQgBDAEQATQBQAFoAdwCGAIcAxgDRANIAsACcAJ0AjQB8AI4ArQDNAOwA+QAEAQsBDgEOAQ8BEQESARMBFQEXASsBNAE1AToBNQE0ATIBNQE3ATgBOAE4AToBPAE7ATwBPAE9AT4BPgFAAUYB/QDtALcAAAAAAAAAJwArAC0ALQAxADsAOQBJAEsAUgBZAHsAhgB1ALUA0QDRAMIAkACNAHsAfgCCAJUA1gDjAOwA+QAHAQQBBQEHAQYBBQEIAQsBEwEeASwBOQFAATsBNwE4ATkBOQE4ATcBOAE5ATkBOwE8ATwBPAE9AT4BQAFBAfMA7QDHAAAAAAAAACkALQAtAC0AMgA5AEwASwBLAEsAUQBWAFoAnQDHANEAgQB3AI4AhQB8AH0AcgB2ALkA3QDpAO0A+gD4APoAAwEHAQcBCQELARQBHgEtAToBQgE9ATkBOQE5AToBOwE5ATkBOAE6ATsBOwE7ATwBPAE9AT0BRgHwAO0AyAAAAAAAAAArAC4ALgAtADMANgBXAFEAUgBYAFIAWQBbAG8AmQBoAG0AbgCaAJIAewBkAGoAdACVAM0A5gDnAOcA6wDvAPQABQEJAQsBDAEUAR0BJwE1ATwBPAE7AToBOgE6AToBOQE6AToBQAFCAT0BPAE+AT4BPQFCATQB8ADtAMoAAAAAAAAALQAxADEAMQAzAEYAVwBbAGcAYAB4AGwAYQBdAGEAVwBKAFUAVQBjAF8AUQB8AH8AjADAAOEA4wDjAOYA8wABAQ4BEAEUARgBHgEfASoBMQEwATIBOAE5AToBOwE6ATkBOQE5ATwBTgFWAVYBWwFgAWABWAEaAfAA7QDMAAAAAAAAACoALQAvAC8AMgA+AFMAVQBTAGIAewBfAFsAYwBdAEsARgBNAD4APwA3AFUAXgA5AFcAlACrAMcAzQDdAOkA/gANARIBGgEcAR8BIAEqATEBMQEkASYBKAEuATkBOQE5ATkBOQE6AUsBVAFTAVYBXAFbAUoBKAHwAO0AzQAAAAAAAAArACsAKwAtADAANQBIAEgARwBTAGYAWABSAFAASABFAEUASAArACcAPQBIAFkAPABJAFsASgBwAGUAqgC5AI0A7ADnAP0AEgEaASABKAEyASgBIAElATQBNAE3ATcBNwE4ATkBOwE8AUcBTQFNAU4BTAFEAUIB8ADsAMoAAAAAAAAAKwArACsALgAwAD4ASABJAEcAUABOAEYARgBHAEYARgBIAEkAKwAoAD4APAA7AD0APwA/AD8AQQA6AEsAVQBYAE0AWQBTAE0ASQCUAPoAwQDSAK8A2AArAS8BNwE3ATcBNgEzATwBSwFRAU8BTgFJAUYBQQE5AfAA7QDLAAAAAAAAACkAKgArAC0AMABBAEgASQBFAEYARgBFAEYARQBFAEYASABRACsAJAA7AD0AOwA5ADsAOQA1ADQAOgA8AEEAPwA8ADwAPQA+AD4AQQChAGoASQBGAIQAKQEoAToBOAE6ATUBNAFKAVcBWAFYAVcBTwFKAUcBQwHwAO0AygAAAAAAAAAjACQAJQAnACwAOQA7AEIARABFAEgAQwBEAEMARABFAE0AUQA4ACkAQAA9AD0AOQA7ADkAMgAxADgAPAA+ADwAPAA8AD0APgA/AEIARwBKADoAPgCoAB8BIAFAAUABPwFCAUIBTwFaAVoBWgFZAVYBUgFOATMB8ADrAMgAAAAAAAAAHwAhACEAIQAnADAAMABAAEMASQBJAEMARABCAEIARgBRAFYAQAA6ADYAOgA5ADkANwA3ADMAMgA/AD4APQA7ADsAOwA9AD4AQQBCAEMAQQA7ADsAawAUAR4BOQFBAUMBOgFEAUkBWwFaAVsBWgFaAVUBSwEZAfAA7ADJAAAAAAAAABYAGAAZABoAHgAiACsARABHAEsASwBHAEgARwBHAFEAWQBgAF0AQAA5ADgAOAA5ADcANwA1ADQAPgA6ADUANgA6ADoAPQBBAEMAQQA/AD0AOwA7AFIAywAeAUQBSQFEAUIBRgFJAVMBVgFaAVsBWwFaAVABLAHwAOoAwgAAAAAAAAAQABEAEQASABEAEAAsAEcARwBLAEsASQBIAEgASgBNAFAAUgBQAEkAOgA3ADYANgA3ADcANgA3ADoAOAAyADQANgA5ADkAQQA8AD4APwA9ADoAOwBSABMBHgFGAUUBRAFEAUYBRAFSAVUBWQFcAVsBWQFUAUEB8ADpAL4AAAAAAAAAEAARABIAEgARABMANABJAEkATQBNAEwARwA+AD4APwA/AEAAPwA8ADgANwA0ADQANAA2ADcAOgA4ADkAMQAyADMANAA6AEIAOgA+AD8APQA6ADoAZAANATABPAFDAUUBRwEyAUMBUAFUAVYBWQFUAVUBUQFBAfAA6gC7AAAAAAAAABEAEQASABIAEQARADMARgBLAE4ATgBOAEUAPwA/AEAAQAA/AD4AOwA4ADkANwA1ADMANAA1ADkANAAyADEAMQAxADIAMgBCAD0APQA9ADsAOgA7AGEADgExATsBQgFDAUUBMgFEAUsBUQFQAU8BTQFLATwBMgHwAOYAsAAAAAAAAAARABEAEgASABEAFAAwAEIARgBIAEYARABCAEEAQQA/AD0AOwA8ADgANwA7ADwANgA0ADEAMQAwADAAMAAxADEAMQAyADQAQgA9ADsAPAA7ADoAQgBSAMgAKQFAAUIBOgFFATsBRQFOAU8BTwFOAU0BTAFJASQB8ADmAKwAAAAAAAAAEgATABMAEwASABQAMgA8AD0APgA9AD0APgA+AEAAPAA9ADsAOwA4ADoAOgA7ADYANQA1ADAALwAvADAAMQAxADEAMwA1ADwAPAA6ADsAOgA8ADoATwAOAR8BOQE6ATcBQAFAAUgBTgFPAU8BTwFRAUwBQQEoAfAA5ACkAAAAAAAAAB8AHwAeAB4AIgAqAD8ARwBGAEUARABDAEEAQAA+AD4APQA9ADkAOAAvAC4AMAAxADAAMQAuAC8AMAAxADAAMQAyADYANQA5ADoAOgA7ADsAOwA4AEEAcgDcACABNAE5ATABQQFHAU0BTwFQAVABUAFNASoB/ADwAN8AlwAAAAAAAAAkACUAJwAoADAAQgBPAFQAVABTAFIAUQBHAD4APgA9AD0APQA2ADAAMAAuAC4ALwAvACwAKwAuADAAMAAxADIAOQA2ADQAOAA6ADoAPAA7ADcANwA5AEcAhwAgASYBMAE+AUgBSQFNAU4BTgFPAU8BTQExAfAA8ADaAI8AAAAAAAAAIgAjACYAKAAxAEMAUABVAFUAVQBKAEcAQQA9AD0APAA7ADkANQAxADIALwAuAC8AKwAqACsALwAwADAAMAAxADQAMwA0ADgAOgA6AEAANAA0ADQAOgBHAJMAGAEmASkBQwFIAUkBTAFNAU0BTQFNAUoBOwH9APAA1gCEAAAAAAAAACIAIgAlACgAMgBDAE8AUwBTAFQARgBAAEEAPwA7ADsAOwA3ADUAMQAwADEAMgAsACkAKQApAC0ALwAwADAAMAAyADEANgA5ADoAOwA9ADIAMgAyADMAOwADAREBJwEPATMBQwE6AUYBRgFIAUYBRQFCAT0BJwHvAM8AewAAAAAAAAAiACIAJAAnADMAQwBOAFUAVwBaAFMARgBCAD4AOwA7ADsANwAzADIALwAuACoAKQApACgAKwArADAAMQAxADEAMgAyADgAOQA6AD4AQQA5ADkAOAA3ADwAYgDkAB4BAAEtATQBOwFCAUIBQwFDAUQBQQE0ASkB7wDOAHcAAAAAAAAAIgAjACQAJwA0AEsAVwBeAGEAYwBgAEkAQgA+ADoAOgA5ADQAMAAwAC4AKgArACkAKQApAC0ALwAwADAAMAAwADEAMQA2ADgANwA6AD0ANgA2ADYANwA+AI4ABwH6AAUBCwENATsBQwFEAUQBRgFFAUIBMgEqAe8AygBxAAAAAAAAACMAIwAkACcAMgBMAFwAYQBjAGMAYwBJAEYAPAA7ADoAOQA0ADAALwArACsAKwArACoAKQAuAC8ALwAvADAAMAAxADEAMgAzADMANAA1ADIAMgAyADIANwC+AAwB/QD5AP0ANwE3ATgBOAE4ATwBQQFDATMBEgHuAMcAbgAAAAAAAAAjACMAJAAmADAARgBZAF8AYQBhAGEAUgBCADwAOgA6ADkANgAwAC8ALQAtAC0AKwAqACsALAAwAC8AMAAxADEAMQAyADYAOAA2ADYANQAyADIAMgAyADMAqQDyAP8A+QD9AC8BOAE5ATkBOQE4ATgBNQEvARAB7wDIAGwAAAAAAAAAIwAjACMAJgAxAEgAWQBeAGAAYQBhAFIARABBAD4AOQA5ADQALwAvAC4ALgAtAC0ALAAsACwAMAA3ADIAMwAyADIAMgA1ADYANQA3ADcAMwAzADMANgA/AL8A7wD4APcAAwE1ATgBNwFAAUABPQE7ATkBLAHyAPAAyQBtAAAAAAAAACIAIwAjACYANgBNAFkAXgBfAGAAXwBKAEkAPgA6ADgANwA0AC8ALwAvAC4ALgAuAC0ALAAuAC4AMAAxADQANAAzADMAPABAADwAQAA+ADMAMwAzADYARADKAOcA9QDyABIBMQE1ATQBPQE9ATwBPQE8ATkBAwHvAMYAaQAAAAAAAAAhACEAIgAlADYARwBSAFUAUQBRAFQAQwA7ADoAOgA4ADYANAAxADEAMQAzADEALQAtAC4ALwAwADEAMQAyADIAMQAxADoAPAA3ADsAOwAyADIAMgA1AEcAxQDiAPAA8wAfAS0BLwE7ATsBPAE8AUABPgE7AR4B7wDDAGYAAAAAAAAAIAAgACAAHwAfACIAOgBGAEsAUgBXAEIAPwA6ADsAOQA1ADMAMgAyADMAMgAyADAALQAtAC8AMAAxADEAMQAxADEANQA6ADsAOAA7ADsANAAzADQANwBYAKgA2gDnAOcA+gAoATQBOQE6AToBOQE5ATsBOwEdAe4AvABgAAAAAAAAAB8AHwAfAB0AFwAkAEQAVQBbAFsAQgBCAD0APAA5ADcAOAA0ADMANAA1ADMAMgAxADAALgAxADAAMQA0ADQANAA0ADkARABFAD4ARQBCADkAOQA6AEEAcwDOANkA5gDrABwBLAEzATkBOwE6ATkBNgE6AT0B8ADrALgAWwAAAAAAAAAfAB8AHwAeACsAQgBUAFwAXQBCAEMAPwBAADkAOAA4ADYANQA0ADUANAA0ADQAMgAyADEAMQAwADIANQA1ADUANgA3AD0APQA6AD4APQA5ADkAOgA8AHQA0ADZAOcA8wAhASYBLAE0ATwBPAE8ATgBPAE6AQcB6wC3AFwAAAAAAAAAHwAfAB8AIAAyAEkAVQBbAF0ARwBGAEkARQA8ADsAOQA6ADYANQA1ADQANAAzADIAMwA0ADQAMwA0ADQANAA0ADQANQA8AD8AOgBFAEcANgA2ADYAOQCWANIA1wDrAPEAGQEgATUBOgE3ATwBPQE6ATwBOwEqAekAsgBZAAAAAAAAAB8AIAAgAB8ALQBGAFQAVwBbAF4AXwBcAFcAQAA6ADoAPAA4ADUANQA1ADUANAAzADMAOAA2ADMAMwA0ADQANAA0ADUAOQA7ADgAPgBBADgAOwA8AD0AZgDHAN8A6gDvACABLwE0ATcBNQE+AUABNQE/ATsBJwHmAK4AVgAAAAAAAAAfACAAHwAfACgAQABXAFoAWwBZAFMATQBIADkAOAA7AD0ANwA2ADYANgA1ADQAMwA1ADcAOQA0ADQANAA0ADQANQA0ADQANQA8AD8APQA7ADsAPAA+AEUAfQDbAOcAAQEDASUBMQEzATYBPgE+ATwBQQE8ASYB5ACsAFYAAAAAAAAAHwAgAB8AHwAmADkAVQBUAE4ASQBDAEAANwA3ADgAOwA7ADcANgA2ADYANgA4ADUANwA3ADYANQA1ADcANQA8ADwAOQA4ADsAQABCAEEAPQA5ADgAQwBZAKEA1wDnAPIA+wAeATUBOQE8AT0BPgE9AT0BMwEeAeAAowBPAAAAAAAAAB8AHwAdAB4AJAAuAEIAQwBAAEAAQABAADcANwA7ADoAOgA6ADgAOAA4ADcAPAA2ADcAOAAzADIAMQA0AEcAQgBCAEUAQABAAFQAXQBHAD8APwA5AD0AXACkANQA4QDvAPkA6AA0ATsBOwE8ATsBPAE6ATYBFQHdAJ8ATwAAAAAAAAAeAB0AGgAbAB8AHgAsAD0APwA/AEAAQABAADsAOgA6AD4AOwA4ADwAOAA4ADgANgA7ADoANQAxADEAMgBAAEkAQgBCAEYAQgBFAEwATQBDAEEAQAA/AGUAsgDeANoA4wDpACIBNAE6AToBOQE5ATgBOAE4ASwB3ACdAEgAAAAAAAAAGQAaABkAGgAcABsAJAA9AD8APwBAAD8AOwA5ADkAPwA7ADsAPQA+ADkAPwA3ADUANwA4ADMAMgAyADMANwA6ADsAQQBCAEAAPwA/AEAAQQBCAEMAQwBXANkA3gDcAO8A8QAuATYBNgE3ATcBNwEzATQBNgEzAdUAkwBEAAAAAAAAABUAGQAZABoAHAAjADMAOwA/AD4APgA7ADgAOAA9AEEAOgA7AEYAQQBCADsANQA2ADUANgA0ADYAOQA5ADkAPAA8ADwAPAA/AD8APwBAAEAAQABAAEIAWQDZANwA4gDrABgBKAEyATYBOgE6AToBMgE1ATABMgHTAJMARAAAAAAAAAAUABgAGQAaABwAMQAzADgAOwA9AD4AOwA4ADwAQABEAD0AQQBIAEsAPAA3ADYAOQA9ADsAOgA5ADkAOQA8ADwAPAA9AD4AQABAAEAAQABAAEAAQABDAFIAogDUAOkAAAEYASYBMQE9AT8BQAFCATIBOAEvATIB0wCPAD4AAAAAAAAAEwAYABoAHQAqADEANQA3ADwAPgA/AD8AQQBCAEQASABMAFEAUgBFAD0AOgA8AD0APQA7ADoAOgA6ADsAQABAAD8APwBBAEAAQABAAEAAQABAAEAAQgBGAFUAowAHAQMBFwEqAToBPgE9AT8BQAE8AT0BKwEqAdIAjAA7AAAAAAAAAA4AFwAcAC4AMAAxADMAOgBAAEEAQwBGAEgASQBMAFQAUgBMAEkASQA+AD8APQA+ADsAOgA6ADsANgA5ADoAPgA9ADwAPgA/AD8AQABBAEAAQABAAEYATgBpANAACAEbARMBMAE9AT0BPQFAAUEBPAE+ASwBJQHRAI0AOwAAAAAAAAAJABQAHAAgACgAIAAmADcAQgBKAFQAXABfAF8AYQBPAE0ATgBOAFAAQwA/ADwAOwA7ADsAOgA2ADIANAA4ADoAPQA+AD4APwA/AD8AQABAAEAAQABGAFgAbQCiAKEAzAAVAS0BPAE8AUMBRQFBATwBPwEoAQsBzwCKADcAAAAAAAAACAAPABoAHQAdAB4AKQA6AEsAXgBoAGwAbQBtAG4AUQBRAFoAZABOAEwAPAA7ADsAPAA5ADYANAAyADQANwA7AD0APgA+AD4APgA+AD8AQABAAEAAQABEAE4AiACgALYAEQElATMBPAFFAUUBMwE8AT0BJgEPAc0AhwA2AAAAAAAAAAgADAAWABwAHQAeAD8AZwBsAHEAcgByAHQAdQB1AHYAdgB4AFQATQA9ADsAOwA9ADsAOQA1ADMAMwA2ADgAPAA9AD4APgA+AEAAQwBAAEAAQABAAEAARgBbAJoAwgA2AT0BOQEnAT4BRAFEATMBOwE+ASYBCwHNAIcANAAAAAAAAAAHAAoAEQAaAB0AHgBRAGoAbgB5AHcAfQCDAIMAhACDAIIAXQBWAEUAPQA8AD0APQA7ADoANwA0ADMANwA3ADkAOgA9ADwAQABDAEQAQwBBAEEAQQBEAE8AsAAfASoBOAE7AUABMgE+AUEBRwFCAUUBOwEjARABzACEADcAAAAAAAAABwAKAA0AFgAcAB4AUABrAHYAgACJAIsAjACMAIwAjAB8AFkASABCAEQAQAA9ADwAOwA8ADwANgAyADcANwA4ADgAOQA6AD0AQwBDAEMAQgBCAEMAQwBsANwAMwEmATcBOQE8AT4BOAEyAVABQAFHAT4BKgEWAcwAiAA5AAAAAAAAAAgACgAKABAAJwA6AFwAagBtAIAAiQCJAIkAiQCJAIoAigBlAFsASQA/ADwAQAA9ADwAPwBBADMANQA5ADgAPAA8AD0APAA8AEUARQBEAEMARQBGAFwApgAsAS0BLAE0AT8BQgFEATkBMAE1ATkBRAFCATsBDQHKAIsAQQAAAAAAAAAKAAoACgALAFAAXQBiAGcAbgBxAHMAdwB5AHoAewB+AIIAhgB0AGYAVgBTAEoAUwBFAE0AggB7AHEAdABTAG4AcgCCAGEAeAChAHYArwCOAKEA1wDtACABJQElASUBJwFMAU0BSgEtATABLwE6AUIBQgErAecAyACJAEEAAAAAAAAACgAKAAoACgAbAFMAZQBwAHAAcQB0AHcAeAB5AHoAfwCFAIUAhgCDAGYAhQBXAFYAaQCBAIIAgwCGAJEAkACdAKwAtQDaAN0A+gDoAPcAGAEjASIBIQEkASUBJQElASQBRwFRAUUBKwElASQBOAFCAUQBKQHxAL0AewA2AAAAAAAAAAYACAAJAAoAFQBCAFAAXgBfAGQAcQB1AHQAdgB3AHoAfAB9AH0AfwB/AH4AfgB/AH4AgQCDAIMAnQC9AL4AzwDfAOkA9wACAQQB8AAMAREBGAEjASEBIwEjASMBIAEcAT4BRwEjAQcBCwETAToBOQFCASQB6QCfAFsAJAAAAAAAAAADAAUABgAHADUASABLAFAAUABZAGYAagBwAHYAeAB7AHwAfAB9AH0AfQB9AH0AfgB9AIAAggCDAIoAuQC9ANgA2wDjAPcAAQEDAdMA4ADpAPcADQERARgBIAEcARYBGwE5ATgBEgESAQwBEAE7ARkBMAEpAfcAcAA1ABUAAAAAAAAAAwAEAAQABAAGADoAVwBbAGAAaQBvAHAAdAB1AHUAdwB5AHgAfAB9AH0AfAB8AHkAeAB7AIAAgACCAIsAkADBAMgArwC/AO8A2QDDAMoA1wDeAOoA7QD0APoA/AALARIBMQEoASABIwENARABPAEbATEBKAHFADcAGAAIAAAAAAAAAAIABAAEADEAWABnAGcAaABpAGsAbgBvAHIAcwB0AHQAdgB3AHwAewB1AHMAbwBqAGwAcwB4AHsAegB+AI0AlgChAJwAnACkAKYAvADEAM4AzADWAOIA6wDvAPIACgEUAR8BHwEfASYBDAEHASQBKgEiAfsAagATAAYAAAAAAAAAAAABAAMADgBMAF8AXABfAF8AXgBfAGIAaABvAHEAcwB2AH4AhgCfAJwAhgB6AG0AYwBgAGEAagBtAG4AZgCFAI4AkwCUAJsAtACoAJsAsQDPAMoAyQDHANQA5QD4APoA+gAWARgBAwEWAQgBCAEiASABCAHFAEsAAAAAAAAAAAAAAAAAAAABAAIAAwACAAEAAAAAAAAAAAAAAAwAOQBdAHIAfQCSAKEArwCwAJIAfABkAF0AXQBfAGEAYgBgAFoAdwCXAIsAhwCSAKwA3wD4AAEB/ADdANAA0QDcAAEB/gDtAO8ABwENAfsAGQEIAQIBFQESAQABtQA4AAAAAAAAAAAAAAA=","spacing":0.5},"visible":true,"children":["building_47yrxyutirp7w94z"],"parentId":null},"slab_0f5hfo7nzb74sy01":{"id":"slab_0f5hfo7nzb74sy01","name":"Slab 15","type":"slab","holes":[],"slots":{"surface":"library:wood-squareparquet23"},"object":"node","polygon":[[-8.491483799151588,-3.486013613686246],[-8.555273056030273,6.905969619750977],[-2.1,6.8500000000000005],[-2.0500000000000003,4.6000000000000005],[-2.153425931930542,-3.5733888149261475]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.82,"thickness":0.08,"holeMetadata":[],"autoFromWalls":false},"slab_4eik3g2c3wzu2n1x":{"id":"slab_4eik3g2c3wzu2n1x","name":"Slab 4","type":"slab","holes":[],"object":"node","polygon":[[5.057193279266357,-7.6],[5.15,-3.4000000000000004],[-1.5852010250091553,-3.327772617340088],[-1.5521034002304077,-7.6]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.2,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_4tyn48br19e3m2lo":{"id":"slab_4tyn48br19e3m2lo","name":"Room 2 Slab","type":"slab","holes":[],"object":"node","polygon":[[13.65,-9.9],[9.450000000000001,-9.850000000000001],[9.5,-13.4],[13.699331547990232,-13.155882167355275]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.76,"thickness":0.05,"holeMetadata":[],"autoFromWalls":true},"slab_771ag7ek013tiee3":{"id":"slab_771ag7ek013tiee3","name":"Slab 23","type":"slab","holes":[],"slots":{"surface":"library:flooring-ground13"},"object":"node","polygon":[[-2.95,-7.65],[-5.050000000000001,-7.65],[-5,-5.050000000000001],[-9,-5],[-9,6.9],[-5.050000000000001,7],[-5,11.950000000000001],[-2.9000000000000004,11.950000000000003],[-2.900000000000001,5.550000000000001],[-6.9,5.550000000000001],[-6.8500000000000005,-3.4000000000000004],[-2.9000000000000004,-3.4000000000000004]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.15,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_9y9pkx8vq9o2b03o":{"id":"slab_9y9pkx8vq9o2b03o","name":"Slab 7","type":"slab","holes":[],"slots":{"surface":"library:flooring-ground13"},"object":"node","polygon":[[-1.55,-7.6000000000000005],[-2.9000000000000004,-7.65],[-2.85,-3.4000000000000004],[-1.6,-3.4000000000000004]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.1,"thickness":0.08,"holeMetadata":[],"autoFromWalls":false},"slab_am3bz3vinj3t9vm8":{"id":"slab_am3bz3vinj3t9vm8","name":"Slab 10","type":"slab","holes":[[[-3.4527216982841487,-7.59],[-3.4527216982841487,-8.73],[2.532828301715851,-8.73],[2.6728283017158514,-8.73],[5.288649301715852,-8.73],[5.288649301715852,-7.59],[2.6728283017158514,-7.59],[2.532828301715851,-7.59]],[[-0.65,6.912654999999999],[-0.65,6.819999999999999],[-0.6499999999999999,5.4799999999999995],[-0.6499999999999999,5.387345],[3.588758,5.387345],[3.9287579999999998,5.387345],[3.9287579999999998,5.4799999999999995],[5.175093,5.4799999999999995],[5.175093,6.82],[3.9287579999999998,6.819999999999999],[3.9287579999999998,6.912655],[3.588758,6.912655]]],"slots":{"surface":"library:concrete-polished"},"object":"node","polygon":[[4.879626274108887,-7.630306720733643],[4.95,12.3],[-2.0500000000000003,12.350000000000001],[-2.150686025619507,-7.572563648223877]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.82,"thickness":0.10000000000000009,"holeMetadata":[{"source":"stair","stairId":"stair_geaij9m0pt5dxycv"},{"source":"stair","stairId":"stair_uqnjve0miurt8gsv"}],"autoFromWalls":false,"fillToTerrain":true},"slab_f3sskulpfwzd1obx":{"id":"slab_f3sskulpfwzd1obx","name":"Slab 14","type":"slab","holes":[],"slots":{"surface":"library:flooring-tiles4"},"object":"node","polygon":[[9.491926193237305,-3.491515636444092],[6.639129638671875,-3.479066848754883],[6.500010973959478,-7.500373154234771],[9.487615585327148,-7.50291633605957]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.79,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_fnb1n0kpjlw6b951":{"id":"slab_fnb1n0kpjlw6b951","name":"Room 1 Slab","type":"slab","holes":[],"object":"node","polygon":[[8.5,11.900000000000002],[-1.5,11.950000000000003],[-1.5,5.5],[-0.95,5.5],[-0.9,-3.4000000000000004],[-1.5,-3.4000000000000004],[-1.5,-7.6],[5.15,-7.6],[5.2,-6.3999999999999995],[6.75,-6.3999999999999995],[6.75,-5.75],[8.5,-5.75]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.05,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false,"fillToTerrain":true},"slab_fqfoj4m09yf41qoc":{"id":"slab_fqfoj4m09yf41qoc","name":"Slab 8","type":"slab","holes":[],"slots":{"surface":"library:flooring-ground13"},"object":"node","polygon":[[-1.55,6.75],[-2.9000000000000004,6.75],[-2.9000000000000004,11.950000000000003],[-1.55,11.950000000000003]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.2,"thickness":0.08,"holeMetadata":[],"autoFromWalls":false},"slab_fssn9crda7317xci":{"id":"slab_fssn9crda7317xci","name":"Slab 17","type":"slab","holes":[],"slots":{"surface":"library:wood-squareparquet23"},"object":"node","polygon":[[-3.9000000000000004,4.6000000000000005],[-2.15,4.6000000000000005],[-2.00045450789191,12.250004131889927],[-3.958498001098633,12.219377517700195]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.95,"thickness":0.19999999999999996,"holeMetadata":[],"autoFromWalls":false},"slab_hzztobsuegq3bzxj":{"id":"slab_hzztobsuegq3bzxj","name":"Slab 3","type":"slab","holes":[],"object":"node","polygon":[[-2.85,-3.4000000000000004],[-6.8500000000000005,-3.4000000000000004],[-6.85,5.6],[-2.8499999999999996,5.6]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.1,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_i018ub2h6brulvmq":{"id":"slab_i018ub2h6brulvmq","name":"Room 1 Slab","type":"slab","holes":[],"slots":{"surface":"library:wood-squareparquet23"},"object":"node","polygon":[[6.6188178062438965,3.9406776428222656],[9.550079037251013,3.9757663862745343],[9.566926002502441,12.309372901916504],[6.725612640380859,12.305633544921875]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.79,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_insih5v5fkmprxkm":{"id":"slab_insih5v5fkmprxkm","name":"Slab 23","type":"slab","holes":[],"slots":{"surface":"library:wood-squareparquet23"},"object":"node","polygon":[[-0.45,4.6000000000000005],[-2.15,4.6000000000000005],[-2.1,-3.5],[-0.5,-3.5]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.97,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_lfdaagebci5bddqn":{"id":"slab_lfdaagebci5bddqn","name":"Slab 12","type":"slab","holes":[[[-3.4527216982841487,-7.59],[-3.4527216982841487,-8.73],[2.532828301715851,-8.73],[2.6728283017158514,-8.73],[5.288649301715852,-8.73],[5.288649301715852,-7.59],[2.6728283017158514,-7.59],[2.532828301715851,-7.59]],[[-0.65,6.912654999999999],[-0.65,6.819999999999999],[-0.6499999999999999,5.4799999999999995],[-0.6499999999999999,5.387345],[3.588758,5.387345],[3.9287579999999998,5.387345],[3.9287579999999998,5.4799999999999995],[5.175093,5.4799999999999995],[5.175093,6.82],[3.9287579999999998,6.819999999999999],[3.9287579999999998,6.912655],[3.588758,6.912655]]],"slots":{"surface":"library:flooring-tiles4"},"object":"node","polygon":[[4.9654059410095215,12.306550979614258],[6.7161946296691895,12.310070037841797],[6.550000000000001,-8.75],[4.825202465057373,-8.701677322387695]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.79,"thickness":0.08,"holeMetadata":[{"source":"stair","stairId":"stair_geaij9m0pt5dxycv"},{"source":"stair","stairId":"stair_uqnjve0miurt8gsv"}],"autoFromWalls":false},"slab_lt5v8ufyejl12dft":{"id":"slab_lt5v8ufyejl12dft","name":"Slab 9","type":"slab","holes":[],"object":"node","polygon":[[-1.55,5.45],[-1.5,6.75],[-2.9000000000000004,6.75],[-2.9000000000000004,5.550000000000001]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.2,"thickness":0.08,"holeMetadata":[],"autoFromWalls":false},"slab_nxjmelpqhjomln9k":{"id":"slab_nxjmelpqhjomln9k","name":"Slab 5","type":"slab","holes":[],"slots":{"surface":"library:flooring-ceramic53"},"object":"node","polygon":[[5.150029091073293,6.749999999692257],[-1.5,6.75],[-1.5,11.950000000000003],[5.150083747906303,11.916749581260468]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.2,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_pb577t0qw81qvg48":{"id":"slab_pb577t0qw81qvg48","name":"Slab 6","type":"slab","holes":[],"object":"node","polygon":[[-0.9500000000000001,-3.35],[-2.85,-3.4000000000000004],[-2.9000000000000004,5.550000000000001],[-0.95,5.5]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.1,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_r3rcoqhv8z0em8vi":{"id":"slab_r3rcoqhv8z0em8vi","name":"Slab 20","type":"slab","holes":[],"slots":{"surface":"library:concrete-polished"},"object":"node","polygon":[[6.8,12.2],[5.235159397125244,12.188426971435547],[5.181943893432617,-7.4813666343688965],[6.7,-7.500000000000001]],"visible":true,"parentId":"level_9aer4vw8rexz9qbk","recessed":false,"elevation":1.99,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_sz4w3xcwfyiy7f7h":{"id":"slab_sz4w3xcwfyiy7f7h","name":"Slab 18","type":"slab","holes":[],"slots":{"surface":"library:flooring-ground13"},"object":"node","polygon":[[6.500010973959478,-7.500373154234771],[6.5,-13.5],[9.5,-13.5],[9.487615585327148,-7.50291633605957]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.71,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_t4xu5fmj2cwh69ws":{"id":"slab_t4xu5fmj2cwh69ws","name":"Slab 13","type":"slab","holes":[],"slots":{"surface":"library:wood-squareparquet23"},"object":"node","polygon":[[9.55,3.95],[6.602827548980713,3.959419012069702],[6.6000835864500464,-3.533519422598677],[9.500030180688327,-3.5482274170597363]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.79,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_w4gdmlukxsamq8fw":{"id":"slab_w4gdmlukxsamq8fw","name":"Slab 16","type":"slab","holes":[],"slots":{"surface":"library:wood-squareparquet23"},"object":"node","polygon":[[-2.10064663474742,-7.450008182957414],[-3.5,-7.45],[-3.4314663410186768,-3.548307418823242],[-2.15,-3.5500000000000003]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.92,"thickness":0.19999999999999996,"holeMetadata":[],"autoFromWalls":false},"slab_xp9ne45jh7stdfka":{"id":"slab_xp9ne45jh7stdfka","name":"Slab 3","type":"slab","holes":[],"object":"node","polygon":[[-0.9101530611515045,-3.3843870162963867],[5.08963471761332,-3.399844478817506],[5.089634717613321,6.654051251669115],[-0.9103254587868443,6.654051251669114]],"visible":true,"parentId":"level_i80amuksqi4z98rs","recessed":false,"elevation":0.21,"thickness":0.15000000000000002,"holeMetadata":[],"autoFromWalls":false},"slab_ylc7otse3rrb0u51":{"id":"slab_ylc7otse3rrb0u51","name":"Slab 18","type":"slab","holes":[],"slots":{"surface":"library:flooring-ground13"},"object":"node","polygon":[[4.75,-8.75],[4.75,-23],[6.5,-23],[6.5,-8.75]],"visible":true,"parentId":"level_sf01i06lzxjhci90","recessed":false,"elevation":1.72,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"wall_0i3y578th94b8b9p":{"id":"wall_0i3y578th94b8b9p","end":[2.376955032348633,-5.412365436553955],"name":"Wall 94","type":"wall","slots":{"exterior":"library:flooring-tile20","interior":"library:preset-white"},"start":[2.3260741666869236,-7.532099816785014],"height":2.6484156406125328,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_0jm76jl97l1pn11g":{"id":"wall_0jm76jl97l1pn11g","end":[7.95,-26.950000000000003],"name":"Wall 111","type":"wall","slots":{"exterior":"library:concrete-raw"},"start":[7.75,-13.700000000000001],"height":3.5,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_0xwe9uz5bb5l4ent":{"id":"wall_0xwe9uz5bb5l4ent","end":[6.720719039117027,8.999813341989936],"name":"Wall 85","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-charcoal"},"start":[9.55,9],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_14qqztrgq7llrayz":{"id":"wall_14qqztrgq7llrayz","end":[-3.909393787384033,6.815302848815918],"name":"Wall 91","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-8.487570762634277,6.840870380401611],"height":0.6,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"flat"},"frontSide":"exterior","supportOffset":-0.050000000000000044},"wall_1cic0845kn6dzgsm":{"id":"wall_1cic0845kn6dzgsm","end":[8.5,-5.75],"name":"Wall 13","type":"wall","start":[7.050000000000001,-5.75],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior","supportOffset":-0.05},"wall_1cs12gkft1qbcunm":{"id":"wall_1cs12gkft1qbcunm","end":[4.8500000000000005,-7.550000000000001],"name":"Wall 77","type":"wall","start":[4.850649241146712,-7.500008431703204],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_1n2g40icx5o2ioln":{"id":"wall_1n2g40icx5o2ioln","end":[13.65,-9.9],"name":"Wall 110","type":"wall","slots":{"interior":"library:concrete-plate"},"start":[13.699331547990232,-13.155882167355275],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_1oakh6vclfu5qmwg":{"id":"wall_1oakh6vclfu5qmwg","end":[-6.800000000000001,5.550000000000001],"name":"Wall 49","type":"wall","crown":{"proud":0.055,"sides":"both","height":0.12,"enabled":true,"profile":"crown-cove"},"slots":{"exterior":"library:concrete-stucco","interior":"library:mtl_c9E79yBZj9rk5VSh","chairRailInterior":"library:flooring-tile79"},"start":[-6.8500000000000005,-3.4000000000000004],"height":2.6,"object":"node","visible":true,"backSide":"interior","children":["door_nxqmcxygwbc0g6ho","window_aj7nfncuii6d9ks1","window_g43e8hgcxfa6yd42"],"parentId":"level_i80amuksqi4z98rs","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"base-colonial"},"chairRail":{"proud":0.026,"sides":"interior","height":0.055,"enabled":true,"offsetY":0.9,"profile":"rail-rounded"},"frontSide":"exterior","thickness":0.12,"supportOffset":0.04999999999999982},"wall_1pfid7ya3mjsry2a":{"id":"wall_1pfid7ya3mjsry2a","end":[13.699331547990234,-13.155882167355275],"name":"Wall 113","type":"wall","slots":{"exterior":"library:concrete-plate","interior":"library:concrete-plate"},"start":[9.5,-13.4],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_1sjfrmrptax3zp6y":{"id":"wall_1sjfrmrptax3zp6y","end":[-2.9000000000000004,11.950000000000003],"name":"Wall 51","type":"wall","crown":{"proud":0.055,"sides":"both","height":0.12,"enabled":true,"profile":"crown-cove"},"start":[-2.9000000000000004,5.550000000000001],"height":0.1,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"base-colonial"},"chairRail":{"proud":0.026,"sides":"interior","height":0.055,"enabled":true,"offsetY":0.9,"profile":"rail-rounded"},"frontSide":"unknown","thickness":0.12,"supportOffset":0.04999999999999982},"wall_20iapzti6a03nzp2":{"id":"wall_20iapzti6a03nzp2","end":[-8.487570762634277,6.840870380401611],"name":"Wall 90","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-8.470929145812988,-3.4470407962799072],"height":0.6,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"flat"},"frontSide":"exterior","supportOffset":-0.050000000000000044},"wall_280c755hxpla5e4e":{"id":"wall_280c755hxpla5e4e","end":[-2.15,-3.5500000000000003],"name":"Wall 76","type":"wall","start":[-2.2,-3.5500000000000003],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_2n03kd6eit1hzhax":{"id":"wall_2n03kd6eit1hzhax","end":[6.7,6.7],"name":"Wall 63","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:preset-softwhite"},"start":[6.720719039117027,8.999813341989936],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_36cs30s2gr1w93by":{"id":"wall_36cs30s2gr1w93by","end":[6.7,6.7],"name":"Wall 48","type":"wall","slots":{"interior":"library:concrete-raw"},"start":[6.7,9.35],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior","supportOffset":-0.05},"wall_3ipadomniw1kc6yt":{"id":"wall_3ipadomniw1kc6yt","end":[-16.344329681971345,-26.415208657329547],"name":"Wall 54","type":"wall","start":[-16.35,-26.35],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown"},"wall_460g00qka4zmmvwj":{"id":"wall_460g00qka4zmmvwj","end":[7.03167305594949,-6.0109342068883205],"name":"Wall 117","type":"wall","slots":{"exterior":"library:mtl_HA9sdp9vc98J5YXZ","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[9.492257034907817,-5.998056247973452],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["door_154dl0z66h9ossr5"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_46uufq7tbo6xq7gq":{"id":"wall_46uufq7tbo6xq7gq","end":[-1.5,5.5],"name":"Wall 62","type":"wall","slots":{"exterior":"library:mtl_c9E79yBZj9rk5VSh","interior":"library:flooring-tile79"},"start":[-2.9000000000000004,5.5],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":["door_xxw5lk6em2uk02nh"],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown"},"wall_4g7w137s2sqjatn4":{"id":"wall_4g7w137s2sqjatn4","end":[-1.3,5.45],"name":"Wall 5","type":"wall","slots":{"exterior":"library:mtl_c9E79yBZj9rk5VSh","interior":"library:flooring-tile79"},"start":[-1.5,5.5],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_4steouo1i8n1euof":{"id":"wall_4steouo1i8n1euof","end":[6.500010973959478,-7.500373154234771],"name":"Wall 74","type":"wall","slots":{"exterior":"library:flooring-tile85a","interior":"library:preset-softwhite"},"start":[7.0394160210416725,-7.490377958914869],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_5ivktfnj4q69zui4":{"id":"wall_5ivktfnj4q69zui4","end":[9.531521062100898,-5.997850751825647],"name":"Wall 103","type":"wall","slots":{"exterior":"library:flooring-tile85a","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[9.53926402719308,-7.477294503852195],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_5l49mu2vaob1i1bl":{"id":"wall_5l49mu2vaob1i1bl","end":[8.5,6.75],"name":"Wall 51","type":"wall","start":[6.7,6.7],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05},"wall_6giiuyemu1cymxqn":{"id":"wall_6giiuyemu1cymxqn","end":[-3.425480365753174,-3.473207712173462],"name":"Wall 88","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-3.4359443187713623,-7.398186206817627],"height":0.6,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_6xute67lysx53msd":{"id":"wall_6xute67lysx53msd","end":[6.7,-3.4000000000000004],"name":"Wall 19","type":"wall","start":[6.7,-4.699999999999999],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05},"wall_75nrmwd89i1mlmov":{"id":"wall_75nrmwd89i1mlmov","end":[-1.6,11.950000000000003],"name":"Wall 52","type":"wall","crown":{"proud":0.055,"sides":"both","height":0.12,"enabled":true,"profile":"crown-cove"},"start":[-2.9000000000000004,11.950000000000003],"height":0.1,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"base-colonial"},"chairRail":{"proud":0.026,"sides":"interior","height":0.055,"enabled":true,"offsetY":0.9,"profile":"rail-rounded"},"frontSide":"unknown","thickness":0.12,"supportOffset":0.04999999999999982},"wall_7dc75bkj2yzdqrg3":{"id":"wall_7dc75bkj2yzdqrg3","end":[-2.15,4.6000000000000005],"name":"Wall 80","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[-2.1,6.8500000000000005],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":["window_kg2jwctr4p4rgs8i"],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_7g6gnjs7fq6712dj":{"id":"wall_7g6gnjs7fq6712dj","end":[-2.15,-3.5500000000000003],"name":"Wall 83","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[-2.101378062530358,-7.392209199562817],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_854iqmwfjire1l1v"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_7i5uapt27c87bydk":{"id":"wall_7i5uapt27c87bydk","end":[5.1000000000000005,-3.35],"name":"Wall 52","type":"wall","slots":{"interior":"library:concrete-raw"},"start":[5.1000000000000005,6.75],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_947lyb0g73iwo863":{"id":"wall_947lyb0g73iwo863","end":[6.75,12.25],"name":"Wall 62","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[4.9,12.25],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_97726n6gfe32f7fn":{"id":"wall_97726n6gfe32f7fn","end":[5.15,-7.65],"name":"Wall 57","type":"wall","slots":{"exterior":"library:flooring-tile79","interior":"library:preset-softwhite"},"start":[5.1411813528842165,-5.150207497579196],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_99y0voobavl5o0fr":{"id":"wall_99y0voobavl5o0fr","end":[5.1000000000000005,-3.35],"name":"Wall 53","type":"wall","slots":{"exterior":"library:mtl_c9E79yBZj9rk5VSh"},"start":[5.050000000000001,6.75],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_9eruv8k4qxk7495v":{"id":"wall_9eruv8k4qxk7495v","end":[1.7000000000000006,6.75],"name":"Wall 51","type":"wall","slots":{"exterior":"library:mtl_c9E79yBZj9rk5VSh","interior":"library:preset-olive"},"start":[5.050000000000001,6.75],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_a3wsy66uqumu4d10":{"id":"wall_a3wsy66uqumu4d10","end":[-2.0004630605796776,12.249063336235483],"name":"Wall 59","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[-2.04823720688643,6.993907242492746],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_z7gnoxfn6pxyn7us"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_a6pvfi43xqjdolt1":{"id":"wall_a6pvfi43xqjdolt1","end":[-2.04823720688643,6.993907242492746],"name":"Wall 107","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:preset-white"},"start":[4.9,6.95215368270874],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior","supportOffset":-0.030000000000000915},"wall_ar0bsb3uvcx2pja0":{"id":"wall_ar0bsb3uvcx2pja0","end":[6.700044998875029,11.908999775005626],"name":"Wall 2","type":"wall","start":[8.5,11.900000000000002],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_bdkcmjsihkf59wab":{"id":"wall_bdkcmjsihkf59wab","end":[4.9,12.25],"name":"Wall 60","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[2.0337095305887747,12.270770220792835],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_x5cq6wus7bx6nzsv"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_bnywyxujlwp4ubjm":{"id":"wall_bnywyxujlwp4ubjm","end":[9.499946594238281,-3.5422079944610596],"name":"Wall 76","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[9.492257034907817,-5.998056247973452],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["window_hjn05f384cikt568","window_iyxrjoln2pcq2l2k"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_bxb7mnl6bzokxuro":{"id":"wall_bxb7mnl6bzokxuro","end":[7.75,-13.700000000000001],"name":"Wall 110","type":"wall","start":[13.8,-13.450000000000001],"height":4,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_dbggg38wix3g1op5":{"id":"wall_dbggg38wix3g1op5","end":[-2.0004630605796776,12.249063336235483],"name":"Wall 107","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-3.8990378379821777,12.202646255493164],"height":0.6,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"flat"},"frontSide":"unknown","supportOffset":-0.030000000000000027,"supportSlabId":"slab_fssn9crda7317xci"},"wall_de6kehxv7lc4pex9":{"id":"wall_de6kehxv7lc4pex9","end":[4.9,9.436186790466309],"name":"Wall 100","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:flooring-lightceramic24"},"start":[2.0334784984588623,9.436081886291504],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["door_hckoo7yqxicb2d1d"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_dfbucsrupel9xcyu":{"id":"wall_dfbucsrupel9xcyu","end":[-2.900000000000001,5.550000000000001],"name":"Wall 50","type":"wall","crown":{"proud":0.055,"sides":"both","height":0.12,"enabled":true,"profile":"crown-cove"},"slots":{"exterior":"library:flooring-tile79","interior":"library:mtl_c9E79yBZj9rk5VSh","skirtingInterior":"library:concrete-stucco"},"start":[-6.800000000000001,5.550000000000001],"height":2.6,"object":"node","visible":true,"backSide":"interior","children":["window_xi4od9yzt5sv0rdp","window_zrx7tun46ubh2ij8"],"parentId":"level_i80amuksqi4z98rs","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"base-colonial"},"chairRail":{"proud":0.026,"sides":"interior","height":0.055,"enabled":true,"offsetY":0.9,"profile":"rail-rounded"},"frontSide":"exterior","thickness":0.12,"supportOffset":0.04999999999999982},"wall_dnjctsqpzz9g8bae":{"id":"wall_dnjctsqpzz9g8bae","end":[13.699331547990232,-13.155882167355275],"name":"Wall 110","type":"wall","start":[13.700000000000001,-13.200000000000001],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_e50yfnnocfwnk5hi":{"id":"wall_e50yfnnocfwnk5hi","end":[13.8,-13.450000000000001],"name":"Wall 109","type":"wall","slots":{"exterior":"library:concrete-raw"},"start":[13.800502511152887,-13.15000084172723],"height":4,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_e5hudabid17j7m0c":{"id":"wall_e5hudabid17j7m0c","end":[-1.6,11.950000000000003],"name":"Wall 47","type":"wall","slots":{"exterior":"library:concrete-stucco","interior":"library:preset-sky"},"start":[-1.55,6.75],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_eojbhto8qaqdk6ql"],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05},"wall_ej413c830bju48p3":{"id":"wall_ej413c830bju48p3","end":[7.0394160210416725,-7.490377958914869],"name":"Wall 81","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[4.850649241146712,-7.500008431703204],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["window_e57d0rkbijnk41fx"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_eyok8hofk34fyuqo":{"id":"wall_eyok8hofk34fyuqo","end":[8.5,-3.4000000000000004],"name":"Wall 1","type":"wall","start":[8.5,-5.75],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_fbrvqkv587g1zeuf":{"id":"wall_fbrvqkv587g1zeuf","end":[8.5,-3.4000000000000004],"name":"Wall 20","type":"wall","start":[6.7,-3.4000000000000004],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05},"wall_fdjd3bxef0pvivrx":{"id":"wall_fdjd3bxef0pvivrx","end":[5.1000000000000005,-3.4000000000000004],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:mtl_c9E79yBZj9rk5VSh"},"start":[-1.6,-3.4000000000000004],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":["window_5jtz0q5oxxifnqoj","door_sksbyv6qm5dda79m"],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_fitty57cmrsit6pf":{"id":"wall_fitty57cmrsit6pf","end":[-0.44999999999999996,-3.5],"name":"Wall 119","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[-0.45,4.6000000000000005],"height":2.6895943809134675,"object":"node","visible":true,"backSide":"unknown","children":["window_wrr3e03nuzgvq6m0","door_i3q2889ydv9p5si6","window_8qce71iwvjrnwxy0"],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_fkya3c070ahmoj93":{"id":"wall_fkya3c070ahmoj93","end":[4.9,6.8500000000000005],"name":"Wall 57","type":"wall","slots":{"exterior":"library:preset-charcoal","interior":"library:preset-beige"},"start":[4.9,6.95215368270874],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_fsmfn5hofa8pe81e":{"id":"wall_fsmfn5hofa8pe81e","end":[2.6500000000000004,-7.65],"name":"Wall 58","type":"wall","slots":{"interior":"library:preset-softwhite"},"start":[5.15,-7.65],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_g26j3dtf36bu6plp":{"id":"wall_g26j3dtf36bu6plp","end":[-0.45,4.6000000000000005],"name":"Wall 119","type":"wall","start":[-0.45,4.65],"height":2.6895943809134675,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_h4j4jhid4d99epc4":{"id":"wall_h4j4jhid4d99epc4","end":[-2.100005029675083,-7.500709184186702],"name":"Wall 78","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[2.3260741666869236,-7.532099816785014],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_yaadtc8npk9apbmj","window_cth3u7m0zqnkflud"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_hhxdh43u2kwu82n6":{"id":"wall_hhxdh43u2kwu82n6","end":[4.87635894673726,-5.4682652344440665],"name":"Wall 96","type":"wall","slots":{"exterior":"library:flooring-tile20","interior":"library:preset-white"},"start":[2.376955032348633,-5.412365436553955],"height":2.632485976438831,"object":"node","visible":true,"backSide":"unknown","children":["door_4496t5gswn6s80fh"],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_hrzdo3w2sq9pjgoe":{"id":"wall_hrzdo3w2sq9pjgoe","end":[13.800502511152887,-13.15000084172723],"name":"Wall 109","type":"wall","slots":{"exterior":"library:concrete-raw"},"start":[13.850000000000001,16.400000000000002],"height":4,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_i2q5s3aknj3kasko":{"id":"wall_i2q5s3aknj3kasko","end":[4.9,6.95215368270874],"name":"Wall 57","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:preset-white"},"start":[4.9,9.436186790466309],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["door_wvwuv8c0lbn5vm3j"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_iazgnn6b298jt5h4":{"id":"wall_iazgnn6b298jt5h4","end":[-2.101378062530358,-7.392209199562817],"name":"Wall 83","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:preset-beige"},"start":[-2.100005029675083,-7.500709184186702],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_ibb5fyo78jx5a42w":{"id":"wall_ibb5fyo78jx5a42w","end":[8.5,9.325000000000001],"name":"Wall 1","type":"wall","slots":{"exterior":"library:concrete-raw"},"start":[8.5,6.75],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_icw2ueso5jbd0kot":{"id":"wall_icw2ueso5jbd0kot","end":[-2.04823720688643,6.993907242492746],"name":"Wall 59","type":"wall","slots":{"exterior":"library:mtl_HA9sdp9vc98J5YXZ","interior":"library:preset-lightgrey"},"start":[-2.0500000000000003,6.800000000000001],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_if4f2apfhbqzk8ej":{"id":"wall_if4f2apfhbqzk8ej","end":[4.87635894673726,-5.4682652344440665],"name":"Wall 77","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:preset-white"},"start":[4.9,-3.6],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["door_o1q52jyppkq43ocd"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_ig6m35gemx8dd0lj":{"id":"wall_ig6m35gemx8dd0lj","end":[-1,5.4],"name":"Wall 119","type":"wall","slots":{"interior":"library:preset-glass"},"start":[-1.0000744628353848,6.9876085908356425],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_j9mie1ep1ke34ml8":{"id":"wall_j9mie1ep1ke34ml8","end":[-2.15,4.6000000000000005],"name":"Wall 120","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[-0.45,4.6000000000000005],"height":2.684654309361483,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_jkmjjnf0i695rhb3":{"id":"wall_jkmjjnf0i695rhb3","end":[9.5,-13.4],"name":"Wall 112","type":"wall","slots":{"exterior":"library:concrete-stucco","interior":"library:concrete-plate"},"start":[9.450000000000001,-9.850000000000001],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["door_gpr13l6diwd6p7vi"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_jxfq48humseebjj2":{"id":"wall_jxfq48humseebjj2","end":[6.7,9.35],"name":"Wall 48","type":"wall","slots":{"interior":"library:concrete-raw"},"start":[6.7,11.850000000000001],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportOffset":-0.05},"wall_k489wtujdy8i27ou":{"id":"wall_k489wtujdy8i27ou","end":[3.7,5.5],"name":"Wall 64","type":"wall","slots":{"exterior":"library:mtl_c9E79yBZj9rk5VSh","interior":"library:flooring-tile79"},"start":[-1.3,5.45],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":["window_48sy95piuynvc8wc"],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_k62mbcudnoinr3op":{"id":"wall_k62mbcudnoinr3op","end":[8.5,11.900000000000002],"name":"Wall 1","type":"wall","slots":{"exterior":"library:concrete-raw"},"start":[8.5,9.325000000000001],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_k7v39bcwpjcvl42v":{"id":"wall_k7v39bcwpjcvl42v","end":[-1.6,-7.65],"name":"Wall 58","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:concrete-stucco"},"start":[2.6500000000000004,-7.65],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":["window_41mgpg15hg5q1jw4"],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_ko0t4czoisekpi2t":{"id":"wall_ko0t4czoisekpi2t","end":[8.5,6.75],"name":"Wall 1","type":"wall","slots":{"exterior":"library:concrete-raw"},"start":[8.5,4.05],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_ktwhhlu2qppo36ru":{"id":"wall_ktwhhlu2qppo36ru","end":[6.75,-6.3999999999999995],"name":"Wall 11","type":"wall","start":[5.15,-6.3999999999999995],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_ku9utuvxec6qn09x":{"id":"wall_ku9utuvxec6qn09x","end":[9.450000000000001,-9.850000000000001],"name":"Wall 111","type":"wall","slots":{"exterior":"library:concrete-stucco","interior":"library:concrete-plate"},"start":[13.65,-9.9],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["window_wta4nf8sd5lla5fx"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_kvdgivq7usboz8fx":{"id":"wall_kvdgivq7usboz8fx","end":[1.6998162276549538,11.92537450576377],"name":"Wall 49","type":"wall","slots":{"exterior":"library:concrete-stucco","interior":"library:preset-olive"},"start":[-1.6,11.950000000000003],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_lel0871av5r6hnlx":{"id":"wall_lel0871av5r6hnlx","end":[-8.470929145812988,-3.4470407962799072],"name":"Wall 90","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-8.303927421569824,-3.4677581787109375],"height":0.6,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior","supportOffset":-0.050000000000000044},"wall_ll3zth5e97kl9rp9":{"id":"wall_ll3zth5e97kl9rp9","end":[13.55,-13.45],"name":"Wall 58","type":"wall","slots":{"interior":"library:concrete-raw"},"start":[7.800000000000001,-13.65],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown"},"wall_mcp9ybwfe99437ea":{"id":"wall_mcp9ybwfe99437ea","end":[-6.8500000000000005,-3.4000000000000004],"name":"Wall 48","type":"wall","crown":{"proud":0.055,"sides":"both","height":0.12,"enabled":true,"profile":"crown-cove"},"slots":{"exterior":"library:concrete-stucco","interior":"library:mtl_c9E79yBZj9rk5VSh","chairRailInterior":"library:preset-softwhite"},"start":[-1.6500000000000001,-3.4000000000000004],"height":2.6,"object":"node","visible":true,"backSide":"interior","children":["window_8kxospvky3rl8bd9","door_6847ujfykl4mxxpg","window_yau4scug58im677t"],"parentId":"level_i80amuksqi4z98rs","skirting":{"proud":0.02,"sides":"exterior","height":0.12,"enabled":true,"profile":"base-colonial"},"chairRail":{"proud":0.026,"sides":"interior","height":0.055,"enabled":true,"offsetY":0.9,"profile":"rail-rounded"},"frontSide":"exterior","thickness":0.12,"supportOffset":0.04999999999999982},"wall_mdt4o2r6xroifegy":{"id":"wall_mdt4o2r6xroifegy","end":[-1.55,6.75],"name":"Wall 51","type":"wall","slots":{"exterior":"library:flooring-tile79","interior":"library:preset-sky"},"start":[1.7000000000000006,6.75],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["door_nlq766qzo5urb582"],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_n7bfomyfezi75jfr":{"id":"wall_n7bfomyfezi75jfr","end":[3.5,5.4],"name":"Wall 120","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-1,5.4],"height":0.6799999999999999,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_nb5b3f2ov983pwkk":{"id":"wall_nb5b3f2ov983pwkk","end":[8.5,4.05],"name":"Wall 49","type":"wall","start":[6.7,4.05],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior","supportOffset":-0.05},"wall_noiqi8om9eykyi63":{"id":"wall_noiqi8om9eykyi63","end":[5.1000000000000005,11.9],"name":"Wall 49","type":"wall","slots":{"exterior":"library:concrete-stucco","interior":"library:preset-softwhite"},"start":[1.6998162276549538,11.92537450576377],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_zsm5b7quzm6z8gmm"],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_nqyiiqhgs8x5ciur":{"id":"wall_nqyiiqhgs8x5ciur","end":[9.500030180688327,-3.5257274170597364],"name":"Wall 111","type":"wall","slots":{"exterior":"library:mtl_c9E79yBZj9rk5VSh"},"start":[9.499946594238281,-3.5422079944610596],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_ntrpazsddg7c8r78":{"id":"wall_ntrpazsddg7c8r78","end":[-1.6,-3.4000000000000004],"name":"Wall 55","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:concrete-stucco"},"start":[-1.55,-7.6000000000000005],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":["window_3tkd78hy7fu3q9p0"],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_nzam1vodcoj7l0lt":{"id":"wall_nzam1vodcoj7l0lt","end":[5.1411813528842165,-5.150207497579196],"name":"Wall 61","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-softwhite"},"start":[2.6500000000000004,-5.15],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_nzheazst19yf53qj":{"id":"wall_nzheazst19yf53qj","end":[7.805670318028657,-24.315208657329546],"name":"Wall 56","type":"wall","slots":{"exterior":"library:concrete-raw","interior":"library:concrete-raw"},"start":[-16.344329681971345,-26.415208657329547],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown"},"wall_oefrz8dk57tz4qad":{"id":"wall_oefrz8dk57tz4qad","end":[9.55,9],"name":"Wall 66","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:preset-charcoal"},"start":[9.55,6.7],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["window_14rldlkz0ir5d351"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_ogpl3ug4icu7esk1":{"id":"wall_ogpl3ug4icu7esk1","end":[6.75,-5.75],"name":"Wall 12","type":"wall","start":[6.75,-6.3999999999999995],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_ogplbt7vkm3pilq3":{"id":"wall_ogplbt7vkm3pilq3","end":[4.9,-3.6],"name":"Wall 76","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:preset-white"},"start":[-2.15,-3.5500000000000003],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_ozfgdx9lsr62aqr6":{"id":"wall_ozfgdx9lsr62aqr6","end":[5.1411813528842165,-5.150207497579196],"name":"Wall 57","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:concrete-raw"},"start":[5.1000000000000005,-3.4000000000000004],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_p53qz474zxcj519k":{"id":"wall_p53qz474zxcj519k","end":[-16.4,15.850000000000001],"name":"Wall 54","type":"wall","slots":{"interior":"library:concrete-raw"},"start":[13.65,16.3],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown"},"wall_p5v5xjnaq0qu8kh8":{"id":"wall_p5v5xjnaq0qu8kh8","end":[6.700044998875029,11.908999775005626],"name":"Wall 58","type":"wall","slots":{"exterior":"library:concrete-stucco"},"start":[5.1000000000000005,11.9],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_pgki0wkxpf4c2n2t":{"id":"wall_pgki0wkxpf4c2n2t","end":[2.0334784984588623,9.436081886291504],"name":"Wall 98","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:flooring-lightceramic24"},"start":[2.0337095305887747,12.270770220792835],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_q0du3ew1peu88zhx":{"id":"wall_q0du3ew1peu88zhx","end":[-3.8990378379821777,12.202646255493164],"name":"Wall 106","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-3.909393787384033,6.815302848815918],"height":0.6,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"flat"},"frontSide":"unknown","supportOffset":-0.030000000000000027,"supportSlabId":"slab_fssn9crda7317xci"},"wall_qcuvw9y1znnwe39y":{"id":"wall_qcuvw9y1znnwe39y","end":[-16.35,-26.35],"name":"Wall 55","type":"wall","slots":{"exterior":"library:concrete-raw","interior":"library:concrete-raw"},"start":[-16.4,15.850000000000001],"height":1.4,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown"},"wall_qjiec7hzg9sovxt8":{"id":"wall_qjiec7hzg9sovxt8","end":[5.1000000000000005,6.75],"name":"Wall 50","type":"wall","slots":{"exterior":"library:concrete-raw","interior":"library:preset-softwhite"},"start":[5.1000000000000005,11.9],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_qmk1kov6chk1rhn1":{"id":"wall_qmk1kov6chk1rhn1","end":[13.800502511152887,-13.15000084172723],"name":"Wall 114","type":"wall","start":[13.699331547990234,-13.155882167355275],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_qrwi4aythp3sflps":{"id":"wall_qrwi4aythp3sflps","end":[7.050000000000001,-5.75],"name":"Wall 13","type":"wall","start":[6.75,-5.75],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior","supportOffset":-0.05},"wall_r8yap7dioibpczlk":{"id":"wall_r8yap7dioibpczlk","end":[7.03167305594949,-6.0109342068883205],"name":"Wall 103","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[7.0394160210416725,-7.490377958914869],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_rzn277yajhnxwzyj":{"id":"wall_rzn277yajhnxwzyj","end":[2.6500000000000004,-5.15],"name":"Wall 59","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-softwhite"},"start":[2.6500000000000004,-7.65],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_s8hr4n5hv7s2uwl9":{"id":"wall_s8hr4n5hv7s2uwl9","end":[6.7,4.05],"name":"Wall 48","type":"wall","slots":{"interior":"library:concrete-raw"},"start":[6.7,6.7],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior","supportOffset":-0.05},"wall_sh0tcrxesq8iwnju":{"id":"wall_sh0tcrxesq8iwnju","end":[6.700044998875029,11.908999775005626],"name":"Wall 57","type":"wall","slots":{"exterior":"library:flooring-tile79"},"start":[5.1000000000000005,11.9],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_sho6sk89n8n8piv3":{"id":"wall_sho6sk89n8n8piv3","end":[6.720719039117027,8.999813341989936],"name":"Wall 63","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:preset-softwhite"},"start":[6.75,12.25],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["door_dflxf3jet3iwyl0j"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_tb1zg8r42g4irnh8":{"id":"wall_tb1zg8r42g4irnh8","end":[1.6998162276549538,11.92537450576377],"name":"Wall 117","type":"wall","slots":{"exterior":"library:preset-olive","interior":"library:preset-sky"},"start":[1.7000000000000006,6.75],"height":2.7,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown","supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_tyaxy9vtt3gzu6w3":{"id":"wall_tyaxy9vtt3gzu6w3","end":[-1.55,11.950000000000003],"name":"Wall 52","type":"wall","crown":{"proud":0.055,"sides":"both","height":0.12,"enabled":true,"profile":"crown-cove"},"start":[-1.6,11.950000000000003],"height":0.5,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","skirting":{"proud":0.02,"sides":"both","height":0.12,"enabled":true,"profile":"base-colonial"},"chairRail":{"proud":0.026,"sides":"interior","height":0.055,"enabled":true,"offsetY":0.9,"profile":"rail-rounded"},"frontSide":"exterior","thickness":0.12,"supportOffset":0.04999999999999982},"wall_u975xadkr4o2dgj8":{"id":"wall_u975xadkr4o2dgj8","end":[6.6000835864500464,-3.511019422598677],"name":"Wall 72","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:preset-midgrey"},"start":[9.500030180688327,-3.5257274170597364],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior","curveOffset":0},"wall_uep7lw9jgtmag335":{"id":"wall_uep7lw9jgtmag335","end":[9.5,6.7],"name":"Wall 65","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:preset-softwhite"},"start":[6.7,6.7],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":["door_05xb8mny9hw5qqfz"],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_uq857q760o9ryf14":{"id":"wall_uq857q760o9ryf14","end":[9.55,6.7],"name":"Wall 65","type":"wall","start":[9.5,6.7],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_uv7zdjifiqk6vele":{"id":"wall_uv7zdjifiqk6vele","end":[8.5,9.325000000000001],"name":"Wall 54","type":"wall","start":[6.7,9.35],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05},"wall_uz1q3gxudcyrbczq":{"id":"wall_uz1q3gxudcyrbczq","end":[2.0337095305887747,12.270770220792835],"name":"Wall 60","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[-2.0004630605796776,12.249063336235483],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_x4save99gcz21374","window_2i8ogag7d5a9k3g1"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_w5f03lbhc6arjyk8":{"id":"wall_w5f03lbhc6arjyk8","end":[7.0394160210416725,-7.490377958914869],"name":"Wall 75","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:preset-softwhite"},"start":[6.500010973959478,-7.500373154234771],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_wtqn8jqsu6zx03cz":{"id":"wall_wtqn8jqsu6zx03cz","end":[7.050000000000001,-4.699999999999999],"name":"Wall 16","type":"wall","start":[7.050000000000001,-5.75],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05},"wall_wuyd7t6z9oobj6zf":{"id":"wall_wuyd7t6z9oobj6zf","end":[6.75,12.25],"name":"Wall 67","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[9.555974006652832,12.23916244506836],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_wwkhx6v38gogbvoe":{"id":"wall_wwkhx6v38gogbvoe","end":[-3.4359443187713623,-7.398186206817627],"name":"Wall 86","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-2.101378062530358,-7.392209199562817],"height":0.6,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_wxslhvmbee8jvmkc":{"id":"wall_wxslhvmbee8jvmkc","end":[-8.470929145812988,-3.4470407962799072],"name":"Wall 106","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[-3.425480365753174,-3.473207712173462],"height":0.6,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"unknown"},"wall_wybuip3yo34ukzl9":{"id":"wall_wybuip3yo34ukzl9","end":[5.050000000000001,6.75],"name":"Wall 51","type":"wall","start":[5.1000000000000005,6.75],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05,"supportSlabId":"slab_fnb1n0kpjlw6b951"},"wall_xeqtxw0qa9p2gzjz":{"id":"wall_xeqtxw0qa9p2gzjz","end":[2.3260741666869236,-7.532099816785014],"name":"Wall 78","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[4.8500000000000005,-7.550000000000001],"height":2.6862496104087326,"object":"node","visible":true,"backSide":"interior","children":["window_rnllzkswreigp6qf"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_xtp8kmtr8i9wetfb":{"id":"wall_xtp8kmtr8i9wetfb","end":[4.9,9.436186790466309],"name":"Wall 57","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:flooring-lightceramic24"},"start":[4.9,12.25],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_y7dl0xc08yd7v6o3":{"id":"wall_y7dl0xc08yd7v6o3","end":[9.497268676757812,-3.477088689804077],"name":"Wall 71","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[9.55,3.95],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["window_wmfuc35d5xgy3q7i"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_ya2r2ff8z81i45vz":{"id":"wall_ya2r2ff8z81i45vz","end":[9.555974006652832,12.23916244506836],"name":"Wall 66","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[9.55,9],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"interior"},"wall_yb442wmqslxz5iiy":{"id":"wall_yb442wmqslxz5iiy","end":[6.7,-4.699999999999999],"name":"Wall 18","type":"wall","start":[7.050000000000001,-4.699999999999999],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"exterior","supportOffset":-0.05},"wall_yv1j7ocfks3rp73f":{"id":"wall_yv1j7ocfks3rp73f","end":[4.850649241146712,-7.500008431703204],"name":"Wall 77","type":"wall","slots":{"exterior":"library:preset-midgrey","interior":"library:flooring-tile20"},"start":[4.87635894673726,-5.4682652344440665],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_z30f2sysbxfykbvf":{"id":"wall_z30f2sysbxfykbvf","end":[9.55,3.95],"name":"Wall 68","type":"wall","slots":{"exterior":"library:mtl_RjlZN6tUv6pDU1UA","interior":"library:mtl_RjlZN6tUv6pDU1UA"},"start":[9.5,6.7],"height":2.7,"object":"node","visible":true,"backSide":"interior","children":["door_cswt0xn9koyescm9"],"parentId":"level_sf01i06lzxjhci90","frontSide":"exterior"},"wall_zd9vbkl7vq4nznjp":{"id":"wall_zd9vbkl7vq4nznjp","end":[8.5,4.05],"name":"Wall 1","type":"wall","slots":{"exterior":"library:concrete-raw"},"start":[8.5,-3.4000000000000004],"height":2.7,"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"interior"},"wall_zh9f8ve3jyu8exn7":{"id":"wall_zh9f8ve3jyu8exn7","end":[7.805670318028657,-24.315208657329546],"name":"Wall 55","type":"wall","start":[7.800000000000001,-24.25],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_i80amuksqi4z98rs","frontSide":"unknown"},"level_9aer4vw8rexz9qbk":{"id":"level_9aer4vw8rexz9qbk","name":"Roof","type":"level","level":2,"height":2.5,"object":"node","visible":true,"children":["slab_r3rcoqhv8z0em8vi"],"parentId":"building_47yrxyutirp7w94z","baseElevation":0},"level_i80amuksqi4z98rs":{"id":"level_i80amuksqi4z98rs","type":"level","level":0,"height":1,"object":"node","visible":true,"children":["wall_4g7w137s2sqjatn4","wall_ktwhhlu2qppo36ru","wall_ogpl3ug4icu7esk1","slab_fnb1n0kpjlw6b951","wall_qrwi4aythp3sflps","wall_1cic0845kn6dzgsm","wall_wtqn8jqsu6zx03cz","wall_yb442wmqslxz5iiy","wall_6xute67lysx53msd","wall_eyok8hofk34fyuqo","wall_fbrvqkv587g1zeuf","wall_ar0bsb3uvcx2pja0","wall_mcp9ybwfe99437ea","wall_1oakh6vclfu5qmwg","wall_dfbucsrupel9xcyu","wall_1sjfrmrptax3zp6y","wall_p53qz474zxcj519k","wall_qcuvw9y1znnwe39y","wall_nzheazst19yf53qj","wall_ll3zth5e97kl9rp9","slab_hzztobsuegq3bzxj","slab_xp9ne45jh7stdfka","slab_4eik3g2c3wzu2n1x","slab_nxjmelpqhjomln9k","stair_geaij9m0pt5dxycv","wall_3ipadomniw1kc6yt","wall_zh9f8ve3jyu8exn7","wall_sh0tcrxesq8iwnju","wall_p5v5xjnaq0qu8kh8","wall_k489wtujdy8i27ou","wall_75nrmwd89i1mlmov","wall_tyaxy9vtt3gzu6w3","wall_e5hudabid17j7m0c","wall_qjiec7hzg9sovxt8","wall_7i5uapt27c87bydk","wall_wybuip3yo34ukzl9","wall_99y0voobavl5o0fr","wall_ntrpazsddg7c8r78","wall_fsmfn5hofa8pe81e","wall_k7v39bcwpjcvl42v","wall_rzn277yajhnxwzyj","wall_ozfgdx9lsr62aqr6","wall_97726n6gfe32f7fn","wall_nzam1vodcoj7l0lt","slab_pb577t0qw81qvg48","slab_9y9pkx8vq9o2b03o","wall_zd9vbkl7vq4nznjp","wall_nb5b3f2ov983pwkk","wall_ko0t4czoisekpi2t","wall_s8hr4n5hv7s2uwl9","wall_5l49mu2vaob1i1bl","wall_ibb5fyo78jx5a42w","wall_k62mbcudnoinr3op","wall_jxfq48humseebjj2","wall_36cs30s2gr1w93by","wall_uv7zdjifiqk6vele","stair_uqnjve0miurt8gsv","ceiling_86g4wbgw9h0tr99s","ceiling_3y7rj3jkhxdmhll9","ceiling_sm3737w8pq5amwb6","slab_fqfoj4m09yf41qoc","slab_lt5v8ufyejl12dft","wall_fdjd3bxef0pvivrx","wall_46uufq7tbo6xq7gq","wall_9eruv8k4qxk7495v","wall_mdt4o2r6xroifegy","wall_kvdgivq7usboz8fx","wall_noiqi8om9eykyi63","wall_tb1zg8r42g4irnh8","slab_771ag7ek013tiee3"],"parentId":"building_47yrxyutirp7w94z","baseElevation":0.5},"level_sf01i06lzxjhci90":{"id":"level_sf01i06lzxjhci90","type":"level","level":1,"height":2.5,"object":"node","visible":true,"children":["slab_am3bz3vinj3t9vm8","slab_i018ub2h6brulvmq","slab_lfdaagebci5bddqn","slab_t4xu5fmj2cwh69ws","slab_f3sskulpfwzd1obx","slab_0f5hfo7nzb74sy01","wall_947lyb0g73iwo863","wall_wuyd7t6z9oobj6zf","wall_uep7lw9jgtmag335","wall_uq857q760o9ryf14","wall_z30f2sysbxfykbvf","wall_y7dl0xc08yd7v6o3","wall_u975xadkr4o2dgj8","wall_7dc75bkj2yzdqrg3","wall_4steouo1i8n1euof","wall_1cs12gkft1qbcunm","wall_ej413c830bju48p3","wall_280c755hxpla5e4e","wall_ogplbt7vkm3pilq3","wall_sho6sk89n8n8piv3","wall_2n03kd6eit1hzhax","wall_oefrz8dk57tz4qad","wall_ya2r2ff8z81i45vz","wall_0xwe9uz5bb5l4ent","slab_w4gdmlukxsamq8fw","slab_fssn9crda7317xci","wall_iazgnn6b298jt5h4","wall_7g6gnjs7fq6712dj","wall_wwkhx6v38gogbvoe","wall_6giiuyemu1cymxqn","wall_14qqztrgq7llrayz","wall_xeqtxw0qa9p2gzjz","wall_h4j4jhid4d99epc4","wall_0i3y578th94b8b9p","wall_if4f2apfhbqzk8ej","wall_yv1j7ocfks3rp73f","wall_hhxdh43u2kwu82n6","wall_uz1q3gxudcyrbczq","wall_bdkcmjsihkf59wab","wall_pgki0wkxpf4c2n2t","wall_xtp8kmtr8i9wetfb","wall_de6kehxv7lc4pex9","wall_w5f03lbhc6arjyk8","wall_bnywyxujlwp4ubjm","wall_r8yap7dioibpczlk","wall_lel0871av5r6hnlx","wall_20iapzti6a03nzp2","wall_wxslhvmbee8jvmkc","wall_q0du3ew1peu88zhx","wall_dbggg38wix3g1op5","slab_ylc7otse3rrb0u51","wall_icw2ueso5jbd0kot","wall_a3wsy66uqumu4d10","wall_i2q5s3aknj3kasko","wall_fkya3c070ahmoj93","wall_a6pvfi43xqjdolt1","slab_sz4w3xcwfyiy7f7h","wall_nqyiiqhgs8x5ciur","wall_bxb7mnl6bzokxuro","wall_0jm76jl97l1pn11g","wall_ku9utuvxec6qn09x","wall_jkmjjnf0i695rhb3","wall_hrzdo3w2sq9pjgoe","wall_e50yfnnocfwnk5hi","wall_dnjctsqpzz9g8bae","wall_1n2g40icx5o2ioln","wall_1pfid7ya3mjsry2a","wall_qmk1kov6chk1rhn1","slab_4tyn48br19e3m2lo","wall_j9mie1ep1ke34ml8","ceiling_wg9lgmkhjuviljij","wall_g26j3dtf36bu6plp","wall_fitty57cmrsit6pf","wall_460g00qka4zmmvwj","wall_5ivktfnj4q69zui4","wall_ig6m35gemx8dd0lj","wall_n7bfomyfezi75jfr","slab_insih5v5fkmprxkm"],"parentId":"building_47yrxyutirp7w94z","baseElevation":0},"stair_geaij9m0pt5dxycv":{"id":"stair_geaij9m0pt5dxycv","name":"Staircase 1","type":"stair","width":1,"object":"node","visible":true,"children":["sseg_ydviu29x1k7pcj5d","sseg_ttyw2sbabqs8v5v4"],"parentId":"level_i80amuksqi4z98rs","position":[-3.382721698284149,0.18,-8.16],"rotation":1.5707963267948966,"stairType":"straight","stepCount":10,"thickness":0.25,"toLevelId":"level_7ykh7xr9sa5h3l9o","totalRise":2.5,"sweepAngle":1.5707963267948966,"fillToFloor":true,"fromLevelId":"level_c4j8imqs0sze5hz0","innerRadius":0.9,"railingMode":"left","openingOffset":0.07,"railingHeight":0.92,"topLandingMode":"none","slabOpeningMode":"destination","topLandingDepth":0.9,"showCenterColumn":true,"showStepSupports":true},"stair_uqnjve0miurt8gsv":{"id":"stair_uqnjve0miurt8gsv","name":"Staircase 1","type":"stair","slots":{"treads":"library:preset-midgrey"},"width":1,"object":"node","visible":true,"children":["sseg_mxgpqiyxincf53dm","sseg_z6r540wu4zisu2cg"],"parentId":"level_i80amuksqi4z98rs","position":[-0.48,-0.01,6.1499999999999995],"rotation":1.5707963267948966,"stairType":"straight","stepCount":10,"thickness":0.25,"toLevelId":"level_i80amuksqi4z98rs","totalRise":2.5,"sweepAngle":1.5707963267948966,"fillToFloor":true,"fromLevelId":"level_yzrswl9a12idqn1b","innerRadius":0.9,"railingMode":"none","openingOffset":0.17,"railingHeight":0.91,"supportSlabId":"slab_xp9ne45jh7stdfka","topLandingMode":"none","slabOpeningMode":"destination","topLandingDepth":0.9,"showCenterColumn":true,"showStepSupports":true},"ceiling_3y7rj3jkhxdmhll9":{"id":"ceiling_3y7rj3jkhxdmhll9","name":"Room 5 Ceiling","type":"ceiling","holes":[],"height":2.6900000000000004,"object":"node","polygon":[[8.5,9.325000000000001],[6.7,9.35],[6.7,6.7],[8.5,6.75]],"visible":true,"children":[],"parentId":"level_i80amuksqi4z98rs","holeMetadata":[],"autoFromWalls":true},"ceiling_86g4wbgw9h0tr99s":{"id":"ceiling_86g4wbgw9h0tr99s","name":"Room 4 Ceiling","type":"ceiling","holes":[],"height":2.6900000000000004,"object":"node","polygon":[[8.5,6.75],[6.7,6.7],[6.7,4.05],[8.5,4.05]],"visible":true,"children":[],"parentId":"level_i80amuksqi4z98rs","holeMetadata":[],"autoFromWalls":true},"ceiling_sm3737w8pq5amwb6":{"id":"ceiling_sm3737w8pq5amwb6","name":"Room 6 Ceiling","type":"ceiling","holes":[],"height":2.6900000000000004,"object":"node","polygon":[[6.7,-3.4000000000000004],[6.7,-4.699999999999999],[7.050000000000001,-4.699999999999999],[7.050000000000001,-5.75],[8.5,-5.75],[8.5,-3.4000000000000004]],"visible":true,"children":[],"parentId":"level_i80amuksqi4z98rs","holeMetadata":[],"autoFromWalls":true},"ceiling_wg9lgmkhjuviljij":{"id":"ceiling_wg9lgmkhjuviljij","name":"Room 15 Ceiling","type":"ceiling","holes":[],"object":"node","polygon":[[13.65,-9.9],[9.450000000000001,-9.850000000000001],[9.5,-13.4],[13.699331547990232,-13.155882167355275]],"visible":true,"children":[],"parentId":"level_sf01i06lzxjhci90","holeMetadata":[],"autoFromWalls":true},"building_47yrxyutirp7w94z":{"id":"building_47yrxyutirp7w94z","type":"building","object":"node","visible":true,"children":["level_i80amuksqi4z98rs","level_sf01i06lzxjhci90","level_9aer4vw8rexz9qbk"],"parentId":"site_tkuvu0spmm7izov4","position":[0,0,0],"rotation":[0,0,0]},"door_05xb8mny9hw5qqfz":{"id":"door_05xb8mny9hw5qqfz","name":"Door 4","side":"front","type":"door","slots":{"panel":"library:preset-charcoal"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_uep7lw9jgtmag335","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_uep7lw9jgtmag335","position":[0.8500000000000001,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_154dl0z66h9ossr5":{"id":"door_154dl0z66h9ossr5","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_460g00qka4zmmvwj","visible":true,"doorType":"french","panicBar":false,"parentId":"wall_460g00qka4zmmvwj","position":[1.31328017066473,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1,1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.045,0.055],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_4496t5gswn6s80fh":{"id":"door_4496t5gswn6s80fh","name":"Door 4","side":"back","type":"door","slots":{"panel":"library:preset-glass"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_hhxdh43u2kwu82n6","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_hhxdh43u2kwu82n6","position":[0.65,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_6847ujfykl4mxxpg":{"id":"door_6847ujfykl4mxxpg","name":"Door 4","side":"back","type":"door","slots":{"frame":"library:preset-charcoal","panel":"library:preset-glass"},"width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_mcp9ybwfe99437ea","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_mcp9ybwfe99437ea","position":[3.5,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_cswt0xn9koyescm9":{"id":"door_cswt0xn9koyescm9","name":"Door 4","side":"front","type":"door","slots":{"frame":"library:preset-charcoal","panel":"library:wood-hungarianparquet2"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_z30f2sysbxfykbvf","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_z30f2sysbxfykbvf","position":[1.35,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_dflxf3jet3iwyl0j":{"id":"door_dflxf3jet3iwyl0j","name":"Door 4","side":"front","type":"door","slots":{"panel":"library:preset-midgrey"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_sho6sk89n8n8piv3","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_sho6sk89n8n8piv3","position":[2.240908220640288,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_gpr13l6diwd6p7vi":{"id":"door_gpr13l6diwd6p7vi","name":"Door 4","side":"back","type":"door","width":3,"handle":false,"height":2.4,"object":"node","wallId":"wall_jkmjjnf0i695rhb3","visible":true,"doorType":"garage-tiltup","panicBar":false,"parentId":"wall_jkmjjnf0i695rhb3","position":[1.8,1.2,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":1,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.1,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"overhead","openingKind":"door","cornerRadius":0.15,"doorCategory":"garage","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":1,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_hckoo7yqxicb2d1d":{"id":"door_hckoo7yqxicb2d1d","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.4116332921371337,"object":"node","wallId":"wall_de6kehxv7lc4pex9","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_de6kehxv7lc4pex9","position":[0.9382140770115392,1.2058166460685669,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.2058166460685669,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_i3q2889ydv9p5si6":{"id":"door_i3q2889ydv9p5si6","name":"Door 4","side":"front","type":"door","slots":{"frame":"library:concrete-polished","panel":"library:preset-nearblack"},"width":3.7931765594988636,"handle":true,"height":2.413133326484127,"object":"node","wallId":"wall_fitty57cmrsit6pf","visible":true,"children":[],"doorType":"french","panicBar":false,"parentId":"wall_fitty57cmrsit6pf","position":[3.910258899690095,1.2065666632420635,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.23,"columnRatios":[0.3333333333333333,0.3333333333333333,0.3333333333333333],"dividerThickness":0.06096000000000001},{"type":"panel","panelDepth":0,"panelInset":0.0435864,"heightRatio":0.05,"columnRatios":[0.3333333333333333,0.3333333333333333,0.3333333333333333],"dividerThickness":0.03},{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.21992419331581559,"columnRatios":[0.3333333333333333,0.3333333333333333,0.3333333333333333],"dividerThickness":0.06096000000000001},{"type":"panel","panelDepth":0.0012192000000000001,"panelInset":0.021031200000000003,"heightRatio":0.04780960724256861,"columnRatios":[1],"dividerThickness":0.03},{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.21992419331581559,"columnRatios":[0.3333333333333333,0.3333333333333333,0.3333333333333333],"dividerThickness":0.06096000000000001},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.05874690655697212,"columnRatios":[1],"dividerThickness":0.03},{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.21992419331581559,"columnRatios":[0.33299999999999996,0.33366666666666667,0.3333333333333333],"dividerThickness":0.06096000000000001}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.054864,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.2065666632420633,"openingShape":"rectangle","contentPadding":[0.0762,0.0762],"frameThickness":0.05181600000000001,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_nlq766qzo5urb582":{"id":"door_nlq766qzo5urb582","name":"Door 4","side":"back","type":"door","slots":{"panel":"library:preset-midgrey"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_mdt4o2r6xroifegy","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_mdt4o2r6xroifegy","position":[2.8000000000000003,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_nxqmcxygwbc0g6ho":{"id":"door_nxqmcxygwbc0g6ho","name":"Door 4","side":"back","type":"door","slots":{"frame":"library:preset-charcoal","panel":"library:preset-glass"},"width":3.268366814179307,"handle":true,"height":2.1,"object":"node","wallId":"wall_1oakh6vclfu5qmwg","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_1oakh6vclfu5qmwg","position":[4.607692793714527,1.05,-2.9674074458784303e-17],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_o1q52jyppkq43ocd":{"id":"door_o1q52jyppkq43ocd","name":"Door 4","side":"back","type":"door","slots":{"panel":"library:preset-charcoal"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_if4f2apfhbqzk8ej","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_if4f2apfhbqzk8ej","position":[0.8500000000000001,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_sksbyv6qm5dda79m":{"id":"door_sksbyv6qm5dda79m","name":"Door 4","side":"back","type":"door","slots":{"panel":"library:preset-midgrey"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_fdjd3bxef0pvivrx","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_fdjd3bxef0pvivrx","position":[1.1,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_wvwuv8c0lbn5vm3j":{"id":"door_wvwuv8c0lbn5vm3j","name":"Door 4","side":"back","type":"door","slots":{"panel":"library:preset-charcoal"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_i2q5s3aknj3kasko","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_i2q5s3aknj3kasko","position":[1.2361867904663084,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_xxw5lk6em2uk02nh":{"id":"door_xxw5lk6em2uk02nh","side":"front","type":"door","slots":{"frame":"library:preset-charcoal","panel":"library:preset-glass"},"width":1.4000000000000004,"handle":true,"height":2.1,"object":"node","wallId":"wall_46uufq7tbo6xq7gq","visible":true,"doorType":"double","panicBar":false,"parentId":"wall_46uufq7tbo6xq7gq","position":[0.7000000000000002,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"sseg_mxgpqiyxincf53dm":{"id":"sseg_mxgpqiyxincf53dm","type":"stair-segment","width":1.1853103637695312,"height":2.5,"length":4.238757610321045,"object":"node","visible":true,"parentId":"stair_uqnjve0miurt8gsv","position":[0,0,0],"rotation":0,"stepCount":10,"thickness":0.25,"fillToFloor":true,"segmentType":"stair","attachmentSide":"front"},"sseg_ttyw2sbabqs8v5v4":{"id":"sseg_ttyw2sbabqs8v5v4","type":"stair-segment","width":1,"height":0,"length":2.615821245861601,"object":"node","visible":true,"parentId":"stair_geaij9m0pt5dxycv","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":true,"segmentType":"landing","attachmentSide":"front"},"sseg_ydviu29x1k7pcj5d":{"id":"sseg_ydviu29x1k7pcj5d","type":"stair-segment","width":1,"height":2.5,"length":5.985549688339233,"object":"node","visible":true,"parentId":"stair_geaij9m0pt5dxycv","position":[0,0,0],"rotation":0,"stepCount":10,"thickness":0.25,"fillToFloor":true,"segmentType":"stair","attachmentSide":"front"},"sseg_z6r540wu4zisu2cg":{"id":"sseg_z6r540wu4zisu2cg","type":"stair-segment","width":1,"height":0,"length":1.2463350292750608,"object":"node","visible":true,"parentId":"stair_uqnjve0miurt8gsv","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":true,"segmentType":"landing","attachmentSide":"front"},"window_14rldlkz0ir5d351":{"id":"window_14rldlkz0ir5d351","name":"Window 5","side":"back","sill":false,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":1.5,"height":1.5,"object":"node","wallId":"wall_oefrz8dk57tz4qad","visible":true,"parentId":"wall_oefrz8dk57tz4qad","position":[0.7828690634523348,1.5064505417336518,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"awning","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0.3,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_2i8ogag7d5a9k3g1":{"id":"window_2i8ogag7d5a9k3g1","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_uz1q3gxudcyrbczq","visible":true,"parentId":"wall_uz1q3gxudcyrbczq","position":[0.3908743441926097,1.4676500724723196,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_3tkd78hy7fu3q9p0":{"id":"window_3tkd78hy7fu3q9p0","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":1.5,"height":1.5,"object":"node","wallId":"wall_ntrpazsddg7c8r78","visible":true,"parentId":"wall_ntrpazsddg7c8r78","position":[1.8354415389995256,1.4326933102530033,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_41mgpg15hg5q1jw4":{"id":"window_41mgpg15hg5q1jw4","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_k7v39bcwpjcvl42v","visible":true,"parentId":"wall_k7v39bcwpjcvl42v","position":[3.85,1.7000000000000002,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_48sy95piuynvc8wc":{"id":"window_48sy95piuynvc8wc","name":"Window 5","side":"back","sill":true,"type":"window","width":1.6,"height":0.8103574387743921,"object":"node","wallId":"wall_k489wtujdy8i27ou","visible":true,"parentId":"wall_k489wtujdy8i27ou","position":[2.7,0.65,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"opening","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rounded","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_5jtz0q5oxxifnqoj":{"id":"window_5jtz0q5oxxifnqoj","name":"Window 5","side":"back","sill":true,"type":"window","width":2.27355527136667,"height":0.9608652258894326,"object":"node","wallId":"wall_fdjd3bxef0pvivrx","visible":true,"parentId":"wall_fdjd3bxef0pvivrx","position":[2.9362280447255897,1.6709354304039379,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"opening","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_854iqmwfjire1l1v":{"id":"window_854iqmwfjire1l1v","name":"Window 5","side":"back","sill":false,"type":"window","slots":{"frame":"library:concrete-polished"},"width":2.8131488558810975,"height":2.3141974020509486,"object":"node","wallId":"wall_7g6gnjs7fq6712dj","visible":true,"children":[],"parentId":"wall_7g6gnjs7fq6712dj","position":[1.8471360801591283,1.1944014619645118,-1.1555185234474693e-17],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"sliding","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_8kxospvky3rl8bd9":{"id":"window_8kxospvky3rl8bd9","name":"Window 5","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":1.2426214188844,"height":1.2592949541244196,"object":"node","wallId":"wall_mcp9ybwfe99437ea","visible":true,"parentId":"wall_mcp9ybwfe99437ea","position":[1.4448916060174861,1.5,-6.798117178705136e-17],"rotation":[0,6.283185307179586,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"louvered","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_8qce71iwvjrnwxy0":{"id":"window_8qce71iwvjrnwxy0","name":"Window 5","side":"back","sill":false,"type":"window","slots":{"frame":"library:concrete-polished"},"width":0.7364181035798131,"height":1.853627952375613,"object":"node","wallId":"wall_fitty57cmrsit6pf","visible":true,"children":[],"parentId":"wall_fitty57cmrsit6pf","position":[6.534337487729644,1.3582933151856362,-4.675590626689238e-17],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"louvered","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.04,"operationState":1,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_aj7nfncuii6d9ks1":{"id":"window_aj7nfncuii6d9ks1","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":2.352838206849428,"height":1.2592949541244196,"object":"node","wallId":"wall_1oakh6vclfu5qmwg","visible":true,"parentId":"wall_1oakh6vclfu5qmwg","position":[1.4210902204156273,1.42035252293779,-2.8033362886152856e-17],"rotation":[0,3.141592653589793,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"awning","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_cth3u7m0zqnkflud":{"id":"window_cth3u7m0zqnkflud","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:concrete-polished"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_h4j4jhid4d99epc4","visible":true,"parentId":"wall_h4j4jhid4d99epc4","position":[3.650895439982074,1.487852856525702,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_e57d0rkbijnk41fx":{"id":"window_e57d0rkbijnk41fx","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":1.318245963463787,"height":1.5,"object":"node","wallId":"wall_ej413c830bju48p3","visible":true,"parentId":"wall_ej413c830bju48p3","position":[0.9114685240377591,1.6016761049417152,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_eojbhto8qaqdk6ql":{"id":"window_eojbhto8qaqdk6ql","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":1.5,"height":1.141896400786345,"object":"node","wallId":"wall_e5hudabid17j7m0c","visible":true,"parentId":"wall_e5hudabid17j7m0c","position":[3.6500000000000004,1.7000000000000002,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_g43e8hgcxfa6yd42":{"id":"window_g43e8hgcxfa6yd42","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":2.352838206849428,"height":1.2592949541244196,"object":"node","wallId":"wall_1oakh6vclfu5qmwg","visible":true,"parentId":"wall_1oakh6vclfu5qmwg","position":[7.6000000000000005,1.35,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"awning","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_hjn05f384cikt568":{"id":"window_hjn05f384cikt568","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_bnywyxujlwp4ubjm","visible":true,"parentId":"wall_bnywyxujlwp4ubjm","position":[1.7862034133023839,1.2659326565876712,0],"rotation":[0,6.283185307179586,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_iyxrjoln2pcq2l2k":{"id":"window_iyxrjoln2pcq2l2k","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_bnywyxujlwp4ubjm","visible":true,"parentId":"wall_bnywyxujlwp4ubjm","position":[0.5585836124303665,1.2659326565876712,0],"rotation":[0,6.283185307179586,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_kg2jwctr4p4rgs8i":{"id":"window_kg2jwctr4p4rgs8i","name":"Window 5","side":"back","sill":false,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.45749697282107765,"height":2.0669934804343617,"object":"node","wallId":"wall_7dc75bkj2yzdqrg3","visible":true,"parentId":"wall_7dc75bkj2yzdqrg3","position":[1.088211730584177,1.457280575950791,-7.700913384943488e-19],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"louvered","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.04,"operationState":1,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_rnllzkswreigp6qf":{"id":"window_rnllzkswreigp6qf","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:concrete-polished"},"width":1.5,"height":1.5,"object":"node","wallId":"wall_xeqtxw0qa9p2gzjz","visible":true,"children":[],"parentId":"wall_xeqtxw0qa9p2gzjz","position":[1.520690133778046,1.5379623613378541,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_wmfuc35d5xgy3q7i":{"id":"window_wmfuc35d5xgy3q7i","name":"Window 5","side":"front","sill":false,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":3.8,"height":1.4085806047505112,"object":"node","wallId":"wall_y7dl0xc08yd7v6o3","visible":true,"parentId":"wall_y7dl0xc08yd7v6o3","position":[3.6246821328419054,1.603304534448552,3.304989257706995e-16],"rotation":[0,12.566370614359172,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.16,"hingesSide":"left","windowType":"bay","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.04,"operationState":1,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_wrr3e03nuzgvq6m0":{"id":"window_wrr3e03nuzgvq6m0","name":"Window 5","side":"back","sill":false,"type":"window","slots":{"frame":"library:concrete-polished"},"width":1.5,"height":1.853627952375613,"object":"node","wallId":"wall_fitty57cmrsit6pf","visible":true,"parentId":"wall_fitty57cmrsit6pf","position":[0.926912549385305,1.3582933151856362,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"louvered","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.04,"operationState":1,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_wta4nf8sd5lla5fx":{"id":"window_wta4nf8sd5lla5fx","name":"Window 5","side":"back","sill":false,"type":"window","slots":{"glass":"scene:mat_bbx4et24lxz4a6qq"},"width":3.1076969323451307,"height":0.48848542158489217,"object":"node","wallId":"wall_ku9utuvxec6qn09x","visible":true,"parentId":"wall_ku9utuvxec6qn09x","position":[1.9538484661725655,2.0500000000000003,9.844304510977416e-17],"rotation":[0,15.707963267948966,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"awning","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_x4save99gcz21374":{"id":"window_x4save99gcz21374","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_uz1q3gxudcyrbczq","visible":true,"parentId":"wall_uz1q3gxudcyrbczq","position":[3.5,1.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_x5cq6wus7bx6nzsv":{"id":"window_x5cq6wus7bx6nzsv","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":1.5,"height":1.546998324043993,"object":"node","wallId":"wall_bdkcmjsihkf59wab","visible":true,"parentId":"wall_bdkcmjsihkf59wab","position":[1.3333785671316756,1.527874395157974,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_xi4od9yzt5sv0rdp":{"id":"window_xi4od9yzt5sv0rdp","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":2.092201848540878,"height":1.2592949541244196,"object":"node","wallId":"wall_dfbucsrupel9xcyu","visible":true,"parentId":"wall_dfbucsrupel9xcyu","position":[2.3603997269724646,1.35,8.699887517519821e-17],"rotation":[0,3.141592653589793,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"louvered","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_yaadtc8npk9apbmj":{"id":"window_yaadtc8npk9apbmj","name":"Window 5","side":"back","sill":true,"type":"window","slots":{"frame":"library:concrete-polished"},"width":1.5,"height":1.5,"object":"node","wallId":"wall_h4j4jhid4d99epc4","visible":true,"parentId":"wall_h4j4jhid4d99epc4","position":[2,1.5,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"louvered","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_yau4scug58im677t":{"id":"window_yau4scug58im677t","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_mcp9ybwfe99437ea","visible":true,"parentId":"wall_mcp9ybwfe99437ea","position":[4.8500000000000005,1.4500000000000002,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_z7gnoxfn6pxyn7us":{"id":"window_z7gnoxfn6pxyn7us","name":"Window 5","side":"back","sill":false,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":3.20991954772716,"height":2.074780167972852,"object":"node","wallId":"wall_a3wsy66uqumu4d10","visible":true,"parentId":"wall_a3wsy66uqumu4d10","position":[2.427037623041907,1.2768073180645225,-2.1955029498356002e-17],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"sliding","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_zrx7tun46ubh2ij8":{"id":"window_zrx7tun46ubh2ij8","name":"Window 1","side":"front","sill":true,"type":"window","slots":{"frame":"library:preset-charcoal"},"width":0.3048,"height":1.524,"object":"node","wallId":"wall_dfbucsrupel9xcyu","visible":true,"parentId":"wall_dfbucsrupel9xcyu","position":[0.6000000000000001,1.3,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_zsm5b7quzm6z8gmm":{"id":"window_zsm5b7quzm6z8gmm","name":"Window 5","side":"back","sill":false,"type":"window","width":0.7511950516449588,"height":0.754905901647373,"object":"node","wallId":"wall_noiqi8om9eykyi63","visible":true,"parentId":"wall_noiqi8om9eykyi63","position":[1.5,2.1,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"awning","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0.3,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03}} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-17.json b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-17.json new file mode 100644 index 0000000000..d6230d4d31 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-17.json @@ -0,0 +1 @@ +{"door_jlacszfb9na2h1n8":{"id":"door_jlacszfb9na2h1n8","name":"Door 1","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_8gdhb44voglwtj8v","visible":true,"metadata":{},"panicBar":false,"parentId":"wall_8gdhb44voglwtj8v","position":[2.75,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"threshold":true,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","handleHeight":1.05,"contentPadding":[0.04,0.04],"frameThickness":0.05,"panicBarHeight":1,"swingDirection":"inward","thresholdHeight":0.02},"item_3zmj1om4ko1x9pj2":{"id":"item_3zmj1om4ko1x9pj2","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["shower","enclosure","cubicle","modern","glass","corner","bathroom","chrome","minimalist","washing","hygiene","plumbing","stall","sleek"],"scale":[1,1,1],"offset":[0.41,0,-0.42],"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1,2,1]},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","position":[1.5,0,-1.5],"rotation":[0,0,0]},"item_c8eb880hbx4l8ja7":{"id":"item_c8eb880hbx4l8ja7","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["fruit","produce","food","kitchen","dining","centerpiece","tabletop","vibrant","fresh","organic","natural","accessory","decor","colorful"],"scale":[1,1,1],"offset":[0,0,0],"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.5,0.3,0.5]},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","position":[2.25,0,-3.25],"rotation":[0,0,0]},"site_5qj3cpqkt5sb7mry":{"id":"site_5qj3cpqkt5sb7mry","type":"site","object":"node","polygon":{"type":"polygon","points":[[-15,-15],[15,-15],[15,15],[-15,15]]},"visible":true,"children":[{"id":"building_1hwhevw13g76vas1","type":"building","object":"node","visible":true,"children":["level_js99lr8qtygbrpud"],"metadata":{},"parentId":null,"position":[0,0,0],"rotation":[0,0,0]}],"metadata":{},"parentId":null},"slab_bbn0g5li1gtrgluw":{"id":"slab_bbn0g5li1gtrgluw","name":"Room 1 Slab","type":"slab","holes":[],"object":"node","polygon":[[4.5,5],[-3.5,5],[-3.5,-1],[-1,-1],[-1,0.5],[4.5,0.5]],"visible":true,"metadata":{},"parentId":"level_js99lr8qtygbrpud","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_yywwynsmfceb37d5":{"id":"slab_yywwynsmfceb37d5","name":"Slab 2","type":"slab","holes":[],"object":"node","polygon":[[4.5,5],[-3.5,5],[-3.5,-1],[-1,-1],[-1,0.5],[4.5,0.5]],"visible":true,"metadata":{},"parentId":"level_js99lr8qtygbrpud","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"wall_6r9n18szh0q1hlj4":{"id":"wall_6r9n18szh0q1hlj4","end":[-1,0.5],"name":"Wall 4","type":"wall","start":[-1,-1],"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","frontSide":"interior","materialPreset":"library:preset-glass"},"wall_8gdhb44voglwtj8v":{"id":"wall_8gdhb44voglwtj8v","end":[4.5,0.5],"name":"Wall 5","type":"wall","start":[-1,0.5],"object":"node","visible":true,"backSide":"exterior","children":["door_jlacszfb9na2h1n8"],"metadata":{},"parentId":"level_js99lr8qtygbrpud","frontSide":"interior"},"wall_mns9xqqke9pucvlb":{"id":"wall_mns9xqqke9pucvlb","end":[-1,-1],"name":"Wall 3","type":"wall","start":[-3.5,-1],"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","frontSide":"interior"},"wall_n092vembwmwyqgbq":{"id":"wall_n092vembwmwyqgbq","end":[-3.5,5],"name":"Wall 1","type":"wall","start":[4.5,5],"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","frontSide":"interior"},"wall_n1xa0800aqmazoar":{"id":"wall_n1xa0800aqmazoar","end":[-4,1.5],"name":"Wall 7","type":"wall","start":[1,1.5],"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_h0hzrubbttc55qf5","frontSide":"unknown"},"wall_ntdnp9kanrinh70y":{"id":"wall_ntdnp9kanrinh70y","end":[-3.5,-1],"name":"Wall 2","type":"wall","start":[-3.5,5],"height":2.5,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","frontSide":"interior","thickness":0.2,"curveOffset":0},"wall_ouh3nsjllwcj220b":{"id":"wall_ouh3nsjllwcj220b","end":[4.5,0.5],"name":"Wall 6","type":"wall","start":[4.5,5],"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","frontSide":"exterior"},"wall_yxpq4bfkmqxqx8vs":{"id":"wall_yxpq4bfkmqxqx8vs","end":[-4,1.5],"name":"Wall 8","type":"wall","start":[-4,-1],"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_h0hzrubbttc55qf5","frontSide":"unknown"},"level_h0hzrubbttc55qf5":{"id":"level_h0hzrubbttc55qf5","type":"level","level":-1,"object":"node","visible":true,"children":["wall_n1xa0800aqmazoar","wall_yxpq4bfkmqxqx8vs"],"metadata":{},"parentId":"building_1hwhevw13g76vas1"},"level_js99lr8qtygbrpud":{"id":"level_js99lr8qtygbrpud","type":"level","level":0,"object":"node","visible":true,"children":["wall_n092vembwmwyqgbq","wall_ntdnp9kanrinh70y","wall_mns9xqqke9pucvlb","wall_6r9n18szh0q1hlj4","wall_8gdhb44voglwtj8v","wall_ouh3nsjllwcj220b","slab_bbn0g5li1gtrgluw","ceiling_ro5rhb1cy66klitz","item_c8eb880hbx4l8ja7","item_3zmj1om4ko1x9pj2","slab_yywwynsmfceb37d5"],"metadata":{},"parentId":null},"ceiling_ro5rhb1cy66klitz":{"id":"ceiling_ro5rhb1cy66klitz","name":"Room 1 Ceiling","type":"ceiling","holes":[],"height":2.5,"object":"node","polygon":[[4.5,5],[-3.5,5],[-3.5,-1],[-1,-1],[-1,0.5],[4.5,0.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_js99lr8qtygbrpud","holeMetadata":[],"autoFromWalls":true},"building_1hwhevw13g76vas1":{"id":"building_1hwhevw13g76vas1","type":"building","object":"node","visible":true,"children":["level_js99lr8qtygbrpud","level_h0hzrubbttc55qf5"],"metadata":{},"parentId":null,"position":[0,0,0],"rotation":[0,0,0]}} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-24.json b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-24.json new file mode 100644 index 0000000000..680dd7ea80 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-24.json @@ -0,0 +1 @@ +{"door_003q2dafgqidsdxm":{"id":"door_003q2dafgqidsdxm","name":"Door 26","side":"front","type":"door","width":1.1,"handle":true,"height":2.6,"object":"node","wallId":"wall_ckjbkszhejacwysj","visible":true,"doorType":"pocket","metadata":{},"panicBar":false,"parentId":"wall_ckjbkszhejacwysj","position":[0.8,1.3,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":1,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"pocket","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.035,0.045],"frameThickness":0.05,"operationState":0.44,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_098asmfnvap5du76":{"id":"door_098asmfnvap5du76","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":2.5,"object":"node","wallId":"wall_1624lf5ywztagcho","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_1624lf5ywztagcho","position":[2.3,1.25,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_0gb3txrhcva9eggd":{"id":"door_0gb3txrhcva9eggd","name":"Door 17","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_rsm36dul3l6ue60h","visible":true,"doorType":"hinged","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_rsm36dul3l6ue60h","position":[0.5,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_11h3hkmf2y1a4qej":{"id":"door_11h3hkmf2y1a4qej","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_poe9onw07jpxc34z","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_poe9onw07jpxc34z","position":[5.6,1.5,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_1iqbwl5ljsok5qta":{"id":"door_1iqbwl5ljsok5qta","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":2.5,"object":"node","wallId":"wall_laxcblwuvhm3ijs7","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_laxcblwuvhm3ijs7","position":[1.6,1.25,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_2rz0zywfxpqi95qs":{"id":"door_2rz0zywfxpqi95qs","name":"Door 25","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_lqvpfuyzau9fzkgs","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_lqvpfuyzau9fzkgs","position":[1.5,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_2zc1fkyldktaa1bi":{"id":"door_2zc1fkyldktaa1bi","name":"Door 53","side":"back","type":"door","width":0.9,"handle":true,"height":2.5,"object":"node","wallId":"wall_7fy1vx9pydr9xs7n","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_7fy1vx9pydr9xs7n","position":[1.5,1.25,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_32vilzg1z4ly2fre":{"id":"door_32vilzg1z4ly2fre","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_lgairsceyw874vwo","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_lgairsceyw874vwo","position":[2,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_3ycwr4olsg7qsbfh":{"id":"door_3ycwr4olsg7qsbfh","name":"Door 1","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_3avujhzyb9vrlmiu","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_3avujhzyb9vrlmiu","position":[1.2,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_612bryuuuvncueq4":{"id":"door_612bryuuuvncueq4","name":"Door 48","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_ptnfpltgh4e4c85b","visible":true,"doorType":"sliding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_ptnfpltgh4e4c85b","position":[0.75,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1,1],"dividerThickness":0.025}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.61,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_6408vazt0pvdfvwt":{"id":"door_6408vazt0pvdfvwt","name":"Door 41","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_4htt68qzmhcal2tp","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_4htt68qzmhcal2tp","position":[1,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_6s80mcnw06l8zsd5":{"id":"door_6s80mcnw06l8zsd5","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_bsrv7p9bnpcdn06h","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_bsrv7p9bnpcdn06h","position":[2.4,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_79e5m56hrbai0wq7":{"id":"door_79e5m56hrbai0wq7","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_vgfztgld1iyz03hs","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_vgfztgld1iyz03hs","position":[5.5,1.5,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_7br7dnqy0mlkibdo":{"id":"door_7br7dnqy0mlkibdo","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_twloychxtm3ec706","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_twloychxtm3ec706","position":[5.3,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_7i68qhc4qnwiqdr2":{"id":"door_7i68qhc4qnwiqdr2","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":2.5,"object":"node","wallId":"wall_0a3llbsfqmoc5ni2","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_0a3llbsfqmoc5ni2","position":[1.85,1.25,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":1,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_85knace7qbiwbeku":{"id":"door_85knace7qbiwbeku","name":"Door 36","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_bmrz9ke2xmdkvynh","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_bmrz9ke2xmdkvynh","position":[1,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_95d7hz9dhied8n19":{"id":"door_95d7hz9dhied8n19","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_vgfztgld1iyz03hs","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_vgfztgld1iyz03hs","position":[2.5,1.5,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_9qpgluas28n0yi3v":{"id":"door_9qpgluas28n0yi3v","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":2.8,"object":"node","wallId":"wall_o3sipgjqvlmla2jt","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_o3sipgjqvlmla2jt","position":[2.5,1.4,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_ag0mssudth9a2afy":{"id":"door_ag0mssudth9a2afy","name":"Door 44","side":"front","type":"door","width":1.55,"handle":true,"height":2.35,"object":"node","wallId":"wall_v8v45xnlfyyc7ep0","visible":true,"doorType":"sliding","metadata":{},"panicBar":false,"parentId":"wall_v8v45xnlfyyc7ep0","position":[2.5,1.175,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1,1],"dividerThickness":0.005}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_aykqs6emre4sxdh3":{"id":"door_aykqs6emre4sxdh3","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_poe9onw07jpxc34z","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_poe9onw07jpxc34z","position":[2.6,1.5,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_az7819jvqmsl3sov":{"id":"door_az7819jvqmsl3sov","name":"Door 54","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_jhq14ndqldmq9vf8","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_jhq14ndqldmq9vf8","position":[2.3000000000000003,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_bn0us8dya3g22tiq":{"id":"door_bn0us8dya3g22tiq","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_m1mxa7gvkcuw886t","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_m1mxa7gvkcuw886t","position":[9.5,1.5,0],"rotation":[0,9.42477796076938,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_d4c5c1cpbszxqjnu":{"id":"door_d4c5c1cpbszxqjnu","name":"Door 52","side":"front","type":"door","width":2,"handle":true,"height":3,"object":"node","wallId":"wall_omc5jlwqm2leepuz","visible":true,"doorType":"double","metadata":{},"panicBar":false,"parentId":"wall_omc5jlwqm2leepuz","position":[1.7,1.5,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_ddapl8ziz3p7cxqo":{"id":"door_ddapl8ziz3p7cxqo","name":"Door 48","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_il3k30g2f3sv1rcm","visible":true,"doorType":"sliding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_il3k30g2f3sv1rcm","position":[0.75,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1,1],"dividerThickness":0.025}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.61,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_dy7nkrp6gpf3wnvc":{"id":"door_dy7nkrp6gpf3wnvc","name":"Door 48","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_vg3bosm6qyt1c25z","visible":true,"doorType":"sliding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_vg3bosm6qyt1c25z","position":[0.8,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1,1],"dividerThickness":0.025}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.61,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_f86wqvbzr8m2gdz5":{"id":"door_f86wqvbzr8m2gdz5","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":2.5,"object":"node","wallId":"wall_5zo7dm0uvk0pfju5","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_5zo7dm0uvk0pfju5","position":[1.5,1.25,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_fadth0vp9x8flk9k":{"id":"door_fadth0vp9x8flk9k","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_tf4qyoz9ekfozccj","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_tf4qyoz9ekfozccj","position":[2.5,1.5,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_g8lx3x486pbrvlp8":{"id":"door_g8lx3x486pbrvlp8","name":"Door 47","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_hclslg87nmmrzhy2","visible":true,"doorType":"pocket","metadata":{},"panicBar":false,"parentId":"wall_hclslg87nmmrzhy2","position":[2,1.05,0],"rotation":[0,9.42477796076938,0],"segments":[{"type":"panel","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":1,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"pocket","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.035,0.045],"frameThickness":0.05,"operationState":0.25,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_hs4mkfaaqx4qksko":{"id":"door_hs4mkfaaqx4qksko","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_vu3f0nwh6q4biyml","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_vu3f0nwh6q4biyml","position":[1.6,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_i3br065zzqiophqr":{"id":"door_i3br065zzqiophqr","name":"Door 47","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_p6up981dq7o6keek","visible":true,"doorType":"pocket","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_p6up981dq7o6keek","position":[2,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":1,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"pocket","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.035,0.045],"frameThickness":0.05,"operationState":0.45,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_i9aw62hd7baa4j86":{"id":"door_i9aw62hd7baa4j86","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_vv46t743yzjkp75d","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_vv46t743yzjkp75d","position":[6,1.5,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_iwdjzs7yvb7fxpn9":{"id":"door_iwdjzs7yvb7fxpn9","name":"Door 9","side":"back","type":"door","width":1.8,"handle":true,"height":3,"object":"node","wallId":"wall_o3sipgjqvlmla2jt","visible":true,"doorType":"folding","metadata":{},"panicBar":false,"parentId":"wall_o3sipgjqvlmla2jt","position":[6,1.5,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":1,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_kb75sajdh4bogo6x":{"id":"door_kb75sajdh4bogo6x","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_vv46t743yzjkp75d","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_vv46t743yzjkp75d","position":[3,1.5,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_kevahot70au3ckwp":{"id":"door_kevahot70au3ckwp","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_ey2wdo1kqv0x23ma","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_ey2wdo1kqv0x23ma","position":[2.5,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_km2yxncnqsnrldvb":{"id":"door_km2yxncnqsnrldvb","name":"Door 25","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_67zv71d6hvihz3wd","visible":true,"doorType":"hinged","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_67zv71d6hvihz3wd","position":[0.8,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_kt1o5t8ahsbxz4s6":{"id":"door_kt1o5t8ahsbxz4s6","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":2.5,"object":"node","wallId":"wall_5tpzo3llueskblic","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_5tpzo3llueskblic","position":[1.6,1.25,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_l2cqtt89tgiyqcfh":{"id":"door_l2cqtt89tgiyqcfh","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_m1mxa7gvkcuw886t","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_m1mxa7gvkcuw886t","position":[6.5,1.5,0],"rotation":[0,9.42477796076938,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_ljuf16e8ozkdtu8p":{"id":"door_ljuf16e8ozkdtu8p","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":2.8,"object":"node","wallId":"wall_fpizzvyeydc1tgwv","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_fpizzvyeydc1tgwv","position":[2,1.4,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_m5dzsciqatw5hyea":{"id":"door_m5dzsciqatw5hyea","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_poe9onw07jpxc34z","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_poe9onw07jpxc34z","position":[8.6,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_m70glk1wsdlx6sol":{"id":"door_m70glk1wsdlx6sol","name":"Door 18","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_mqosy280yms4dcyl","visible":true,"doorType":"hinged","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_mqosy280yms4dcyl","position":[2.5,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_n4poiow1o0jpmnmz":{"id":"door_n4poiow1o0jpmnmz","name":"Door 9","side":"front","type":"door","width":1.8,"handle":true,"height":3,"object":"node","wallId":"wall_te3u345qtohv9vjo","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_te3u345qtohv9vjo","position":[1,1.5,0],"rotation":[0,12.566370614359172,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":1,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_ozmzbgp2e6ezap47":{"id":"door_ozmzbgp2e6ezap47","name":"Door 25","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_zmwbk6swgebpykct","visible":true,"doorType":"hinged","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_zmwbk6swgebpykct","position":[0.7,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_pww6nwv9h1sup14v":{"id":"door_pww6nwv9h1sup14v","name":"Door 47","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_pszoe902uvgt1yqu","visible":true,"doorType":"pocket","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_pszoe902uvgt1yqu","position":[2,1.05,0],"rotation":[0,9.42477796076938,0],"segments":[{"type":"panel","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":1,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"pocket","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.035,0.045],"frameThickness":0.05,"operationState":0.35,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_qo008zrogf9rk1mc":{"id":"door_qo008zrogf9rk1mc","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":2.5,"object":"node","wallId":"wall_zb9zn4p8rteb2uql","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_zb9zn4p8rteb2uql","position":[2,1.25,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_rf0h0gnvtied4uun":{"id":"door_rf0h0gnvtied4uun","name":"Door 6","side":"front","type":"door","width":1.8,"handle":true,"height":3,"object":"node","wallId":"wall_m1mxa7gvkcuw886t","visible":true,"doorType":"folding","metadata":{},"panicBar":false,"parentId":"wall_m1mxa7gvkcuw886t","position":[12,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":1,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_sqzmuwh0yxiejf5j":{"id":"door_sqzmuwh0yxiejf5j","name":"Door 53","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_4d0xw9erem5q4j9h","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_4d0xw9erem5q4j9h","position":[0.5,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_ttkair3f0ki8ltgz":{"id":"door_ttkair3f0ki8ltgz","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_vu3f0nwh6q4biyml","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_vu3f0nwh6q4biyml","position":[4.6,1.5,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_wtguwf95s0e94wum":{"id":"door_wtguwf95s0e94wum","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":2.8,"object":"node","wallId":"wall_uhqtl0rapbnfigqy","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_uhqtl0rapbnfigqy","position":[2.5,1.4,0],"rotation":[0,0,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_yeqzk2brm4dxbl5w":{"id":"door_yeqzk2brm4dxbl5w","name":"Door 45","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_1aqnio3z2swd7632","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_1aqnio3z2swd7632","position":[1.5,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_yf7b3k1ogsdfpoe2":{"id":"door_yf7b3k1ogsdfpoe2","name":"Door 37","side":"front","type":"door","width":1.5,"handle":true,"height":2,"object":"node","wallId":"wall_zovp1qu83cbgn2u9","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_zovp1qu83cbgn2u9","position":[1.7,1,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0,"heightRatio":0.95,"columnRatios":[1],"dividerThickness":0.025}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.045,0.055],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_ylobpafj247i70r2":{"id":"door_ylobpafj247i70r2","name":"Door 2","side":"back","type":"door","width":3,"handle":true,"height":3,"object":"node","wallId":"wall_m1mxa7gvkcuw886t","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_m1mxa7gvkcuw886t","position":[3.5,1.5,0],"rotation":[0,9.42477796076938,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_yp2pr1gco66644fz":{"id":"door_yp2pr1gco66644fz","name":"Door 2","side":"front","type":"door","width":1.5,"handle":true,"height":2.8,"object":"node","wallId":"wall_j06as20cdjshont3","visible":true,"doorType":"sliding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_j06as20cdjshont3","position":[1,1.4,0],"rotation":[0,12.566370614359172,0],"segments":[{"type":"glass","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1,1],"dividerThickness":0.005}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":1,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_zgu2bjq7cgqmhl01":{"id":"door_zgu2bjq7cgqmhl01","name":"Door 2","side":"front","type":"door","width":3,"handle":true,"height":2.5,"object":"node","wallId":"wall_eoyrn00w7x0htu9w","visible":true,"doorType":"folding","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_eoyrn00w7x0htu9w","position":[2,1.25,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"glass","panelDepth":0.008,"panelInset":0.025,"heightRatio":1,"columnRatios":[1],"dividerThickness":0.02}],"leafCount":4,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"right","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_zky92rx94vi84jrl":{"id":"door_zky92rx94vi84jrl","name":"Door 12","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_511vyjfe86jdpfjc","visible":true,"doorType":"hinged","metadata":{},"panicBar":false,"parentId":"wall_511vyjfe86jdpfjc","position":[2.5,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"door_zw4lnwcudh61rwi2":{"id":"door_zw4lnwcudh61rwi2","name":"Door 42","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_9evtpcg2zxspy62d","visible":true,"doorType":"hinged","metadata":{"isNew":true},"panicBar":false,"parentId":"wall_9evtpcg2zxspy62d","position":[1,1.05,0],"rotation":[0,6.283185307179586,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"garagePanelCount":4,"openingRadiusMode":"all","openingRevealRadius":0.025},"item_2paojpidf3f3xfqu":{"id":"item_2paojpidf3f3xfqu","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[0.8,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[6.88,0,2.3],"rotation":[0,-10.995574287564276,0]},"item_3dardy3wuzy5q0o6":{"id":"item_3dardy3wuzy5q0o6","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[10.58,0,3.59],"rotation":[0,-1.5707963267948966,0]},"item_3qn9x40xfvjj3vyx":{"id":"item_3qn9x40xfvjj3vyx","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["floor","large"],"scale":[1,1,1],"offset":[-1.0058283805847168e-06,6.139533326177116e-14,-0.23925671353936195],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.42,0.82,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17.75,0,5.5],"rotation":[0,-3.141592653589793,0]},"item_49oh8gegy3b7yvxf":{"id":"item_49oh8gegy3b7yvxf","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-19,0,-3.5],"rotation":[0,-9.42477796076938,0]},"item_4ppll7gktbykanvz":{"id":"item_4ppll7gktbykanvz","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[0.8,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[6.32,0,-3.17],"rotation":[0,-4.71238898038469,0]},"item_75gj10k31pq2vd3q":{"id":"item_75gj10k31pq2vd3q","name":"Item 3","type":"item","asset":{"id":"item-03","src":"/items/placeholder.glb","name":"Item 3","tags":["bathtub","tub","bath","soaking","modern","minimalist","porcelain","acrylic","ceramic","bathroom","relaxation","spa"],"scale":[1,1,1],"offset":[-4.172325134277344e-07,2.690202336452785e-07,8.642673492431641e-07],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[2.34,0.79,1.11],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-18.22,0,-9.9],"rotation":[0,0,0]},"item_9c4on91q6ohlq32r":{"id":"item_9c4on91q6ohlq32r","name":"Item 4","type":"item","asset":{"id":"item-04","src":"/items/placeholder.glb","name":"Item 4","tags":["bar","counter","island","breakfast","modern","contemporary","wood","stone","quartz","seating","dining","prep","entertaining"],"scale":[2.49,2.49,2.49],"offset":[0.0003166446089745145,0.5321682389080525,-0.002378878891468039],"source":"library","isDraft":false,"surface":{"height":1.06},"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[2.5,1.06,0.96],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[0.5,0.4,0.8],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[10.67,-0.31,11.32],"rotation":[0,-17.27875959474386,0]},"item_9eyeyrqz7vmbj2ix":{"id":"item_9eyeyrqz7vmbj2ix","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-14.01,0,0.64],"rotation":[0,-9.42477796076938,0]},"item_9u5lgu7a9ps314m1":{"id":"item_9u5lgu7a9ps314m1","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[2.37,0,-10.03],"rotation":[0,-4.71238898038469,0]},"item_b5i0u6wmn8ez0cak":{"id":"item_b5i0u6wmn8ez0cak","name":"Item 5","side":"front","type":"item","asset":{"id":"item-05","src":"/items/placeholder.glb","name":"Item 5","tags":["shelf","shelving","rack","ledge","storage","organization","display","bookshelf","modern","minimalist","furniture","decor","contemporary"],"scale":[1,1,1],"offset":[3.3080577850341797e-06,0.01999995157122612,1.7977897925902653e-07],"source":"library","isDraft":false,"surface":{"height":0.04},"attachTo":"wall-side","category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.74,0.04,0.32],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[3,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"wall_lbygbccrx2zapwc9","position":[1.18,1,0],"rotation":[0,0,0]},"item_b7yy788blhr8hovy":{"id":"item_b7yy788blhr8hovy","name":"Item 6","type":"item","asset":{"id":"item-06","src":"/items/placeholder.glb","name":"Item 6","tags":["counter","countertop","island","surface","workspace","stone","granite","marble","modern","kitchen","cooking","prep","sleek","polished"],"scale":[1,1,1],"offset":[0.0011913180351257324,2.36733797009947e-08,-0.0003906339406967163],"source":"library","isDraft":false,"surface":{"height":0.73},"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.96,0.73,0.63],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1.9,1,1.7],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[8.86,0,-0.28],"rotation":[0,-1.5707963267948972,0]},"item_bbsvwhx3gi0rvj2j":{"id":"item_bbsvwhx3gi0rvj2j","name":"Item 7","type":"item","asset":{"id":"item-07","src":"/items/placeholder.glb","name":"Item 7","tags":["floor","large"],"scale":[1,1,1],"offset":[0.4000015414357563,0,-0.39945451711537316],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.81,1.8,0.81],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17.5,0,-8.5],"rotation":[0,-7.853981633974483,0]},"item_bemxpqe5zyv62xat":{"id":"item_bemxpqe5zyv62xat","name":"Item 6","type":"item","asset":{"id":"item-06","src":"/items/placeholder.glb","name":"Item 6","tags":["counter","countertop","island","surface","workspace","stone","granite","marble","modern","kitchen","cooking","prep","sleek","polished"],"scale":[1,1,1],"offset":[0.0011913180351257324,2.36733797009947e-08,-0.0003906339406967163],"source":"library","isDraft":false,"surface":{"height":0.73},"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.96,0.73,0.63],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[2.5,1.1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[10.65,0,-0.51],"rotation":[0,-4.712388980384691,0]},"item_bmn4w1vvzmz75e6k":{"id":"item_bmn4w1vvzmz75e6k","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-14,0,10.66],"rotation":[0,-9.42477796076938,0]},"item_bvo47cc15sv7mfie":{"id":"item_bvo47cc15sv7mfie","name":"Item 8","type":"item","asset":{"id":"item-08","src":"/items/placeholder.glb","name":"Item 8","tags":["floor","seating"],"scale":[1,1,1],"offset":[-0.002263486385345459,0.008962750434875488,0.04589979350566864],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[2.06,0.74,1.01],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-9.75,0,14.25],"rotation":[0,-4.71238898038469,0]},"item_cjqvy71xiz2bj7oq":{"id":"item_cjqvy71xiz2bj7oq","name":"Item 9","type":"item","asset":{"id":"item-09","src":"/items/placeholder.glb","name":"Item 9","tags":["bed","bedstead","double","frame","bedroom","sleeping","modern","minimalist","upholstered","wood","sleep","furniture","contemporary"],"scale":[1,1,1],"offset":[0.004185318946838379,2.028451717706048e-07,-0.027721375226974487],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.52,0.71,2],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17,0,3.5],"rotation":[0,-9.42477796076938,0]},"item_cmrx8hp4jc508xhi":{"id":"item_cmrx8hp4jc508xhi","name":"Item 10","side":"front","type":"item","asset":{"id":"item-10","src":"/items/placeholder.glb","name":"Item 10","tags":["charger","station","electric","vehicle","automotive","garage","modern","minimalist","power","energy","appliance","tech","sleek","plastic","black"],"scale":[1,1,1],"offset":[-0.06774237006902695,0.29789352063503666,0.15027912145209474],"source":"library","isDraft":false,"attachTo":"wall","category":"appliance","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.29,0.65,0.17],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"wall_dazxo798ki8pgnff","position":[4,0.5,0],"rotation":[0,0,0]},"item_e8jxcs2rceaqif9v":{"id":"item_e8jxcs2rceaqif9v","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["floor","large"],"scale":[1,1,1],"offset":[-1.0058283805847168e-06,6.139533326177116e-14,-0.23925671353936195],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.42,0.82,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-14.25,0,-2.5],"rotation":[0,-2.4492935982947064e-16,0]},"item_eyljfsnlp19x60u4":{"id":"item_eyljfsnlp19x60u4","name":"Item 11","type":"item","asset":{"id":"item-11","src":"/items/placeholder.glb","name":"Item 11","tags":["tesla","car","vehicle","automobile","electric","modern","minimalist","sleek","metal","glass","luxury","transportation","commuting"],"scale":[1,1,1],"offset":[0.0038899771975877684,-0.01017908506396381,-0.01475837322021789],"source":"library","isDraft":false,"category":"outdoor","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.98,1.62,4.76],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[11.3,0,-9.9],"rotation":[0,0,0]},"item_f1y18gw5p6fvehhg":{"id":"item_f1y18gw5p6fvehhg","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-14,0,5.64],"rotation":[0,-9.42477796076938,0]},"item_fl3hswt3euwto8qy":{"id":"item_fl3hswt3euwto8qy","name":"Item 4","type":"item","asset":{"id":"item-04","src":"/items/placeholder.glb","name":"Item 4","tags":["bar","counter","island","breakfast","modern","contemporary","wood","stone","quartz","seating","dining","prep","entertaining"],"scale":[2.49,2.49,2.49],"offset":[0.0003166446089745145,0.5321682389080525,-0.002378878891468039],"source":"library","isDraft":false,"surface":{"height":1.06},"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[2.5,1.06,0.96],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1.5,0.8,1.1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[8.77,-0.1,9.26],"rotation":[0,-4.71238898038469,0]},"item_fqtfdbv5dfqjqcoz":{"id":"item_fqtfdbv5dfqjqcoz","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["floor","large"],"scale":[1,1,1],"offset":[-1.0058283805847168e-06,6.139533326177116e-14,-0.23925671353936195],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.42,0.82,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17.75,0,11.5],"rotation":[0,-6.283185307179586,0]},"item_g1s2kivkxdq7kx7x":{"id":"item_g1s2kivkxdq7kx7x","name":"Item 12","type":"item","asset":{"id":"item-12","src":"/items/placeholder.glb","name":"Item 12","tags":["piano","instrument","musical","grand","upright","keyboard","wood","polished","lacquer","ebony","classic","traditional","music","entertainment","luxury"],"scale":[1,1,1],"offset":[0,0,0.01619933545589447],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.54,1.44,0.69],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-10,0,-6],"rotation":[0,-10.995574287564276,0]},"item_gnmwdolg7xbhapzd":{"id":"item_gnmwdolg7xbhapzd","name":"Item 5","side":"front","type":"item","asset":{"id":"item-05","src":"/items/placeholder.glb","name":"Item 5","tags":["shelf","shelving","rack","ledge","storage","organization","display","bookshelf","modern","minimalist","furniture","decor","contemporary"],"scale":[1,1,1],"offset":[3.3080577850341797e-06,0.01999995157122612,1.7977897925902653e-07],"source":"library","isDraft":false,"surface":{"height":0.04},"attachTo":"wall-side","category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.74,0.04,0.32],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[3,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"wall_lbygbccrx2zapwc9","position":[1.18,0.5,0],"rotation":[0,0,0]},"item_gwq4pjm91g1o6b6c":{"id":"item_gwq4pjm91g1o6b6c","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["floor","large"],"scale":[1,1,1],"offset":[-1.0058283805847168e-06,6.139533326177116e-14,-0.23925671353936195],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.42,0.82,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-1.975,0,-9.975],"rotation":[0,0,0]},"item_hle7coq8741fo7a6":{"id":"item_hle7coq8741fo7a6","name":"Item 5","side":"front","type":"item","asset":{"id":"item-05","src":"/items/placeholder.glb","name":"Item 5","tags":["shelf","shelving","rack","ledge","storage","organization","display","bookshelf","modern","minimalist","furniture","decor","contemporary"],"scale":[1,1,1],"offset":[3.3080577850341797e-06,0.01999995157122612,1.7977897925902653e-07],"source":"library","isDraft":false,"surface":{"height":0.04},"attachTo":"wall-side","category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.74,0.04,0.32],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[3,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"wall_lbygbccrx2zapwc9","position":[1.18,2.5,0],"rotation":[0,0,0]},"item_hr6pnvwvn6b1yvd4":{"id":"item_hr6pnvwvn6b1yvd4","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["floor","large"],"scale":[1,1,1],"offset":[-1.0058283805847168e-06,6.139533326177116e-14,-0.23925671353936195],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.42,0.82,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[12.5,0,6.54],"rotation":[0,-1.5707963267948966,0]},"item_i2dvy7hbyprzy6zc":{"id":"item_i2dvy7hbyprzy6zc","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-14,0,11.36],"rotation":[0,-6.283185307179586,0]},"item_ia6qe7ep6w646lp1":{"id":"item_ia6qe7ep6w646lp1","name":"Item 7","type":"item","asset":{"id":"item-07","src":"/items/placeholder.glb","name":"Item 7","tags":["floor","large"],"scale":[1,1,1],"offset":[0.4000015414357563,0,-0.39945451711537316],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.81,1.8,0.81],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-18.5,0,10.5],"rotation":[0,-3.141592653589793,0]},"item_iu7jblky9i7h6x90":{"id":"item_iu7jblky9i7h6x90","name":"Item 4","type":"item","asset":{"id":"item-04","src":"/items/placeholder.glb","name":"Item 4","tags":["bar","counter","island","breakfast","modern","contemporary","wood","stone","quartz","seating","dining","prep","entertaining"],"scale":[2.49,2.49,2.49],"offset":[0.0003166446089745145,0.5321682389080525,-0.002378878891468039],"source":"library","isDraft":false,"surface":{"height":1.06},"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[2.5,1.06,0.96],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1.3,1,0.8],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[5.8,0,6],"rotation":[0,-9.42477796076938,0]},"item_iydikfspl2x5gdv4":{"id":"item_iydikfspl2x5gdv4","name":"Item 13","type":"item","asset":{"id":"item-13","src":"/items/placeholder.glb","name":"Item 13","tags":["chair","armchair","seating","lounge","upholstered","modern","fabric","furniture","minimalist","comfort","accent","lounger"],"scale":[1,1,1],"offset":[-3.5762786865234375e-07,5.49523756490089e-05,0.0052942633628845215],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.1,0.75,1.07],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-9.54,0,12.28],"rotation":[0,1.2915436464758039,0]},"item_jwird8y6e9juvm2l":{"id":"item_jwird8y6e9juvm2l","name":"Item 5","side":"front","type":"item","asset":{"id":"item-05","src":"/items/placeholder.glb","name":"Item 5","tags":["shelf","shelving","rack","ledge","storage","organization","display","bookshelf","modern","minimalist","furniture","decor","contemporary"],"scale":[1,1,1],"offset":[3.3080577850341797e-06,0.01999995157122612,1.7977897925902653e-07],"source":"library","isDraft":false,"surface":{"height":0.04},"attachTo":"wall-side","category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.74,0.04,0.32],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[3,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"wall_lbygbccrx2zapwc9","position":[1.18,2,0],"rotation":[0,0,0]},"item_koh2dkodepr7fdry":{"id":"item_koh2dkodepr7fdry","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17,0,-3.5],"rotation":[0,-9.42477796076938,0]},"item_lqn1xzoxt7hyp5dv":{"id":"item_lqn1xzoxt7hyp5dv","name":"Item 7","type":"item","asset":{"id":"item-07","src":"/items/placeholder.glb","name":"Item 7","tags":["floor","large"],"scale":[1,1,1],"offset":[0.4000015414357563,0,-0.39945451711537316],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.81,1.8,0.81],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-18.5,0,11.5],"rotation":[0,0,0]},"item_lya5kbtxvt1jxnbx":{"id":"item_lya5kbtxvt1jxnbx","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["floor","large"],"scale":[1,1,1],"offset":[-1.0058283805847168e-06,6.139533326177116e-14,-0.23925671353936195],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.42,0.82,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17.75,0,10.5],"rotation":[0,-3.141592653589793,0]},"item_m0rfafsc3o4dn4nu":{"id":"item_m0rfafsc3o4dn4nu","name":"Item 9","type":"item","asset":{"id":"item-09","src":"/items/placeholder.glb","name":"Item 9","tags":["bed","bedstead","double","frame","bedroom","sleeping","modern","minimalist","upholstered","wood","sleep","furniture","contemporary"],"scale":[1,1,1],"offset":[0.004185318946838379,2.028451717706048e-07,-0.027721375226974487],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.52,0.71,2],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-16,0,-8.21],"rotation":[0,-4.71238898038469,0]},"item_mo9d0rcr24zrt7l0":{"id":"item_mo9d0rcr24zrt7l0","name":"Item 14","type":"item","asset":{"id":"item-14","src":"/items/placeholder.glb","name":"Item 14","tags":["desk","table","workstation","furniture","office","work","study","writing","modern","minimalist","industrial","wood","metal"],"scale":[1,1,1],"offset":[-7.927417755126953e-05,1.6806073688258039e-07,-0.005174309015274048],"source":"library","isDraft":false,"surface":{"height":0.75},"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.51,0.76,0.62],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-8,0,-11],"rotation":[0,0,0]},"item_nc7jgap1n30bf0lq":{"id":"item_nc7jgap1n30bf0lq","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[2.37,0,-8.07],"rotation":[0,-4.71238898038469,0]},"item_oq7sjc61h8gpny4t":{"id":"item_oq7sjc61h8gpny4t","name":"Item 6","type":"item","asset":{"id":"item-06","src":"/items/placeholder.glb","name":"Item 6","tags":["counter","countertop","island","surface","workspace","stone","granite","marble","modern","kitchen","cooking","prep","sleek","polished"],"scale":[1,1,1],"offset":[0.0011913180351257324,2.36733797009947e-08,-0.0003906339406967163],"source":"library","isDraft":false,"surface":{"height":0.73},"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.96,0.73,0.63],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1.5,1.1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[7.49,0,-3.67],"rotation":[0,-3.141592653589793,0]},"item_osle5nqu0qcanyvw":{"id":"item_osle5nqu0qcanyvw","name":"Item 7","type":"item","asset":{"id":"item-07","src":"/items/placeholder.glb","name":"Item 7","tags":["floor","large"],"scale":[1,1,1],"offset":[0.4000015414357563,0,-0.39945451711537316],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.81,1.8,0.81],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-13.5,0,-2.5],"rotation":[0,-6.283185307179586,0]},"item_p5ybd7s29uvarrva":{"id":"item_p5ybd7s29uvarrva","name":"Item 15","type":"item","asset":{"id":"item-15","src":"/items/placeholder.glb","name":"Item 15","tags":["fridge","refrigerator","freezer","appliance","kitchen","storage","cooling","metal","steel","modern","industrial","minimalist","silver","sleek"],"scale":[1,1,1],"offset":[3.1739473342895508e-06,4.9804359747440685e-08,-0.05069310963153839],"source":"library","isDraft":false,"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.7,1.92,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[10.5,0,2.24],"rotation":[0,-20.420352248333657,0]},"item_phyf3kvw72q20sj9":{"id":"item_phyf3kvw72q20sj9","name":"Item 5","side":"front","type":"item","asset":{"id":"item-05","src":"/items/placeholder.glb","name":"Item 5","tags":["shelf","shelving","rack","ledge","storage","organization","display","bookshelf","modern","minimalist","furniture","decor","contemporary"],"scale":[1,1,1],"offset":[3.3080577850341797e-06,0.01999995157122612,1.7977897925902653e-07],"source":"library","isDraft":false,"surface":{"height":0.04},"attachTo":"wall-side","category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.74,0.04,0.32],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[3,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"wall_lbygbccrx2zapwc9","position":[1.18,1.5,0],"rotation":[0,0,0]},"item_rnpnvb2zptsklouk":{"id":"item_rnpnvb2zptsklouk","name":"Item 16","type":"item","asset":{"id":"item-16","src":"/items/placeholder.glb","name":"Item 16","tags":["sink","basin","lavatory","washbasin","vanity","modern","minimalist","ceramic","porcelain","white","plumbing","washing","bathroom","hygiene"],"scale":[1,1,1],"offset":[0.1037352979183197,1.7134145480213192e-07,0.022128716111183167],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.83,0.97,0.63],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[0.7,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17.36,0,-6.24],"rotation":[0,-7.853981633974483,0]},"item_rqw12mokwasjm197":{"id":"item_rqw12mokwasjm197","name":"Item 7","type":"item","asset":{"id":"item-07","src":"/items/placeholder.glb","name":"Item 7","tags":["floor","large"],"scale":[1,1,1],"offset":[0.4000015414357563,0,-0.39945451711537316],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.81,1.8,0.81],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-18.5,0,5.5],"rotation":[0,-3.141592653589793,0]},"item_rt1jnwuu5q7jr1ho":{"id":"item_rt1jnwuu5q7jr1ho","name":"Item 9","type":"item","asset":{"id":"item-09","src":"/items/placeholder.glb","name":"Item 9","tags":["bed","bedstead","double","frame","bedroom","sleeping","modern","minimalist","upholstered","wood","sleep","furniture","contemporary"],"scale":[1,1,1],"offset":[0.004185318946838379,2.028451717706048e-07,-0.027721375226974487],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.52,0.71,2],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-16.98,0,13.54],"rotation":[0,0,0]},"item_rz8i6vvgycvkciu4":{"id":"item_rz8i6vvgycvkciu4","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[5,0,-2.66],"rotation":[0,0,0]},"item_ttkl9g6k5bmdn81l":{"id":"item_ttkl9g6k5bmdn81l","name":"Item 17","type":"item","asset":{"id":"item-17","src":"/items/placeholder.glb","name":"Item 17","tags":["dining","table","dinette","wood","oak","modern","minimalist","scandinavian","rectangular","kitchen","mealtime","entertaining"],"scale":[2,2,2],"offset":[0.000243455171585083,0.379309743642807,-0.002589896321296692],"source":"library","isDraft":false,"surface":{"height":0.77},"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[2,0.77,0.91],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1.5,1,1.1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[5.91,0,9.75],"rotation":[0,-1.5707963267948966,0]},"item_twd7ta3np8q1my3n":{"id":"item_twd7ta3np8q1my3n","name":"Item 9","type":"item","asset":{"id":"item-09","src":"/items/placeholder.glb","name":"Item 9","tags":["bed","bedstead","double","frame","bedroom","sleeping","modern","minimalist","upholstered","wood","sleep","furniture","contemporary"],"scale":[1,1,1],"offset":[0.004185318946838379,2.028451717706048e-07,-0.027721375226974487],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.52,0.71,2],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17,0,8.5],"rotation":[0,-3.141592653589793,0]},"item_vd6lnd61man7injx":{"id":"item_vd6lnd61man7injx","name":"Item 4","type":"item","asset":{"id":"item-04","src":"/items/placeholder.glb","name":"Item 4","tags":["bar","counter","island","breakfast","modern","contemporary","wood","stone","quartz","seating","dining","prep","entertaining"],"scale":[2.49,2.49,2.49],"offset":[0.0003166446089745145,0.5321682389080525,-0.002378878891468039],"source":"library","isDraft":false,"surface":{"height":1.06},"category":"kitchen","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[2.5,1.06,0.96],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1.3,0.8,0.8],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[10.66,-0.1,9.16],"rotation":[0,-17.27875959474386,0]},"item_xq66fayns2ugskna":{"id":"item_xq66fayns2ugskna","name":"Item 9","type":"item","asset":{"id":"item-09","src":"/items/placeholder.glb","name":"Item 9","tags":["bed","bedstead","double","frame","bedroom","sleeping","modern","minimalist","upholstered","wood","sleep","furniture","contemporary"],"scale":[1,1,1],"offset":[0.004185318946838379,2.028451717706048e-07,-0.027721375226974487],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.52,0.71,2],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17.5,0,-2],"rotation":[0,-6.283185307179586,0]},"item_xvwq3s5d26gmao82":{"id":"item_xvwq3s5d26gmao82","name":"Item 2","type":"item","asset":{"id":"item-02","src":"/items/placeholder.glb","name":"Item 2","tags":["floor","large"],"scale":[1,1,1],"offset":[-1.0058283805847168e-06,6.139533326177116e-14,-0.23925671353936195],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.42,0.82,0.72],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-17.45,0,-7.34],"rotation":[0,-7.853981633974483,0]},"item_y2mq75o5q1n8n333":{"id":"item_y2mq75o5q1n8n333","name":"Item 1","type":"item","asset":{"id":"item-01","src":"/items/placeholder.glb","name":"Item 1","tags":["closet","wardrobe","armoire","cabinet","storage","organization","wood","bedroom","modern","minimalist","clothing","apparel","cupboard","locker"],"scale":[1,1,1],"offset":[-3.2782554626464844e-06,4.649089291319797e-08,-0.0141085684299469],"source":"library","isDraft":false,"category":"furniture","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[1.95,2.26,0.6],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1.2,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[6.89,0,4.28],"rotation":[0,-4.71238898038469,0]},"item_y9bc3lpc2ci6pxsv":{"id":"item_y9bc3lpc2ci6pxsv","name":"Item 18","type":"item","asset":{"id":"item-18","src":"/items/placeholder.glb","name":"Item 18","tags":["floor","large","electronics"],"scale":[1,1,1],"offset":[-1.862645149230957e-06,1.0083027035534542e-07,-0.011400297284126282],"source":"library","isDraft":false,"category":"bathroom","rotation":[0,0,0],"thumbnail":"/items/placeholder.webp","dimensions":[0.6,0.86,0.53],"floorPlanUrl":"/items/placeholder-floor-plan.webp"},"scale":[1,1,1],"object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-9.450000000000001,0,5.4750000000000005],"rotation":[0,0,0]},"roof_14zvu2n2u6yg8o05":{"id":"roof_14zvu2n2u6yg8o05","name":"Roof 6","type":"roof","object":"node","visible":true,"children":["rseg_xbmtr7zm4chleq6e"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-7.75,0,-13],"rotation":0},"roof_18wafaxjhnk09d57":{"id":"roof_18wafaxjhnk09d57","name":"Roof 15","type":"roof","object":"node","visible":true,"children":["rseg_nuh3hvdww3gglo4d"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-10,0,0],"rotation":0},"roof_2gl2hghodp541yw9":{"id":"roof_2gl2hghodp541yw9","name":"Roof 18","type":"roof","object":"node","visible":true,"children":["rseg_afrfkpvhg38camgr"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[2.25,0,6.25],"rotation":0},"roof_4c9z960oiy9mvtd0":{"id":"roof_4c9z960oiy9mvtd0","name":"Roof 21","type":"roof","object":"node","visible":true,"children":["rseg_cvz682eh4kr70w72"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-15,0,-7.75],"rotation":0},"roof_58fhgyatlj0739cq":{"id":"roof_58fhgyatlj0739cq","name":"Roof 25","type":"roof","object":"node","visible":true,"children":["rseg_ysf1cnf72psu34wz"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[0,0.05,-14.25],"rotation":0},"roof_5ai324c2mm4g9oe9":{"id":"roof_5ai324c2mm4g9oe9","name":"Roof 21","type":"roof","object":"node","visible":true,"children":["rseg_izrb0u0dd9bzoqsl"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[8,0,17.5],"rotation":0},"roof_6fs144kokuw3d66o":{"id":"roof_6fs144kokuw3d66o","name":"Roof 20","type":"roof","object":"node","visible":true,"children":["rseg_mgm797va9dpyku7m"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[2.5,0,-6.25],"rotation":0},"roof_6gxvkkt81ntnp0h4":{"id":"roof_6gxvkkt81ntnp0h4","name":"Roof 3","type":"roof","object":"node","visible":true,"children":["rseg_bocdxxx7uk7q3gxb"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[7.5,0,-9.75],"rotation":0},"roof_b5t2vadph3339fj1":{"id":"roof_b5t2vadph3339fj1","name":"Roof 23","type":"roof","object":"node","visible":true,"children":["rseg_bani5h96ni5ziui1"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-19.25,0,-8],"rotation":0},"roof_c3wrxwv3tv2eog7q":{"id":"roof_c3wrxwv3tv2eog7q","name":"Roof 24","type":"roof","object":"node","visible":true,"children":["rseg_lvtc0446u3nffgxd"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-12,0,14.5],"rotation":0},"roof_daipbvbrid886o9d":{"id":"roof_daipbvbrid886o9d","name":"Roof 20","type":"roof","object":"node","visible":true,"children":["rseg_rf924f04g6ixruoi"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[13.25,0,4.75],"rotation":0},"roof_f3uny9sfzkuju5wo":{"id":"roof_f3uny9sfzkuju5wo","name":"Roof 7","type":"roof","object":"node","visible":true,"children":["rseg_k23o2ih8wfn5b0ic"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-6.5,0,-8.25],"rotation":0},"roof_fjutdcwgvmaxx6tu":{"id":"roof_fjutdcwgvmaxx6tu","name":"Roof 9","type":"roof","object":"node","visible":true,"children":["rseg_di5vviiqou7jd8w7"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-6.5,0,-2.5],"rotation":0},"roof_igb1vv7574i5lvqq":{"id":"roof_igb1vv7574i5lvqq","name":"Roof 27","type":"roof","object":"node","visible":true,"children":["rseg_4hrj8mu5olcsm9ty"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[13.25,0,1.75],"rotation":0},"roof_iw0d29jyd8h3ug2h":{"id":"roof_iw0d29jyd8h3ug2h","name":"Roof 18","type":"roof","object":"node","visible":true,"children":["rseg_o0efrwa15nevfhcd"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-5.25,0,16],"rotation":0},"roof_ja24y37qth8r8z5k":{"id":"roof_ja24y37qth8r8z5k","name":"Roof 22","type":"roof","object":"node","visible":true,"children":["rseg_qlcqbzy4j2opbyo9"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-16.75,0,9.25],"rotation":0},"roof_k4weorepgkerrkue":{"id":"roof_k4weorepgkerrkue","name":"Roof 11","type":"roof","object":"node","visible":true,"children":["rseg_fu5znxakqkr4illb"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-18,0,-8],"rotation":0},"roof_l8novz1nm4f87uwg":{"id":"roof_l8novz1nm4f87uwg","name":"Roof 28","type":"roof","object":"node","visible":true,"children":["rseg_3dmvz6lp6898kdmr"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[0.25,0,-9.75],"rotation":0},"roof_n2d4t91csyoe63oc":{"id":"roof_n2d4t91csyoe63oc","name":"Roof 28","type":"roof","object":"node","visible":true,"children":["rseg_ftnwtmd17tbij1wu"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[13.25,0,-7],"rotation":0},"roof_n9ce4tnnpfcm2ak9":{"id":"roof_n9ce4tnnpfcm2ak9","name":"Roof 23","type":"roof","object":"node","visible":true,"children":["rseg_4eny1djhv4xmgkj1"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-10.75,0,7.5],"rotation":0},"roof_oy5wu0vekqdxgigf":{"id":"roof_oy5wu0vekqdxgigf","name":"Roof 8","type":"roof","object":"node","visible":true,"children":["rseg_4nryt723k27rzus7"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-0.5,0,-4],"rotation":0},"roof_uam7w7hfhuemgolb":{"id":"roof_uam7w7hfhuemgolb","name":"Roof 21","type":"roof","object":"node","visible":true,"children":["rseg_9r5s9mudanssugpu"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-12.25,0,-4.5],"rotation":0},"roof_utu4r0g4k97b3tqq":{"id":"roof_utu4r0g4k97b3tqq","name":"Roof 14","type":"roof","object":"node","visible":true,"children":["rseg_r264ln4hdi9s09wj"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-16,0,-1],"rotation":0},"roof_uxedomh4y0oyomrp":{"id":"roof_uxedomh4y0oyomrp","name":"Roof 23","type":"roof","object":"node","visible":true,"children":["rseg_z0r53255b4rb9s4r"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-11.75,0,-9.75],"rotation":0},"roof_vvcgpqscthisxuhu":{"id":"roof_vvcgpqscthisxuhu","name":"Roof 12","type":"roof","object":"node","visible":true,"children":["rseg_gc6ypptmjhvr1dqy"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-18.75,0,-4.25],"rotation":0},"roof_vwen3bpj3gjqlk7f":{"id":"roof_vwen3bpj3gjqlk7f","name":"Roof 30","type":"roof","object":"node","visible":true,"children":[],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-17,0,5.75],"rotation":0},"roof_w36mcr69xg1wdaox":{"id":"roof_w36mcr69xg1wdaox","name":"Roof 28","type":"roof","object":"node","visible":true,"children":["rseg_yfv1mrrxvop983x3"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[9.25,0,-6.25],"rotation":0},"roof_xnp2fmv9194sv5bv":{"id":"roof_xnp2fmv9194sv5bv","name":"Roof 19","type":"roof","object":"node","visible":true,"children":["rseg_e7ftfn8l6xbdz4j5"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[-4,0,11.25],"rotation":0},"roof_z1i58d6e60oeb7dw":{"id":"roof_z1i58d6e60oeb7dw","name":"Roof 1","type":"roof","object":"node","visible":true,"children":["rseg_8nlt7y8fs1jtextk"],"metadata":{},"parentId":"level_zoigq4mixumm1k6t","position":[8,0,5.75],"rotation":0},"rseg_3dmvz6lp6898kdmr":{"id":"rseg_3dmvz6lp6898kdmr","type":"roof-segment","depth":5.5,"pitch":40,"width":3.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_l8novz1nm4f87uwg","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_4eny1djhv4xmgkj1":{"id":"rseg_4eny1djhv4xmgkj1","type":"roof-segment","depth":13,"pitch":40,"width":4.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_n9ce4tnnpfcm2ak9","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_4hrj8mu5olcsm9ty":{"id":"rseg_4hrj8mu5olcsm9ty","type":"roof-segment","depth":1,"pitch":40,"width":2.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_igb1vv7574i5lvqq","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_4nryt723k27rzus7":{"id":"rseg_4nryt723k27rzus7","type":"roof-segment","depth":6,"pitch":40,"width":2,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_oy5wu0vekqdxgigf","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_8nlt7y8fs1jtextk":{"id":"rseg_8nlt7y8fs1jtextk","type":"roof-segment","depth":22.5,"pitch":40,"width":8,"object":"node","visible":true,"children":["solarpanel_otkgl1d0sv2wfgqq","solarpanel_3f1pjkda065ol6u1","solarpanel_s5kqzi4eq1wxuka1","solarpanel_vkkov9mbny93e8wn","solarpanel_tkn7tdnkpumt0oo3","solarpanel_shim3qipejj18p9a","solarpanel_p56gklaauhob6wel","solarpanel_6q278690k162lil6"],"metadata":{},"overhang":0,"parentId":"roof_z1i58d6e60oeb7dw","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_9r5s9mudanssugpu":{"id":"rseg_9r5s9mudanssugpu","type":"roof-segment","depth":3,"pitch":40,"width":1.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_uam7w7hfhuemgolb","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_afrfkpvhg38camgr":{"id":"rseg_afrfkpvhg38camgr","type":"roof-segment","depth":23.5,"pitch":40,"width":3.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_2gl2hghodp541yw9","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_bani5h96ni5ziui1":{"id":"rseg_bani5h96ni5ziui1","type":"roof-segment","depth":5,"pitch":40,"width":1,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_b5t2vadph3339fj1","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_bocdxxx7uk7q3gxb":{"id":"rseg_bocdxxx7uk7q3gxb","type":"roof-segment","depth":5.5,"pitch":40,"width":11,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_6gxvkkt81ntnp0h4","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_cvz682eh4kr70w72":{"id":"rseg_cvz682eh4kr70w72","type":"roof-segment","depth":9.5,"pitch":40,"width":4,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_4c9z960oiy9mvtd0","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_di5vviiqou7jd8w7":{"id":"rseg_di5vviiqou7jd8w7","type":"roof-segment","depth":3,"pitch":40,"width":10,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_fjutdcwgvmaxx6tu","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_e7ftfn8l6xbdz4j5":{"id":"rseg_e7ftfn8l6xbdz4j5","type":"roof-segment","depth":5.5,"pitch":40,"width":9,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_xnp2fmv9194sv5bv","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_ftnwtmd17tbij1wu":{"id":"rseg_ftnwtmd17tbij1wu","type":"roof-segment","depth":5.5,"pitch":40,"width":1,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_n2d4t91csyoe63oc","position":[0,0,-2.75],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_fu5znxakqkr4illb":{"id":"rseg_fu5znxakqkr4illb","type":"roof-segment","depth":5,"pitch":40,"width":2,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_k4weorepgkerrkue","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_gc6ypptmjhvr1dqy":{"id":"rseg_gc6ypptmjhvr1dqy","type":"roof-segment","depth":2.5,"pitch":40,"width":3.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_vvcgpqscthisxuhu","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_izrb0u0dd9bzoqsl":{"id":"rseg_izrb0u0dd9bzoqsl","type":"roof-segment","depth":1,"pitch":40,"width":8,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_5ai324c2mm4g9oe9","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_k23o2ih8wfn5b0ic":{"id":"rseg_k23o2ih8wfn5b0ic","type":"roof-segment","depth":8.5,"pitch":40,"width":10,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_f3uny9sfzkuju5wo","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_lvtc0446u3nffgxd":{"id":"rseg_lvtc0446u3nffgxd","type":"roof-segment","depth":1,"pitch":40,"width":2,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_c3wrxwv3tv2eog7q","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_mgm797va9dpyku7m":{"id":"rseg_mgm797va9dpyku7m","type":"roof-segment","depth":1.5,"pitch":40,"width":4,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_6fs144kokuw3d66o","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_nuh3hvdww3gglo4d":{"id":"rseg_nuh3hvdww3gglo4d","type":"roof-segment","depth":2,"pitch":40,"width":3,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_18wafaxjhnk09d57","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_o0efrwa15nevfhcd":{"id":"rseg_o0efrwa15nevfhcd","type":"roof-segment","depth":4,"pitch":40,"width":11.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_iw0d29jyd8h3ug2h","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_qlcqbzy4j2opbyo9":{"id":"rseg_qlcqbzy4j2opbyo9","type":"roof-segment","depth":16.5,"pitch":40,"width":7.5,"object":"node","visible":true,"children":["skylight_36wy74anvdb0xb2p","skylight_zhxpo0yigowyfsko","skylight_3vpiv265w9yaq8be","skylight_zng4bb9bg0091xpz","skylight_995tecbx7np1uv6c","skylight_xzln5dzu6lhnn959"],"metadata":{},"overhang":0,"parentId":"roof_ja24y37qth8r8z5k","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_r264ln4hdi9s09wj":{"id":"rseg_r264ln4hdi9s09wj","type":"roof-segment","depth":4,"pitch":40,"width":9,"object":"node","visible":true,"children":["skylight_kzgptzbm0ekqto5c"],"metadata":{},"overhang":0,"parentId":"roof_utu4r0g4k97b3tqq","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_rf924f04g6ixruoi":{"id":"rseg_rf924f04g6ixruoi","type":"roof-segment","depth":5.5,"pitch":40,"width":2.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_daipbvbrid886o9d","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_xbmtr7zm4chleq6e":{"id":"rseg_xbmtr7zm4chleq6e","type":"roof-segment","depth":1,"pitch":40,"width":7.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_14zvu2n2u6yg8o05","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_yfv1mrrxvop983x3":{"id":"rseg_yfv1mrrxvop983x3","type":"roof-segment","depth":1.5,"pitch":40,"width":2.5,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_w36mcr69xg1wdaox","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_ysf1cnf72psu34wz":{"id":"rseg_ysf1cnf72psu34wz","type":"roof-segment","depth":1.5,"pitch":40,"width":4,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_58fhgyatlj0739cq","position":[0,2,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"rseg_z0r53255b4rb9s4r":{"id":"rseg_z0r53255b4rb9s4r","type":"roof-segment","depth":7.5,"pitch":40,"width":1,"object":"node","visible":true,"children":[],"metadata":{},"overhang":0,"parentId":"roof_uxedomh4y0oyomrp","position":[0,0,0],"roofType":"flat","rotation":0,"wallHeight":0,"deckThickness":0.1,"wallThickness":0.1,"shingleThickness":0.05},"site_v2fm4xz80l64fezb":{"id":"site_v2fm4xz80l64fezb","type":"site","object":"node","polygon":{"type":"polygon","points":[[-23,-15],[15,-15],[18,21],[-23,18]]},"visible":true,"children":["building_0cuqp4cgakwi0z90"],"metadata":{},"parentId":null},"slab_14xupespfhxy81q6":{"id":"slab_14xupespfhxy81q6","name":"Slab 35","type":"slab","holes":[],"object":"node","polygon":[[-3,-0.5],[-5,-0.5],[-5,-2],[-3,-2]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_1hptmowf5nxohdwz":{"id":"slab_1hptmowf5nxohdwz","name":"Slab 40","type":"slab","holes":[],"object":"node","polygon":[[11.5,14.5],[12,14.5],[12,12.5],[11.5,12.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_2flcl86fygpphdd3":{"id":"slab_2flcl86fygpphdd3","name":"Room 31 Slab","type":"slab","holes":[],"object":"node","polygon":[[-16,-1.3],[-16,-3],[-13,-3],[-13,-1.3]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true,"materialPreset":"library:preset-glass"},"slab_2gzyh5gpavanhg47":{"id":"slab_2gzyh5gpavanhg47","name":"Slab 17","type":"slab","holes":[],"object":"node","polygon":[[11,7],[11,17.5],[-11.05826859045505,17.399001109877915],[-11,10],[-5.5,10],[-5.5,9],[-0.5,9],[-0.5,10],[3.5,10],[3.5,5.5],[11,5.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_4rctvmu1lht5edsb":{"id":"slab_4rctvmu1lht5edsb","name":"Slab 26","type":"slab","holes":[],"object":"node","polygon":[[0,7.5],[-8,7.5],[-8,-0.5],[0,-0.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_4w2maucrcekoyacr":{"id":"slab_4w2maucrcekoyacr","name":"Room 52 Slab","type":"slab","holes":[],"object":"node","polygon":[[-19,-3],[-16,-3],[-16,-1.3],[-13,-1.3],[-13,1],[-19,1]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true},"slab_4xs0oggyfd6zlw1y":{"id":"slab_4xs0oggyfd6zlw1y","name":"Room 50 Slab","type":"slab","holes":[],"object":"node","polygon":[[-1.5,-10.5],[-1.5,-8.5],[-3,-8.5],[-3,-10.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_5hq9gnnvv685w0iy":{"id":"slab_5hq9gnnvv685w0iy","name":"Room 44 Slab","type":"slab","holes":[],"object":"node","polygon":[[-16.5,11],[-19,11],[-19,9.5],[-16.5,9.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true,"materialPreset":"library:preset-glass"},"slab_5xc1b6wvrbhbr9ji":{"id":"slab_5xc1b6wvrbhbr9ji","name":"Room 41 Slab","type":"slab","holes":[],"object":"node","polygon":[[-16.5,12.5],[-16.5,11],[-13,11],[-13,12.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_67ch2q19c1r3xr18":{"id":"slab_67ch2q19c1r3xr18","name":"Slab 34","type":"slab","holes":[],"object":"node","polygon":[[1.5,2.5],[0,2.5],[0,4],[1.5,4]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_82b54zlmz2j1rhqz":{"id":"slab_82b54zlmz2j1rhqz","name":"Slab 24","type":"slab","holes":[],"object":"node","polygon":[[-13,-5.5],[-13,14.5],[-11,14.5],[-11,-4],[-11.5,-4],[-11.5,-5.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false,"materialPreset":"library:wall-wood3"},"slab_8r46nvo4jfmetnmh":{"id":"slab_8r46nvo4jfmetnmh","name":"Slab 20","type":"slab","holes":[],"object":"node","polygon":[[13,-7],[13,-15],[2,-15],[2,-7]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_9i2m8wykuazda1bv":{"id":"slab_9i2m8wykuazda1bv","name":"Slab 25","type":"slab","holes":[],"object":"node","polygon":[[-9,-2],[-11,-2],[-11,3],[-9,3]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_9ynn2en10adk037b":{"id":"slab_9ynn2en10adk037b","name":"Room 51 Slab","type":"slab","holes":[],"object":"node","polygon":[[14,2.5],[14,5.5],[11,5.5],[11,2.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_ac4szhj57oo7lek8":{"id":"slab_ac4szhj57oo7lek8","name":"Room 53 Slab","type":"slab","holes":[],"object":"node","polygon":[[-17,-11],[-13,-11],[-13,-3],[-16,-3],[-16,-5.5],[-17,-5.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true},"slab_b0uy5yl6wyyu4ls5":{"id":"slab_b0uy5yl6wyyu4ls5","name":"Slab 23","type":"slab","holes":[],"object":"node","polygon":[[-1.5,-4],[-1.5,-2],[-11,-2],[-11,-4]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_bh542hgiwr5qawh0":{"id":"slab_bh542hgiwr5qawh0","name":"Slab 20","type":"slab","holes":[],"object":"node","polygon":[[11,7],[11,5.5],[13,5.5],[13,7]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false,"materialPreset":"library:preset-glass"},"slab_bxaqzfp98ffiasba":{"id":"slab_bxaqzfp98ffiasba","name":"Room 38 Slab","type":"slab","holes":[],"object":"node","polygon":[[-16,-5.5],[-16,-3],[-20.5,-3],[-20.5,-5.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_bz3tthixrk0bt55b":{"id":"slab_bz3tthixrk0bt55b","name":"Slab 33","type":"slab","holes":[],"object":"node","polygon":[[-2,9],[-2,7.5],[-4,7.5],[-4,9]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_dcbfhyip0m368v0u":{"id":"slab_dcbfhyip0m368v0u","name":"Room 46 Slab","type":"slab","holes":[],"object":"node","polygon":[[-19,6],[-19,4.5],[-16.5,4.5],[-16.5,6]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true,"materialPreset":"library:preset-glass"},"slab_ded5xta3bjfnjsy6":{"id":"slab_ded5xta3bjfnjsy6","name":"Slab 31","type":"slab","holes":[],"object":"node","polygon":[[-4,-12.5],[-4,-13.5],[-11.5,-13.5],[-11.5,-12.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_dyw0a3vk5at1mzmz":{"id":"slab_dyw0a3vk5at1mzmz","name":"Slab 31","type":"slab","holes":[],"object":"node","polygon":[[-13,-11],[-13,-12],[-17,-12],[-17,-11]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_fq9wkbtpstuw7muc":{"id":"slab_fq9wkbtpstuw7muc","name":"Slab 22","type":"slab","holes":[],"object":"node","polygon":[[4,-2],[4,-7],[2,-7],[2,-12],[-1.5,-12],[-1.5,-2],[2,-2],[2,-2]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_gfwn5gg37s4vbaxq":{"id":"slab_gfwn5gg37s4vbaxq","name":"Room 8 Slab","type":"slab","holes":[],"object":"node","polygon":[[-9,5],[-9,10],[-11,10],[-11,5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_gv57hc2h694xl8qy":{"id":"slab_gv57hc2h694xl8qy","name":"Room 49 Slab","type":"slab","holes":[],"object":"node","polygon":[[-1.5,-4],[-11.5,-4],[-11.5,-12.5],[-3,-12.5],[-3,-8.5],[-1.5,-8.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_i19mzr7uliu7ztpx":{"id":"slab_i19mzr7uliu7ztpx","name":"Room 14 Slab","type":"slab","holes":[],"object":"node","polygon":[[6,-3],[4,-3],[4,-5],[6,-5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_i2hr3x3p5rli1yuw":{"id":"slab_i2hr3x3p5rli1yuw","name":"Slab 39","type":"slab","holes":[],"object":"node","polygon":[[11,14.5],[11.5,14.5],[11.5,12.5],[11,12.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.1,"holeMetadata":[],"autoFromWalls":false},"slab_jp2bg9p3tq59l3iu":{"id":"slab_jp2bg9p3tq59l3iu","name":"Room 19 Slab","type":"slab","holes":[],"object":"node","polygon":[[-13,11],[-13,16],[-19,16],[-19,12.5],[-13,12.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true,"materialPreset":"library:wall-wood3"},"slab_knoyu9wqbw08i2e2":{"id":"slab_knoyu9wqbw08i2e2","name":"Slab 32","type":"slab","holes":[],"object":"node","polygon":[[1.5,-2],[4,-2],[4,10],[1.5,10]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_lt6auhuwta9rqsya":{"id":"slab_lt6auhuwta9rqsya","name":"Room 54 Slab","type":"slab","holes":[],"object":"node","polygon":[[-17,-5.5],[-20.5,-5.5],[-20.5,-11],[-17,-11],[-17,-9],[-19,-9],[-19,-5.5],[-19,-9],[-17,-9],[-17,-7.95],[-18,-7.95],[-17,-7.95]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true},"slab_mdd8h5wyitom71yo":{"id":"slab_mdd8h5wyitom71yo","name":"Room 42 Slab","type":"slab","holes":[],"object":"node","polygon":[[-13,6],[-13,9.5],[-19,9.5],[-19,6]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true,"materialPreset":"library:wall-wood3"},"slab_p0slb1ujxa56wgtm":{"id":"slab_p0slb1ujxa56wgtm","name":"Slab 41","type":"slab","holes":[],"object":"node","polygon":[[6.5,1.5],[6.5,5.5],[4,5.5],[4,1.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_p37ex4kfe3khiwlx":{"id":"slab_p37ex4kfe3khiwlx","name":"Room 37 Slab","type":"slab","holes":[],"object":"node","polygon":[[4,-3],[6,-3],[6,-4],[11,-4],[11,5.5],[6.5,5.5],[6.5,1.5],[4,1.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_pgnswibpafl51hdc":{"id":"slab_pgnswibpafl51hdc","name":"Room 43 Slab","type":"slab","holes":[],"object":"node","polygon":[[-16.5,9.5],[-13,9.5],[-13,11],[-16.5,11]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true},"slab_ptxzpw7sfnttfjaf":{"id":"slab_ptxzpw7sfnttfjaf","name":"Room 40 Slab","type":"slab","holes":[],"object":"node","polygon":[[-19,11],[-16.5,11],[-16.5,12.5],[-19,12.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true,"materialPreset":"library:preset-glass"},"slab_q16hxb0n1rpxd8fe":{"id":"slab_q16hxb0n1rpxd8fe","name":"Slab 29","type":"slab","holes":[],"object":"node","polygon":[[-13,17.5],[-20.5,17.5],[-20.5,16],[-13,16]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_uoka5x6c23v8lci7":{"id":"slab_uoka5x6c23v8lci7","name":"Slab 28","type":"slab","holes":[],"object":"node","polygon":[[-19,-3],[-20.5,-3],[-20.5,16],[-19,16]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":false},"slab_we9t2usq1m3s22qk":{"id":"slab_we9t2usq1m3s22qk","name":"Room 22 Slab","type":"slab","holes":[],"object":"node","polygon":[[-13,6],[-13,4.5],[-19,4.5],[-19,1],[-13,1]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.15,"holeMetadata":[],"autoFromWalls":true,"materialPreset":"library:wall-wood3"},"slab_whaas4pjyvbv8e82":{"id":"slab_whaas4pjyvbv8e82","name":"Slab 19","type":"slab","holes":[],"object":"node","polygon":[[8.5,-4],[6,-4],[6,-5],[8.5,-5],[8.5,-7],[10.5,-7],[10.5,-5],[12.021632486590894,-5.000468183672056],[12,1.5],[14,1.5],[14,2.5],[12,2.5],[11,2.5],[11,-4],[10.411379310344827,-4.043448275862069]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_xhc9lp2ez02kb7t1":{"id":"slab_xhc9lp2ez02kb7t1","name":"Room 45 Slab","type":"slab","holes":[],"object":"node","polygon":[[-13,4.5],[-13,6],[-16.5,6],[-16.5,4.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":true},"slab_yzdeb08ot8x1ufg4":{"id":"slab_yzdeb08ot8x1ufg4","name":"Slab 30","type":"slab","holes":[],"object":"node","polygon":[[-11,5],[-8,5],[-8,3],[-11,3]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","elevation":0.05,"holeMetadata":[],"autoFromWalls":false},"wall_09qn8o3fiwtz45wy":{"id":"wall_09qn8o3fiwtz45wy","end":[4,-7],"name":"Wall 35","type":"wall","start":[4,-5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["window_9kyv4l4vkxr77rgn"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_0a3llbsfqmoc5ni2":{"id":"wall_0a3llbsfqmoc5ni2","end":[-19,-5.5],"name":"Wall 5","type":"wall","start":[-19,-9],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_7i68qhc4qnwiqdr2"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_0npbxm44kepovw9e":{"id":"wall_0npbxm44kepovw9e","end":[9.5,14.5],"name":"Wall 115","type":"wall","start":[6,14.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_140trhrqi7eio8qq":{"id":"wall_140trhrqi7eio8qq","end":[-9,-2],"name":"Wall 12","type":"wall","start":[-11,-2],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_1624lf5ywztagcho":{"id":"wall_1624lf5ywztagcho","end":[-19,1],"name":"Wall 5","type":"wall","start":[-19,-3],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_098asmfnvap5du76"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_1aqnio3z2swd7632":{"id":"wall_1aqnio3z2swd7632","end":[6,-3],"name":"Wall 98","type":"wall","start":[4,-3],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_yeqzk2brm4dxbl5w"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_1o0ho2nwpbwjrysh":{"id":"wall_1o0ho2nwpbwjrysh","end":[-16,-1.3],"name":"Wall 104","type":"wall","start":[-16,-3],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_1xhe9ek9ox92k1ad":{"id":"wall_1xhe9ek9ox92k1ad","end":[-13,6],"name":"Wall 104","type":"wall","start":[-13,4.5],"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior"},"wall_23uozapaf4f7vxbu":{"id":"wall_23uozapaf4f7vxbu","end":[-11,14.5],"name":"Wall 20","type":"wall","start":[-11,11.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_3avujhzyb9vrlmiu":{"id":"wall_3avujhzyb9vrlmiu","end":[6,-4],"name":"Wall 34","type":"wall","start":[11,-4],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_3ycwr4olsg7qsbfh","window_z4g0lf5l560qdqbb"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_3wvtfkszvjddhl09":{"id":"wall_3wvtfkszvjddhl09","end":[3.5,-15],"name":"Wall 107","type":"wall","start":[2,-15],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_45hwqbrj4tkr65pc":{"id":"wall_45hwqbrj4tkr65pc","end":[-9,10],"name":"Wall 83","type":"wall","start":[-9,5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["window_c4bw6z49vgxg9b01"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_4avg2h4yzyytqq8q":{"id":"wall_4avg2h4yzyytqq8q","end":[-20.5,-11],"name":"Wall 112","type":"wall","start":[-20.5,-5.5],"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_4d0xw9erem5q4j9h":{"id":"wall_4d0xw9erem5q4j9h","end":[-13,-1.3],"name":"Wall 105","type":"wall","start":[-16,-1.3],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_sqzmuwh0yxiejf5j"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_4htt68qzmhcal2tp":{"id":"wall_4htt68qzmhcal2tp","end":[-13,9.5],"name":"Wall 11","type":"wall","start":[-13,6],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_6408vazt0pvdfvwt"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_511vyjfe86jdpfjc":{"id":"wall_511vyjfe86jdpfjc","end":[-13,14.5],"name":"Wall 11","type":"wall","start":[-13,11],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_zky92rx94vi84jrl"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_57s39vmwxfq5za0l":{"id":"wall_57s39vmwxfq5za0l","end":[2,-11],"name":"Wall 14","type":"wall","start":[2,-7],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["window_wnbj77udzsef7ml8"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_5tpzo3llueskblic":{"id":"wall_5tpzo3llueskblic","end":[-19,4.5],"name":"Wall 5","type":"wall","start":[-19,1],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_kt1o5t8ahsbxz4s6"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_5zo7dm0uvk0pfju5":{"id":"wall_5zo7dm0uvk0pfju5","end":[-19,16],"name":"Wall 4","type":"wall","start":[-13,16],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_f86wqvbzr8m2gdz5"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_67zv71d6hvihz3wd":{"id":"wall_67zv71d6hvihz3wd","end":[-13,1],"name":"Wall 11","type":"wall","start":[-13,-1.3],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_km2yxncnqsnrldvb"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_72lgxbxx4aq5ifxc":{"id":"wall_72lgxbxx4aq5ifxc","end":[14,2.5],"name":"Wall 97","type":"wall","start":[14,5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_ua0lfxygo38djdnp"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_7fy1vx9pydr9xs7n":{"id":"wall_7fy1vx9pydr9xs7n","end":[-1.5,-8.5],"name":"Wall 63","type":"wall","start":[-1.5,-10.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_2zc1fkyldktaa1bi"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_7vlpz9r5adi41efi":{"id":"wall_7vlpz9r5adi41efi","end":[-19,6],"name":"Wall 5","type":"wall","start":[-19,4.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_0ij8i9wxij6vu68d"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_8ufjpww7jx9bsxhp":{"id":"wall_8ufjpww7jx9bsxhp","end":[-13,17.5],"name":"Wall 89","type":"wall","start":[-13,16],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_90uid8e6qurlee1g":{"id":"wall_90uid8e6qurlee1g","end":[-16.5,11],"name":"Wall 105","type":"wall","start":[-19,11],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_9evtpcg2zxspy62d":{"id":"wall_9evtpcg2zxspy62d","end":[-13,6],"name":"Wall 11","type":"wall","start":[-13,1],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_zw4lnwcudh61rwi2"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_9g78aagb3d9xxitr":{"id":"wall_9g78aagb3d9xxitr","end":[2,-7],"name":"Wall 12","type":"wall","start":[4,-7],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["window_7e1ztf1g1bzou5b7"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_9sfj2yc45km30d4h":{"id":"wall_9sfj2yc45km30d4h","end":[-11,16],"name":"Wall 20","type":"wall","start":[-11,14.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_a6zlyi7ogc0getot":{"id":"wall_a6zlyi7ogc0getot","end":[18,21],"name":"Wall 121","type":"wall","start":[15.082758620689654,-14.006896551724138],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_aq63oll1ms4534us":{"id":"wall_aq63oll1ms4534us","end":[-16.5,9.5],"name":"Wall 120","type":"wall","start":[-19,9.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_ax0ct539gmmfq5qh":{"id":"wall_ax0ct539gmmfq5qh","end":[2,-14],"name":"Wall 103","type":"wall","start":[2,-15],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.26},"wall_b2vligz08ucw81tf":{"id":"wall_b2vligz08ucw81tf","end":[14,5.5],"name":"Wall 99","type":"wall","start":[14,5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_bmrz9ke2xmdkvynh":{"id":"wall_bmrz9ke2xmdkvynh","end":[11,7],"name":"Wall 1","type":"wall","start":[11,5.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_85knace7qbiwbeku"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_boqdcq63dglq6j8t":{"id":"wall_boqdcq63dglq6j8t","end":[6,-5],"name":"Wall 107","type":"wall","start":[6,-4],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_bsrv7p9bnpcdn06h":{"id":"wall_bsrv7p9bnpcdn06h","end":[4,1.5],"name":"Wall 19","type":"wall","start":[4,-3],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_6s80mcnw06l8zsd5"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_bxjfrx4xqt15ir57":{"id":"wall_bxjfrx4xqt15ir57","end":[6.5,1.5],"name":"Wall 98","type":"wall","start":[6.5,5.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior"},"wall_ci1zeo5trejkbdkc":{"id":"wall_ci1zeo5trejkbdkc","end":[-11,14.5],"name":"Wall 103","type":"wall","start":[-13,14.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["window_zwxyh3sl3qpokzcc"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_ckjbkszhejacwysj":{"id":"wall_ckjbkszhejacwysj","end":[-16,-3],"name":"Wall 105","type":"wall","start":[-16,-5.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_003q2dafgqidsdxm"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_dazxo798ki8pgnff":{"id":"wall_dazxo798ki8pgnff","end":[13,-7],"name":"Wall 31","type":"wall","start":[13,-12],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["item_cmrx8hp4jc508xhi"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_ddo4m0zdpr61yl79":{"id":"wall_ddo4m0zdpr61yl79","end":[-16.5,12.5],"name":"Wall 47","type":"wall","start":[-19,12.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_dqq567z069dtz3tv":{"id":"wall_dqq567z069dtz3tv","end":[-1.5,-8.5],"name":"Wall 127","type":"wall","start":[-3,-8.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_e70i2pt14fipf7f9":{"id":"wall_e70i2pt14fipf7f9","end":[4,-5],"name":"Wall 34","type":"wall","start":[6,-5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_5zjdjzx59g2kmzfd"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_eoyrn00w7x0htu9w":{"id":"wall_eoyrn00w7x0htu9w","end":[-13,-11],"name":"Wall 14","type":"wall","start":[-17,-11],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_zgu2bjq7cgqmhl01"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_ey2wdo1kqv0x23ma":{"id":"wall_ey2wdo1kqv0x23ma","end":[-11.5,-11],"name":"Wall 67","type":"wall","start":[-11.5,-5.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_kevahot70au3ckwp"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_ezu11zocogdbtuht":{"id":"wall_ezu11zocogdbtuht","end":[-9,-2],"name":"Wall 86","type":"wall","start":[-9,3],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_7c3ahr05ob2flmo4"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_f2f7ztggiy1sqbj6":{"id":"wall_f2f7ztggiy1sqbj6","end":[-20.5,-5.5],"name":"Wall 114","type":"wall","start":[-20.5,-3],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["window_86ahb5wo9wbup3z4"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_f2npta6ui1n3x8nb":{"id":"wall_f2npta6ui1n3x8nb","end":[-20.5,-11],"name":"Wall 114","type":"wall","start":[-19,-11],"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_f7893lho24ex55pj":{"id":"wall_f7893lho24ex55pj","end":[-19,12.5],"name":"Wall 5","type":"wall","start":[-19,11],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_bhnz7yv89tof7yz9"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_fc0yo78bjook97f6":{"id":"wall_fc0yo78bjook97f6","end":[-19,11],"name":"Wall 5","type":"wall","start":[-19,9.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_kx6wlvpiz2r0lopt"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_fixqs7rz4ejb9wl9":{"id":"wall_fixqs7rz4ejb9wl9","end":[-11.5,-11],"name":"Wall 98","type":"wall","start":[-11.5,-12.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_fpizzvyeydc1tgwv":{"id":"wall_fpizzvyeydc1tgwv","end":[6.5,5.5],"name":"Wall 99","type":"wall","start":[11,5.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_ljuf16e8ozkdtu8p"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_free8uwwxdtfpsm0":{"id":"wall_free8uwwxdtfpsm0","end":[-23,-14.5],"name":"Wall 106","type":"wall","start":[-2,-14.5],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_g2i3cozy8i3s9xns":{"id":"wall_g2i3cozy8i3s9xns","end":[-19,6],"name":"Wall 40","type":"wall","start":[-16.5,6],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_hclslg87nmmrzhy2":{"id":"wall_hclslg87nmmrzhy2","end":[-13,4.5],"name":"Wall 99","type":"wall","start":[-16.5,4.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_g8lx3x486pbrvlp8"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_hervqjln3nui1iwa":{"id":"wall_hervqjln3nui1iwa","end":[-23,18],"name":"Wall 122","type":"wall","start":[18,21],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_hiwy7wvffuz8py7s":{"id":"wall_hiwy7wvffuz8py7s","end":[-20.5,6],"name":"Wall 57","type":"wall","start":[-19,6],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_hkzv1k6d6qowpoac":{"id":"wall_hkzv1k6d6qowpoac","end":[-3,-12.5],"name":"Wall 124","type":"wall","start":[-4,-12.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_hur4i86ycgdti8mz":{"id":"wall_hur4i86ycgdti8mz","end":[14,5.5],"name":"Wall 96","type":"wall","start":[13,5.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_il3k30g2f3sv1rcm":{"id":"wall_il3k30g2f3sv1rcm","end":[-16.5,11],"name":"Wall 116","type":"wall","start":[-16.5,12.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_ddapl8ziz3p7cxqo"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_j06as20cdjshont3":{"id":"wall_j06as20cdjshont3","end":[-17,-9],"name":"Wall 115","type":"wall","start":[-19,-9],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_yp2pr1gco66644fz"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_jhq14ndqldmq9vf8":{"id":"wall_jhq14ndqldmq9vf8","end":[14,2.5],"name":"Wall 98","type":"wall","start":[11,2.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_az7819jvqmsl3sov"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_jj1ptn150ypxrz01":{"id":"wall_jj1ptn150ypxrz01","end":[-23,-14.5],"name":"Wall 123","type":"wall","start":[-23,18],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_k4mh2k5sty71ixll":{"id":"wall_k4mh2k5sty71ixll","end":[-2,-14.5],"name":"Wall 105","type":"wall","start":[-2,-14],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_kcfxabt0e2b3wusf":{"id":"wall_kcfxabt0e2b3wusf","end":[-9,5],"name":"Wall 82","type":"wall","start":[-11,5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_ktqckft5foyfjhyh":{"id":"wall_ktqckft5foyfjhyh","end":[13,5.5],"name":"Wall 117","type":"wall","start":[13,7],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_65h7hrxtu4uwau9l"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_kvotvn6k2je8hv9l":{"id":"wall_kvotvn6k2je8hv9l","end":[-13,16],"name":"Wall 11","type":"wall","start":[-13,14.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["window_ealysksymsw3mvev"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_kvqihqe5d9n9g0oc":{"id":"wall_kvqihqe5d9n9g0oc","end":[11,2.5],"name":"Wall 1","type":"wall","start":[11,-4],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["window_3ck01pusx7nppzmw"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_laxcblwuvhm3ijs7":{"id":"wall_laxcblwuvhm3ijs7","end":[-19,9.5],"name":"Wall 5","type":"wall","start":[-19,6],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_1iqbwl5ljsok5qta"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_lbygbccrx2zapwc9":{"id":"wall_lbygbccrx2zapwc9","end":[4,1.5],"name":"Wall 100","type":"wall","start":[6.5,1.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["item_gnmwdolg7xbhapzd","item_b5i0u6wmn8ez0cak","item_phyf3kvw72q20sj9","item_jwird8y6e9juvm2l","item_hle7coq8741fo7a6"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior"},"wall_lea2gxc27puc3n9z":{"id":"wall_lea2gxc27puc3n9z","end":[-9,3],"name":"Wall 85","type":"wall","start":[-11,3],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_lgairsceyw874vwo":{"id":"wall_lgairsceyw874vwo","end":[-1.5,-4],"name":"Wall 95","type":"wall","start":[-1.5,-8.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_32vilzg1z4ly2fre"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_lhk47afoeymdpvwr":{"id":"wall_lhk47afoeymdpvwr","end":[4,-3],"name":"Wall 19","type":"wall","start":[4,-5],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_lqvpfuyzau9fzkgs":{"id":"wall_lqvpfuyzau9fzkgs","end":[-13,-11],"name":"Wall 67","type":"wall","start":[-13,-3],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_t9x3t14wzyfkap1h","door_2rz0zywfxpqi95qs"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_m1mxa7gvkcuw886t":{"id":"wall_m1mxa7gvkcuw886t","end":[4,10],"name":"Wall 14","type":"wall","start":[-9,10],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_bn0us8dya3g22tiq","door_l2cqtt89tgiyqcfh","door_ylobpafj247i70r2","door_rf0h0gnvtied4uun"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_mco0e8drg9r99eqv":{"id":"wall_mco0e8drg9r99eqv","end":[-3,-9.5],"name":"Wall 128","type":"wall","start":[-3,-8.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_mh6fum5rekj6s07d":{"id":"wall_mh6fum5rekj6s07d","end":[-3,-10.5],"name":"Wall 66","type":"wall","start":[-3,-9.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_mqosy280yms4dcyl":{"id":"wall_mqosy280yms4dcyl","end":[11,5.5],"name":"Wall 95","type":"wall","start":[11,2.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_m70glk1wsdlx6sol"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_mukwta285d1nayjp":{"id":"wall_mukwta285d1nayjp","end":[-13,-1.3],"name":"Wall 11","type":"wall","start":[-13,-3],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_n08yiceoh4qtei2j":{"id":"wall_n08yiceoh4qtei2j","end":[-20.5,1],"name":"Wall 108","type":"wall","start":[-19,1],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_nhk4k0cpxwaya1fj":{"id":"wall_nhk4k0cpxwaya1fj","end":[-11,10],"name":"Wall 14","type":"wall","start":[-9,10],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_njazeipo5u7emoju":{"id":"wall_njazeipo5u7emoju","end":[-6,11.5],"name":"Wall 105","type":"wall","start":[-6,16],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_nmid5oq2vtlxthxz":{"id":"wall_nmid5oq2vtlxthxz","end":[-17,-11],"name":"Wall 14","type":"wall","start":[-19,-11],"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_nnj3nxr3v1h0y65p":{"id":"wall_nnj3nxr3v1h0y65p","end":[-13,11],"name":"Wall 105","type":"wall","start":[-13,12.5],"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_o29gc9a26conmttb":{"id":"wall_o29gc9a26conmttb","end":[-13,-3],"name":"Wall 103","type":"wall","start":[-16,-3],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_o3sipgjqvlmla2jt":{"id":"wall_o3sipgjqvlmla2jt","end":[-11,-4],"name":"Wall 81","type":"wall","start":[-11,3],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_iwdjzs7yvb7fxpn9","door_9qpgluas28n0yi3v"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_omc5jlwqm2leepuz":{"id":"wall_omc5jlwqm2leepuz","end":[-1.5,-11],"name":"Wall 124","type":"wall","start":[2,-11],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_d4c5c1cpbszxqjnu"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_op0omao9jequusd0":{"id":"wall_op0omao9jequusd0","end":[6,-4],"name":"Wall 100","type":"wall","start":[6,-3],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_p6up981dq7o6keek":{"id":"wall_p6up981dq7o6keek","end":[-13,12.5],"name":"Wall 47","type":"wall","start":[-16.5,12.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_i3br065zzqiophqr"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_pj6yfijswry56gho":{"id":"wall_pj6yfijswry56gho","end":[13,7],"name":"Wall 115","type":"wall","start":[11,7],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_poe9onw07jpxc34z":{"id":"wall_poe9onw07jpxc34z","end":[4,16],"name":"Wall 27","type":"wall","start":[-6,16],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_m5dzsciqatw5hyea","door_11h3hkmf2y1a4qej","door_aykqs6emre4sxdh3"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_pszoe902uvgt1yqu":{"id":"wall_pszoe902uvgt1yqu","end":[-13,9.5],"name":"Wall 120","type":"wall","start":[-16.5,9.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_pww6nwv9h1sup14v"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_ptnfpltgh4e4c85b":{"id":"wall_ptnfpltgh4e4c85b","end":[-16.5,4.5],"name":"Wall 123","type":"wall","start":[-16.5,6],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_612bryuuuvncueq4"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_q21eg7ipg0lfmdfc":{"id":"wall_q21eg7ipg0lfmdfc","end":[-1.5,-10.5],"name":"Wall 125","type":"wall","start":[-1.5,-11],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3,"curveOffset":0},"wall_qbipm5170ddx1anr":{"id":"wall_qbipm5170ddx1anr","end":[-20.5,-3],"name":"Wall 109","type":"wall","start":[-19,-3],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_qh3ahacsxna8akmo":{"id":"wall_qh3ahacsxna8akmo","end":[-14,-5.5],"name":"Wall 102","type":"wall","start":[-11.5,-5.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["window_m9oe04rx8mtddlu6"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_rq0pzcyto5oukci6":{"id":"wall_rq0pzcyto5oukci6","end":[-16,-3],"name":"Wall 103","type":"wall","start":[-19,-3],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.25},"wall_rsabhuiuzuei6t14":{"id":"wall_rsabhuiuzuei6t14","end":[4,5.5],"name":"Wall 99","type":"wall","start":[6.5,5.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_rsm36dul3l6ue60h":{"id":"wall_rsm36dul3l6ue60h","end":[4,2.5],"name":"Wall 19","type":"wall","start":[4,1.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_0gb3txrhcva9eggd"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_scjpkore2sqkklqv":{"id":"wall_scjpkore2sqkklqv","end":[-13,1],"name":"Wall 96","type":"wall","start":[-19,1],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_suoqjtukn48pfuw7":{"id":"wall_suoqjtukn48pfuw7","end":[-17,-9],"name":"Wall 87","type":"wall","start":[-17,-11],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.25},"wall_te3u345qtohv9vjo":{"id":"wall_te3u345qtohv9vjo","end":[-11,5],"name":"Wall 118","type":"wall","start":[-11,3],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_n4poiow1o0jpmnmz"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_tebqur8nrk74nmnt":{"id":"wall_tebqur8nrk74nmnt","end":[-16.5,4.5],"name":"Wall 99","type":"wall","start":[-19,4.5],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_tf4qyoz9ekfozccj":{"id":"wall_tf4qyoz9ekfozccj","end":[-6,16],"name":"Wall 27","type":"wall","start":[-11,16],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_fadth0vp9x8flk9k"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_tp7o7mn70e2xwk85":{"id":"wall_tp7o7mn70e2xwk85","end":[-13,11],"name":"Wall 11","type":"wall","start":[-13,9.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_twloychxtm3ec706":{"id":"wall_twloychxtm3ec706","end":[4,10],"name":"Wall 19","type":"wall","start":[4,2.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_0tk51z11kqyiud4w","door_7br7dnqy0mlkibdo"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_tymqcjozlz0wbr3b":{"id":"wall_tymqcjozlz0wbr3b","end":[-17,-5.5],"name":"Wall 87","type":"wall","start":[-17,-7.95],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.25},"wall_u159rpl5ey25g893":{"id":"wall_u159rpl5ey25g893","end":[-16,-5.5],"name":"Wall 102","type":"wall","start":[-17,-5.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_u2vdle19v0ql3ej9":{"id":"wall_u2vdle19v0ql3ej9","end":[-16.5,6],"name":"Wall 40","type":"wall","start":[-13,6],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_uhqtl0rapbnfigqy":{"id":"wall_uhqtl0rapbnfigqy","end":[-11,5],"name":"Wall 80","type":"wall","start":[-11,10],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_wtguwf95s0e94wum"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_v3sr07iaeh1v7hnn":{"id":"wall_v3sr07iaeh1v7hnn","end":[-20.5,11],"name":"Wall 107","type":"wall","start":[-19,11],"height":3,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_v8v45xnlfyyc7ep0":{"id":"wall_v8v45xnlfyyc7ep0","end":[-17,-5.5],"name":"Wall 115","type":"wall","start":[-20.5,-5.5],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_ag0mssudth9a2afy","window_drbs0ipvpb9ksir3"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior"},"wall_vg3bosm6qyt1c25z":{"id":"wall_vg3bosm6qyt1c25z","end":[-16.5,9.5],"name":"Wall 122","type":"wall","start":[-16.5,11],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_dy7nkrp6gpf3wnvc"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_vgfztgld1iyz03hs":{"id":"wall_vgfztgld1iyz03hs","end":[-11.5,-12.5],"name":"Wall 97","type":"wall","start":[-4,-12.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_95d7hz9dhied8n19","door_79e5m56hrbai0wq7"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_vp4awhvgp3deoth1":{"id":"wall_vp4awhvgp3deoth1","end":[12.5,-15],"name":"Wall 120","type":"wall","start":[13,-15],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"wall_vu3f0nwh6q4biyml":{"id":"wall_vu3f0nwh6q4biyml","end":[4,16],"name":"Wall 91","type":"wall","start":[4,10],"height":3,"object":"node","visible":true,"backSide":"unknown","children":["door_hs4mkfaaqx4qksko","door_ttkair3f0ki8ltgz"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.3},"wall_vv46t743yzjkp75d":{"id":"wall_vv46t743yzjkp75d","end":[-11.5,-4],"name":"Wall 96","type":"wall","start":[-1.5,-4],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_kb75sajdh4bogo6x","door_i9aw62hd7baa4j86"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_x1kh2wmgiel4bmfj":{"id":"wall_x1kh2wmgiel4bmfj","end":[13,5.5],"name":"Wall 96","type":"wall","start":[11,5.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior"},"wall_xbfj7l13705yb4al":{"id":"wall_xbfj7l13705yb4al","end":[-18,-7.95],"name":"Wall 127","type":"wall","start":[-17,-7.95],"height":1.2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_xdybfyjhn6p9ucq7":{"id":"wall_xdybfyjhn6p9ucq7","end":[3.5,-15],"name":"Wall 107","type":"wall","start":[2,-15],"height":2,"object":"node","visible":true,"backSide":"unknown","children":[],"metadata":{"isNew":true},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown"},"wall_xttll6vqda9pv1ub":{"id":"wall_xttll6vqda9pv1ub","end":[-17,-7.95],"name":"Wall 87","type":"wall","start":[-17,-9],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.25},"wall_xz7iwgol1ji7w4pz":{"id":"wall_xz7iwgol1ji7w4pz","end":[-3,-10.5],"name":"Wall 127","type":"wall","start":[-1.5,-10.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["window_wh8lydfblsw15mpa"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_ya9meea2cq3u4xep":{"id":"wall_ya9meea2cq3u4xep","end":[-13,11],"name":"Wall 105","type":"wall","start":[-16.5,11],"height":3,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_yjq6lrhge7g81kkh":{"id":"wall_yjq6lrhge7g81kkh","end":[13,-15],"name":"Wall 127","type":"wall","start":[13,-14],"height":2,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_yrmx4yncojhot61j":{"id":"wall_yrmx4yncojhot61j","end":[-3,-12.5],"name":"Wall 66","type":"wall","start":[-3,-10.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_zb9zn4p8rteb2uql":{"id":"wall_zb9zn4p8rteb2uql","end":[-19,16],"name":"Wall 5","type":"wall","start":[-19,12.5],"height":3,"object":"node","visible":true,"backSide":"interior","children":["door_qo008zrogf9rk1mc"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"exterior","thickness":0.3},"wall_zcla9q6jevq75eh8":{"id":"wall_zcla9q6jevq75eh8","end":[13,-14],"name":"Wall 125","type":"wall","start":[15.082758620689654,-14.006896551724138],"height":2,"object":"node","visible":true,"backSide":"exterior","children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.25},"wall_zmwbk6swgebpykct":{"id":"wall_zmwbk6swgebpykct","end":[-11.5,-5.5],"name":"Wall 67","type":"wall","start":[-11.5,-4],"height":3,"object":"node","visible":true,"backSide":"exterior","children":["door_ozmzbgp2e6ezap47"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"interior","thickness":0.3},"wall_zovp1qu83cbgn2u9":{"id":"wall_zovp1qu83cbgn2u9","end":[-2,-14],"name":"Wall 104","type":"wall","start":[2,-14],"height":2,"object":"node","visible":true,"backSide":"unknown","children":["door_yf7b3k1ogsdfpoe2"],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","frontSide":"unknown","thickness":0.25},"zone_0fsedoxyxx793l1z":{"id":"zone_0fsedoxyxx793l1z","name":"Room A","type":"zone","color":"#3b82f6","object":"node","polygon":[[4,5.5],[4,17.5],[11,17.5],[11,5.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_3be32bohno92xs9a":{"id":"zone_3be32bohno92xs9a","name":"Room B","type":"zone","color":"#3b82f6","object":"node","polygon":[[-19,11],[-19,6],[-13,6],[-13,11]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_4enmz21dobmb6syx":{"id":"zone_4enmz21dobmb6syx","name":"Room C","type":"zone","color":"#3b82f6","object":"node","polygon":[[-11,3],[-9,3],[-9,-2],[-11,-2]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_9h2q65itdkpkpedg":{"id":"zone_9h2q65itdkpkpedg","name":"Room D","type":"zone","color":"#3b82f6","object":"node","polygon":[[4,5.5],[6.5,5.5],[6.5,1.5],[4,1.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_arusgjyzhqflpn8a":{"id":"zone_arusgjyzhqflpn8a","name":"Room E","type":"zone","color":"#3b82f6","object":"node","polygon":[[-6,16],[-6,10],[4,10],[4,16]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_aujjt6sq7p45kl72":{"id":"zone_aujjt6sq7p45kl72","name":"Room F","type":"zone","color":"#3b82f6","object":"node","polygon":[[4,-3],[4,-5],[6,-5],[6,-3]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_cpxr02vol9zmutv4":{"id":"zone_cpxr02vol9zmutv4","name":"Room G","type":"zone","color":"#3b82f6","object":"node","polygon":[[-13,-3],[-13,-11],[-20.5,-11],[-20.5,-3]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_dxhvxhl04b7towyq":{"id":"zone_dxhvxhl04b7towyq","name":"Room H","type":"zone","color":"#3b82f6","object":"node","polygon":[[11,-4],[11,5.5],[6.5,5.5],[6.5,1.5],[4,1.5],[4,-3],[6,-3],[6,-4]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_glzsnj67sedhx3sy":{"id":"zone_glzsnj67sedhx3sy","name":"Room I","type":"zone","color":"#3b82f6","object":"node","polygon":[[-11,10],[-11,16],[-6,16],[-6,10]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_jb4l1cwqnwslq6tr":{"id":"zone_jb4l1cwqnwslq6tr","name":"Room J","type":"zone","color":"#3b82f6","object":"node","polygon":[[-19,6],[-19,1],[-13,1],[-13,6]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_jra72agx2ybpsofn":{"id":"zone_jra72agx2ybpsofn","name":"Room K","type":"zone","color":"#3b82f6","object":"node","polygon":[[-11,10],[-9,10],[-9,5],[-11,5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_keikusorpa0974ln":{"id":"zone_keikusorpa0974ln","name":"Room L","type":"zone","color":"#3b82f6","object":"node","polygon":[[-13,16],[-19,16],[-19,11],[-13,11]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_mnf35gnjfxirqhqr":{"id":"zone_mnf35gnjfxirqhqr","name":"Room M","type":"zone","color":"#3b82f6","object":"node","polygon":[[13,-7],[2,-7],[2,-15],[13,-15]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_n2k001mmc4dm93ow":{"id":"zone_n2k001mmc4dm93ow","name":"Room N","type":"zone","color":"#3b82f6","object":"node","polygon":[[4,10],[-9,10],[-9,-2],[-11,-2],[-11,-4],[-1.5,-4],[-1.5,-7],[4,-7]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_p1vz7o7e8a81pye5":{"id":"zone_p1vz7o7e8a81pye5","name":"Room O","type":"zone","color":"#3b82f6","object":"node","polygon":[[11,7],[13,7],[13,5.5],[11,5.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_uhf0e393u8f04e7a":{"id":"zone_uhf0e393u8f04e7a","name":"Room P","type":"zone","color":"#3b82f6","object":"node","polygon":[[-1.5,-8.5],[-1.5,-10.5],[-3,-10.5],[-3,-8.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_vhi7rtdz2eagnf7z":{"id":"zone_vhi7rtdz2eagnf7z","name":"Room Q","type":"zone","color":"#3b82f6","object":"node","polygon":[[-1.5,-8.5],[-1.5,-4],[-11.5,-4],[-11.5,-12.5],[-3,-12.5],[-3,-8.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_w7i3wwyswt8t1kvj":{"id":"zone_w7i3wwyswt8t1kvj","name":"Room R","type":"zone","color":"#3b82f6","object":"node","polygon":[[11,5.5],[14,5.5],[14,2.5],[11,2.5]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_xmmyfm2x084ipdhc":{"id":"zone_xmmyfm2x084ipdhc","name":"Room S","type":"zone","color":"#3b82f6","object":"node","polygon":[[-19,1],[-19,-3],[-13,-3],[-13,1]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"zone_zsywh4vjl3k3jxxp":{"id":"zone_zsywh4vjl3k3jxxp","name":"Room T","type":"zone","color":"#3b82f6","object":"node","polygon":[[2,-7],[-1.5,-7],[-1.5,-11],[2,-11]],"visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m"},"fence_is7i5npo2cl001j7":{"id":"fence_is7i5npo2cl001j7","end":[3.5,-15],"name":"Fence 1","type":"fence","color":"#ffffff","start":[12.5,-15],"style":"privacy","height":2,"object":"node","visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","postSize":0.1,"baseStyle":"grounded","edgeInset":0.015,"thickness":0.08,"baseHeight":0.04,"showInfill":true,"postSpacing":0.35,"topRailHeight":0.09,"groundClearance":0},"level_c7kb8ay8i5n3q92m":{"id":"level_c7kb8ay8i5n3q92m","type":"level","level":0,"object":"node","visible":true,"children":["wall_5zo7dm0uvk0pfju5","wall_dazxo798ki8pgnff","wall_57s39vmwxfq5za0l","wall_9g78aagb3d9xxitr","wall_09qn8o3fiwtz45wy","wall_zb9zn4p8rteb2uql","item_rt1jnwuu5q7jr1ho","wall_hiwy7wvffuz8py7s","wall_lqvpfuyzau9fzkgs","wall_kvqihqe5d9n9g0oc","wall_140trhrqi7eio8qq","wall_uhqtl0rapbnfigqy","wall_o3sipgjqvlmla2jt","wall_kcfxabt0e2b3wusf","wall_m1mxa7gvkcuw886t","wall_nhk4k0cpxwaya1fj","wall_45hwqbrj4tkr65pc","slab_gfwn5gg37s4vbaxq","ceiling_e6x0ev7j1gx2ousc","wall_lea2gxc27puc3n9z","wall_ezu11zocogdbtuht","wall_nmid5oq2vtlxthxz","wall_eoyrn00w7x0htu9w","item_m0rfafsc3o4dn4nu","wall_8ufjpww7jx9bsxhp","wall_vu3f0nwh6q4biyml","wall_lgairsceyw874vwo","wall_vv46t743yzjkp75d","wall_vgfztgld1iyz03hs","wall_fixqs7rz4ejb9wl9","wall_twloychxtm3ec706","wall_mqosy280yms4dcyl","wall_72lgxbxx4aq5ifxc","wall_jhq14ndqldmq9vf8","wall_b2vligz08ucw81tf","wall_lhk47afoeymdpvwr","wall_1aqnio3z2swd7632","wall_3avujhzyb9vrlmiu","wall_e70i2pt14fipf7f9","wall_op0omao9jequusd0","slab_i19mzr7uliu7ztpx","ceiling_m79ylfnf8bjocxdh","item_bemxpqe5zyv62xat","item_b7yy788blhr8hovy","item_oq7sjc61h8gpny4t","wall_fpizzvyeydc1tgwv","wall_rsabhuiuzuei6t14","wall_bxjfrx4xqt15ir57","wall_bsrv7p9bnpcdn06h","wall_rsm36dul3l6ue60h","wall_lbygbccrx2zapwc9","wall_ax0ct539gmmfq5qh","wall_zovp1qu83cbgn2u9","wall_k4mh2k5sty71ixll","wall_free8uwwxdtfpsm0","wall_3wvtfkszvjddhl09","wall_23uozapaf4f7vxbu","wall_9sfj2yc45km30d4h","wall_kvotvn6k2je8hv9l","wall_ci1zeo5trejkbdkc","wall_tf4qyoz9ekfozccj","wall_poe9onw07jpxc34z","wall_njazeipo5u7emoju","wall_boqdcq63dglq6j8t","wall_511vyjfe86jdpfjc","wall_f7893lho24ex55pj","slab_jp2bg9p3tq59l3iu","ceiling_fm6jv80vtzwq7lnr","wall_1624lf5ywztagcho","wall_scjpkore2sqkklqv","wall_5tpzo3llueskblic","wall_7vlpz9r5adi41efi","wall_9evtpcg2zxspy62d","slab_we9t2usq1m3s22qk","ceiling_lkq8uii8rj7kp7qw","wall_1xhe9ek9ox92k1ad","wall_nnj3nxr3v1h0y65p","wall_zmwbk6swgebpykct","wall_ey2wdo1kqv0x23ma","wall_qh3ahacsxna8akmo","wall_u159rpl5ey25g893","wall_rq0pzcyto5oukci6","wall_o29gc9a26conmttb","wall_ckjbkszhejacwysj","wall_1o0ho2nwpbwjrysh","wall_mukwta285d1nayjp","wall_67zv71d6hvihz3wd","wall_4d0xw9erem5q4j9h","slab_2flcl86fygpphdd3","ceiling_yxor23q7nlpmzwf9","item_xq66fayns2ugskna","wall_v3sr07iaeh1v7hnn","wall_n08yiceoh4qtei2j","wall_qbipm5170ddx1anr","wall_4avg2h4yzyytqq8q","wall_f2npta6ui1n3x8nb","wall_suoqjtukn48pfuw7","wall_0a3llbsfqmoc5ni2","wall_j06as20cdjshont3","item_cjqvy71xiz2bj7oq","wall_bmrz9ke2xmdkvynh","wall_pj6yfijswry56gho","wall_x1kh2wmgiel4bmfj","wall_hur4i86ycgdti8mz","ceiling_6jarbep0qzj7na5s","wall_ktqckft5foyfjhyh","wall_te3u345qtohv9vjo","slab_2gzyh5gpavanhg47","slab_whaas4pjyvbv8e82","slab_8r46nvo4jfmetnmh","slab_bh542hgiwr5qawh0","slab_fq9wkbtpstuw7muc","slab_b0uy5yl6wyyu4ls5","slab_82b54zlmz2j1rhqz","slab_9i2m8wykuazda1bv","slab_4rctvmu1lht5edsb","slab_yzdeb08ot8x1ufg4","slab_uoka5x6c23v8lci7","slab_q16hxb0n1rpxd8fe","slab_ded5xta3bjfnjsy6","slab_dyw0a3vk5at1mzmz","item_75gj10k31pq2vd3q","item_bbsvwhx3gi0rvj2j","item_xvwq3s5d26gmao82","wall_f2f7ztggiy1sqbj6","wall_v8v45xnlfyyc7ep0","slab_bxaqzfp98ffiasba","ceiling_lo8ibt14jq4l2928","item_rnpnvb2zptsklouk","item_hr6pnvwvn6b1yvd4","item_bvo47cc15sv7mfie","item_iydikfspl2x5gdv4","item_mo9d0rcr24zrt7l0","item_g1s2kivkxdq7kx7x","slab_knoyu9wqbw08i2e2","slab_bz3tthixrk0bt55b","slab_67ch2q19c1r3xr18","slab_14xupespfhxy81q6","wall_0npbxm44kepovw9e","wall_90uid8e6qurlee1g","wall_ya9meea2cq3u4xep","wall_ddo4m0zdpr61yl79","wall_p6up981dq7o6keek","slab_ptxzpw7sfnttfjaf","ceiling_k28mipj53hg3om3t","wall_il3k30g2f3sv1rcm","slab_5xc1b6wvrbhbr9ji","ceiling_6qdx1dgka8y5qae5","wall_xdybfyjhn6p9ucq7","fence_is7i5npo2cl001j7","wall_hervqjln3nui1iwa","wall_jj1ptn150ypxrz01","ceiling_7yzf0q0ucpboidgd","wall_4htt68qzmhcal2tp","wall_tp7o7mn70e2xwk85","wall_laxcblwuvhm3ijs7","wall_fc0yo78bjook97f6","slab_mdd8h5wyitom71yo","ceiling_pcs3z35yr2ekpjda","wall_aq63oll1ms4534us","wall_pszoe902uvgt1yqu","slab_pgnswibpafl51hdc","ceiling_xieopsv10tase7tv","wall_vg3bosm6qyt1c25z","slab_5hq9gnnvv685w0iy","ceiling_r6mjw516c87ppnga","wall_tebqur8nrk74nmnt","wall_hclslg87nmmrzhy2","wall_u2vdle19v0ql3ej9","wall_g2i3cozy8i3s9xns","slab_xhc9lp2ez02kb7t1","ceiling_qe4irigb7v5zj5w1","wall_ptnfpltgh4e4c85b","slab_dcbfhyip0m368v0u","ceiling_myk4w8lb4c8a9gfb","item_twd7ta3np8q1my3n","item_9eyeyrqz7vmbj2ix","item_koh2dkodepr7fdry","item_49oh8gegy3b7yvxf","item_f1y18gw5p6fvehhg","item_i2dvy7hbyprzy6zc","item_bmn4w1vvzmz75e6k","item_e8jxcs2rceaqif9v","item_osle5nqu0qcanyvw","item_rqw12mokwasjm197","item_3qn9x40xfvjj3vyx","item_ia6qe7ep6w646lp1","item_lqn1xzoxt7hyp5dv","item_lya5kbtxvt1jxnbx","item_fqtfdbv5dfqjqcoz","ceiling_1hdfd2xji78bpjz7","ceiling_bya4rjlhmqgsktuj","wall_a6zlyi7ogc0getot","wall_zcla9q6jevq75eh8","wall_vp4awhvgp3deoth1","wall_yjq6lrhge7g81kkh","roof_58fhgyatlj0739cq","item_p5ybd7s29uvarrva","item_rz8i6vvgycvkciu4","item_4ppll7gktbykanvz","slab_i2hr3x3p5rli1yuw","slab_1hptmowf5nxohdwz","item_nc7jgap1n30bf0lq","item_9u5lgu7a9ps314m1","wall_hkzv1k6d6qowpoac","wall_omc5jlwqm2leepuz","wall_mh6fum5rekj6s07d","wall_yrmx4yncojhot61j","slab_gv57hc2h694xl8qy","ceiling_b5s7zqunyczthkez","wall_q21eg7ipg0lfmdfc","wall_xz7iwgol1ji7w4pz","wall_7fy1vx9pydr9xs7n","wall_mco0e8drg9r99eqv","slab_4xs0oggyfd6zlw1y","ceiling_ojdgepqkm30dme26","wall_dqq567z069dtz3tv","slab_p37ex4kfe3khiwlx","slab_9ynn2en10adk037b","ceiling_573df79hlvil8avw","ceiling_i7kwct79xof6ftcc","item_fl3hswt3euwto8qy","item_vd6lnd61man7injx","item_3dardy3wuzy5q0o6","item_y2mq75o5q1n8n333","slab_p0slb1ujxa56wgtm","item_2paojpidf3f3xfqu","slab_4w2maucrcekoyacr","ceiling_0xxy9kvf9idoug3n","item_ttkl9g6k5bmdn81l","item_9c4on91q6ohlq32r","item_iu7jblky9i7h6x90","zone_vhi7rtdz2eagnf7z","zone_uhf0e393u8f04e7a","zone_zsywh4vjl3k3jxxp","zone_n2k001mmc4dm93ow","zone_mnf35gnjfxirqhqr","zone_dxhvxhl04b7towyq","zone_aujjt6sq7p45kl72","zone_9h2q65itdkpkpedg","zone_w7i3wwyswt8t1kvj","zone_p1vz7o7e8a81pye5","zone_arusgjyzhqflpn8a","zone_glzsnj67sedhx3sy","zone_jra72agx2ybpsofn","zone_4enmz21dobmb6syx","zone_keikusorpa0974ln","zone_3be32bohno92xs9a","zone_jb4l1cwqnwslq6tr","zone_xmmyfm2x084ipdhc","zone_cpxr02vol9zmutv4","zone_0fsedoxyxx793l1z","wall_xttll6vqda9pv1ub","slab_ac4szhj57oo7lek8","ceiling_27rtc6ewt7qnnie7","wall_xbfj7l13705yb4al","wall_tymqcjozlz0wbr3b","slab_lt6auhuwta9rqsya","ceiling_u5e8bj231qrgyu7d","item_y9bc3lpc2ci6pxsv","spawn_uk3tnumrp24tw036","item_gwq4pjm91g1o6b6c","item_eyljfsnlp19x60u4","column_nkpw8z9m5wqszdjb","column_jdfkcu2nbfx1nuqu"],"metadata":{},"parentId":null},"level_zoigq4mixumm1k6t":{"id":"level_zoigq4mixumm1k6t","type":"level","level":1,"object":"node","visible":true,"children":["roof_z1i58d6e60oeb7dw","roof_6gxvkkt81ntnp0h4","roof_14zvu2n2u6yg8o05","roof_f3uny9sfzkuju5wo","roof_oy5wu0vekqdxgigf","roof_fjutdcwgvmaxx6tu","roof_k4weorepgkerrkue","roof_vvcgpqscthisxuhu","roof_utu4r0g4k97b3tqq","roof_18wafaxjhnk09d57","roof_iw0d29jyd8h3ug2h","roof_2gl2hghodp541yw9","roof_xnp2fmv9194sv5bv","roof_6fs144kokuw3d66o","roof_daipbvbrid886o9d","roof_5ai324c2mm4g9oe9","roof_4c9z960oiy9mvtd0","roof_uam7w7hfhuemgolb","roof_uxedomh4y0oyomrp","roof_b5t2vadph3339fj1","roof_ja24y37qth8r8z5k","roof_n9ce4tnnpfcm2ak9","roof_c3wrxwv3tv2eog7q","roof_igb1vv7574i5lvqq","roof_w36mcr69xg1wdaox","roof_l8novz1nm4f87uwg","roof_n2d4t91csyoe63oc","roof_vwen3bpj3gjqlk7f"],"metadata":{},"parentId":"building_0cuqp4cgakwi0z90"},"spawn_uk3tnumrp24tw036":{"id":"spawn_uk3tnumrp24tw036","name":"Spawn Point","type":"spawn","object":"node","visible":true,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[-0.07,0,-16],"rotation":0},"column_jdfkcu2nbfx1nuqu":{"id":"column_jdfkcu2nbfx1nuqu","name":"Straight Round","type":"column","depth":0.3,"style":"plain","width":0.3,"height":3,"object":"node","radius":0.15,"visible":true,"leafRows":2,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[0,0,10.5],"rotation":0,"baseStyle":"none","beadCount":0,"leafCount":18,"ringCount":0,"baseHeight":0.22,"braceDepth":0.16,"braceWidth":0.16,"fluteCount":0,"fluteDepth":0.02,"fluteWidth":0.02,"panelCount":0,"panelShape":"rectangle","ringSpread":0.16,"shaftBulge":0,"shaftTaper":0,"voluteSize":0.08,"dentilCount":0,"shaftDetail":"none","spiralTwist":0,"voluteCount":4,"baseRibCount":0,"bracketDepth":0.35,"capitalStyle":"none","carvingLevel":0,"crossSection":"round","edgeSoftness":0,"pendantCount":0,"shaftProfile":"straight","supportStyle":"vertical","baseNeckScale":0.72,"baseTierCount":1,"capitalHeight":0.2,"ringPlacement":"ends","ringThickness":0.055,"shaftEndScale":0.72,"baseDepthScale":1.24,"basePanelInset":0.02,"baseStepSpread":0.34,"baseWidthScale":1.24,"braceTopSpread":0.12,"latheRingCount":0,"shaftTwistStep":0,"spiralRibCount":0,"lowerBandHeight":0.24,"panelInsetDepth":0.02,"shaftStartScale":0.72,"baseCarvingLevel":0,"bracketTierCount":3,"capitalBandCount":0,"capitalTierCount":1,"carvingPlacement":"capital","latheRingSpacing":"ends","lowerBandEnabled":false,"braceBottomSpread":1.2,"bracePlateEnabled":true,"capitalDepthScale":1.22,"capitalStepSpread":0.34,"capitalWidthScale":1.22,"shaftCornerRadius":0.035,"shaftSegmentCount":1,"baseRoundBandCount":0,"baseRoundBandScale":0.92,"capitalCarvingLevel":0,"basePlinthHeightRatio":0.44,"lowerBandCarvingLevel":0},"column_nkpw8z9m5wqszdjb":{"id":"column_nkpw8z9m5wqszdjb","name":"Straight Round","type":"column","depth":0.3,"style":"plain","width":0.3,"height":3,"object":"node","radius":0.15,"visible":true,"leafRows":2,"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","position":[3.5,0,15.5],"rotation":0,"baseStyle":"none","beadCount":0,"leafCount":18,"ringCount":0,"baseHeight":0.22,"braceDepth":0.16,"braceWidth":0.16,"fluteCount":0,"fluteDepth":0.02,"fluteWidth":0.02,"panelCount":0,"panelShape":"rectangle","ringSpread":0.16,"shaftBulge":0,"shaftTaper":0,"voluteSize":0.08,"dentilCount":0,"shaftDetail":"none","spiralTwist":0,"voluteCount":4,"baseRibCount":0,"bracketDepth":0.35,"capitalStyle":"none","carvingLevel":0,"crossSection":"round","edgeSoftness":0,"pendantCount":0,"shaftProfile":"straight","supportStyle":"vertical","baseNeckScale":0.72,"baseTierCount":1,"capitalHeight":0.2,"ringPlacement":"ends","ringThickness":0.055,"shaftEndScale":0.72,"baseDepthScale":1.24,"basePanelInset":0.02,"baseStepSpread":0.34,"baseWidthScale":1.24,"braceTopSpread":0.12,"latheRingCount":0,"shaftTwistStep":0,"spiralRibCount":0,"lowerBandHeight":0.24,"panelInsetDepth":0.02,"shaftStartScale":0.72,"baseCarvingLevel":0,"bracketTierCount":3,"capitalBandCount":0,"capitalTierCount":1,"carvingPlacement":"capital","latheRingSpacing":"ends","lowerBandEnabled":false,"braceBottomSpread":1.2,"bracePlateEnabled":true,"capitalDepthScale":1.22,"capitalStepSpread":0.34,"capitalWidthScale":1.22,"shaftCornerRadius":0.035,"shaftSegmentCount":1,"baseRoundBandCount":0,"baseRoundBandScale":0.92,"capitalCarvingLevel":0,"basePlinthHeightRatio":0.44,"lowerBandCarvingLevel":0},"window_0ij8i9wxij6vu68d":{"id":"window_0ij8i9wxij6vu68d","name":"Window 21","side":"front","sill":false,"type":"window","width":1,"height":0.5,"object":"node","wallId":"wall_7vlpz9r5adi41efi","visible":true,"metadata":{},"parentId":"wall_7vlpz9r5adi41efi","position":[0.7,2.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_0tk51z11kqyiud4w":{"id":"window_0tk51z11kqyiud4w","side":"front","sill":false,"type":"window","width":2.6,"height":0.6,"object":"node","wallId":"wall_twloychxtm3ec706","visible":true,"metadata":{},"parentId":"wall_twloychxtm3ec706","position":[1.5,2.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_3ck01pusx7nppzmw":{"id":"window_3ck01pusx7nppzmw","side":"front","sill":false,"type":"window","width":4.3,"height":1.7,"object":"node","wallId":"wall_kvqihqe5d9n9g0oc","visible":true,"metadata":{},"parentId":"wall_kvqihqe5d9n9g0oc","position":[3.5,1.9,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.2,0.2,0.2,0.2,0.2],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_5zjdjzx59g2kmzfd":{"id":"window_5zjdjzx59g2kmzfd","name":"Window 4","side":"front","sill":false,"type":"window","width":1.5,"height":0.6,"object":"node","wallId":"wall_e70i2pt14fipf7f9","visible":true,"metadata":{},"parentId":"wall_e70i2pt14fipf7f9","position":[1,2.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_65h7hrxtu4uwau9l":{"id":"window_65h7hrxtu4uwau9l","side":"front","sill":false,"type":"window","width":1.2,"height":0.6,"object":"node","wallId":"wall_ktqckft5foyfjhyh","visible":true,"metadata":{},"parentId":"wall_ktqckft5foyfjhyh","position":[0.7,2.4,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_7c3ahr05ob2flmo4":{"id":"window_7c3ahr05ob2flmo4","side":"front","sill":false,"type":"window","width":4,"height":0.6,"object":"node","wallId":"wall_ezu11zocogdbtuht","visible":true,"metadata":{},"parentId":"wall_ezu11zocogdbtuht","position":[2.5,2.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_7e1ztf1g1bzou5b7":{"id":"window_7e1ztf1g1bzou5b7","side":"front","sill":false,"type":"window","width":1,"height":2.2,"object":"node","wallId":"wall_9g78aagb3d9xxitr","visible":true,"metadata":{},"parentId":"wall_9g78aagb3d9xxitr","position":[0.8,1.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_86ahb5wo9wbup3z4":{"id":"window_86ahb5wo9wbup3z4","name":"Window 4","side":"back","sill":false,"type":"window","width":1.5,"height":0.6,"object":"node","wallId":"wall_f2f7ztggiy1sqbj6","visible":true,"metadata":{},"parentId":"wall_f2f7ztggiy1sqbj6","position":[1.3,2.5,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_9kyv4l4vkxr77rgn":{"id":"window_9kyv4l4vkxr77rgn","name":"Window 1","side":"back","sill":false,"type":"window","width":1.3,"height":2.2,"object":"node","wallId":"wall_09qn8o3fiwtz45wy","visible":true,"metadata":{},"parentId":"wall_09qn8o3fiwtz45wy","position":[1,1.5,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_bhnz7yv89tof7yz9":{"id":"window_bhnz7yv89tof7yz9","name":"Window 21","side":"front","sill":true,"type":"window","width":1,"height":0.5,"object":"node","wallId":"wall_f7893lho24ex55pj","visible":true,"metadata":{},"parentId":"wall_f7893lho24ex55pj","position":[0.8,2.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_c4bw6z49vgxg9b01":{"id":"window_c4bw6z49vgxg9b01","side":"back","sill":false,"type":"window","width":4,"height":0.6,"object":"node","wallId":"wall_45hwqbrj4tkr65pc","visible":true,"metadata":{},"parentId":"wall_45hwqbrj4tkr65pc","position":[2.5,2.5,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_drbs0ipvpb9ksir3":{"id":"window_drbs0ipvpb9ksir3","name":"Window 14","side":"back","sill":true,"type":"window","width":1.1,"height":2.3,"object":"node","wallId":"wall_v8v45xnlfyyc7ep0","visible":true,"metadata":{},"parentId":"wall_v8v45xnlfyyc7ep0","position":[0.75,1.2,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_ealysksymsw3mvev":{"id":"window_ealysksymsw3mvev","side":"front","sill":false,"type":"window","width":0.8,"height":1.9,"object":"node","wallId":"wall_kvotvn6k2je8hv9l","visible":true,"metadata":{},"parentId":"wall_kvotvn6k2je8hv9l","position":[0.7,1.3,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.04,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_kx6wlvpiz2r0lopt":{"id":"window_kx6wlvpiz2r0lopt","name":"Window 21","side":"front","sill":true,"type":"window","width":1,"height":0.5,"object":"node","wallId":"wall_fc0yo78bjook97f6","visible":true,"metadata":{},"parentId":"wall_fc0yo78bjook97f6","position":[0.7,2.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_m9oe04rx8mtddlu6":{"id":"window_m9oe04rx8mtddlu6","name":"Window 9","side":"front","sill":false,"type":"window","width":1.1,"height":2.5,"object":"node","wallId":"wall_qh3ahacsxna8akmo","visible":true,"metadata":{},"parentId":"wall_qh3ahacsxna8akmo","position":[0.75,1.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_t9x3t14wzyfkap1h":{"id":"window_t9x3t14wzyfkap1h","side":"back","sill":false,"type":"window","width":3.1,"height":0.6,"object":"node","wallId":"wall_lqvpfuyzau9fzkgs","visible":true,"metadata":{},"parentId":"wall_lqvpfuyzau9fzkgs","position":[5.2,0.5,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_ua0lfxygo38djdnp":{"id":"window_ua0lfxygo38djdnp","side":"front","sill":false,"type":"window","width":2,"height":0.6,"object":"node","wallId":"wall_72lgxbxx4aq5ifxc","visible":true,"metadata":{},"parentId":"wall_72lgxbxx4aq5ifxc","position":[1,2.4,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_wh8lydfblsw15mpa":{"id":"window_wh8lydfblsw15mpa","name":"Window 21","side":"front","sill":true,"type":"window","width":0.9,"height":0.5,"object":"node","wallId":"wall_xz7iwgol1ji7w4pz","visible":true,"metadata":{},"parentId":"wall_xz7iwgol1ji7w4pz","position":[0.75,2.3,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_wnbj77udzsef7ml8":{"id":"window_wnbj77udzsef7ml8","side":"front","sill":false,"type":"window","width":3.4,"height":0.6,"object":"node","wallId":"wall_57s39vmwxfq5za0l","visible":true,"metadata":{},"parentId":"wall_57s39vmwxfq5za0l","position":[2,2.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_z4g0lf5l560qdqbb":{"id":"window_z4g0lf5l560qdqbb","name":"Window 2","side":"back","sill":false,"type":"window","width":2.4,"height":1.7,"object":"node","wallId":"wall_3avujhzyb9vrlmiu","visible":true,"metadata":{},"parentId":"wall_3avujhzyb9vrlmiu","position":[3.3,1.9,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.3333333333333333,0.3333333333333333,0.3333333333333333],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_zwxyh3sl3qpokzcc":{"id":"window_zwxyh3sl3qpokzcc","side":"front","sill":false,"type":"window","width":1.1,"height":2.5,"object":"node","wallId":"wall_ci1zeo5trejkbdkc","visible":true,"metadata":{},"parentId":"wall_ci1zeo5trejkbdkc","position":[1,1.5,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[1],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","openingRadiusMode":"all","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"ceiling_0xxy9kvf9idoug3n":{"id":"ceiling_0xxy9kvf9idoug3n","name":"Room 52 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-19,-3],[-16,-3],[-16,-1.3],[-13,-1.3],[-13,1],[-19,1]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_1hdfd2xji78bpjz7":{"id":"ceiling_1hdfd2xji78bpjz7","name":"Ceiling 21","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-9,3],[-11,3],[-11,-2],[-9,-2]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":false},"ceiling_27rtc6ewt7qnnie7":{"id":"ceiling_27rtc6ewt7qnnie7","name":"Room 54 Ceiling","type":"ceiling","holes":[],"height":2.5,"object":"node","polygon":[[-17,-11],[-13,-11],[-13,-3],[-16,-3],[-16,-5.5],[-17,-5.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_573df79hlvil8avw":{"id":"ceiling_573df79hlvil8avw","name":"Room 50 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[14,2.5],[14,5.5],[11,5.5],[11,2.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_6jarbep0qzj7na5s":{"id":"ceiling_6jarbep0qzj7na5s","name":"Room 37 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[4,-3],[6,-3],[6,-4],[11,-4],[11,5.5],[6.5,5.5],[6.5,1.5],[4,1.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_6qdx1dgka8y5qae5":{"id":"ceiling_6qdx1dgka8y5qae5","name":"Room 40 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-16.5,12.5],[-16.5,11],[-13,11],[-13,12.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_7yzf0q0ucpboidgd":{"id":"ceiling_7yzf0q0ucpboidgd","name":"Ceiling 18","type":"ceiling","holes":[],"height":2,"object":"node","polygon":[[2,-15],[2,-13.5],[-2,-13.5],[-2,-15]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":false},"ceiling_b5s7zqunyczthkez":{"id":"ceiling_b5s7zqunyczthkez","name":"Room 48 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-1.5,-4],[-11.5,-4],[-11.5,-12.5],[-3,-12.5],[-3,-8.5],[-1.5,-8.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_bya4rjlhmqgsktuj":{"id":"ceiling_bya4rjlhmqgsktuj","name":"Ceiling 22","type":"ceiling","holes":[],"height":3.1,"object":"node","polygon":[[-11,-4],[-11,-2],[-9,-2],[-9,-1],[0.5,-1],[0.5,10],[4,10],[4,-7],[2,-7],[2,-12],[-1.5,-12],[-1.5,-4]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":false},"ceiling_e6x0ev7j1gx2ousc":{"id":"ceiling_e6x0ev7j1gx2ousc","name":"Room 8 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-9,5],[-9,10],[-11,10],[-11,5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_fm6jv80vtzwq7lnr":{"id":"ceiling_fm6jv80vtzwq7lnr","name":"Room 19 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-13,11],[-13,16],[-19,16],[-19,12.5],[-13,12.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_i7kwct79xof6ftcc":{"id":"ceiling_i7kwct79xof6ftcc","name":"Room 51 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[11,7],[11,5.5],[13,5.5],[13,7]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_k28mipj53hg3om3t":{"id":"ceiling_k28mipj53hg3om3t","name":"Room 39 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-19,11],[-16.5,11],[-16.5,12.5],[-19,12.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_lkq8uii8rj7kp7qw":{"id":"ceiling_lkq8uii8rj7kp7qw","name":"Room 22 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-13,6],[-13,4.5],[-19,4.5],[-19,1],[-13,1]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_lo8ibt14jq4l2928":{"id":"ceiling_lo8ibt14jq4l2928","name":"Room 38 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-16,-5.5],[-16,-3],[-20.5,-3],[-20.5,-5.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_m79ylfnf8bjocxdh":{"id":"ceiling_m79ylfnf8bjocxdh","name":"Room 14 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[6,-3],[4,-3],[4,-5],[6,-5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_myk4w8lb4c8a9gfb":{"id":"ceiling_myk4w8lb4c8a9gfb","name":"Room 45 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-19,6],[-19,4.5],[-16.5,4.5],[-16.5,6]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_ojdgepqkm30dme26":{"id":"ceiling_ojdgepqkm30dme26","name":"Room 49 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-1.5,-10.5],[-1.5,-8.5],[-3,-8.5],[-3,-10.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_pcs3z35yr2ekpjda":{"id":"ceiling_pcs3z35yr2ekpjda","name":"Room 41 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-13,6],[-13,9.5],[-19,9.5],[-19,6]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_qe4irigb7v5zj5w1":{"id":"ceiling_qe4irigb7v5zj5w1","name":"Room 44 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-13,4.5],[-13,6],[-16.5,6],[-16.5,4.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_r6mjw516c87ppnga":{"id":"ceiling_r6mjw516c87ppnga","name":"Room 43 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-16.5,11],[-19,11],[-19,9.5],[-16.5,9.5]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_u5e8bj231qrgyu7d":{"id":"ceiling_u5e8bj231qrgyu7d","name":"Room 55 Ceiling","type":"ceiling","holes":[],"height":2.5,"object":"node","polygon":[[-17,-5.5],[-20.5,-5.5],[-20.5,-11],[-17,-11],[-17,-9],[-19,-9],[-19,-5.5],[-19,-9],[-17,-9],[-17,-7.95],[-18,-7.95],[-17,-7.95]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_xieopsv10tase7tv":{"id":"ceiling_xieopsv10tase7tv","name":"Room 42 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-16.5,9.5],[-13,9.5],[-13,11],[-16.5,11]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"ceiling_yxor23q7nlpmzwf9":{"id":"ceiling_yxor23q7nlpmzwf9","name":"Room 31 Ceiling","type":"ceiling","holes":[],"height":3,"object":"node","polygon":[[-16,-1.3],[-16,-3],[-13,-3],[-13,-1.3]],"visible":true,"children":[],"metadata":{},"parentId":"level_c7kb8ay8i5n3q92m","holeMetadata":[],"autoFromWalls":true},"building_0cuqp4cgakwi0z90":{"id":"building_0cuqp4cgakwi0z90","type":"building","object":"node","visible":true,"children":["level_c7kb8ay8i5n3q92m","level_zoigq4mixumm1k6t"],"metadata":{},"parentId":null,"position":[0,0,0],"rotation":[0,0,0]},"skylight_36wy74anvdb0xb2p":{"id":"skylight_36wy74anvdb0xb2p","curb":false,"name":"Skylight","type":"skylight","width":3,"height":0.35,"object":"node","visible":true,"metadata":{},"parentId":"rseg_qlcqbzy4j2opbyo9","position":[1.9499999999999993,0,0.5600000000000005],"rotation":0,"curbHeight":0,"frameDepth":0.045,"trackWidth":0.04,"openingSide":"top","cutoutOffset":0,"motorHousing":false,"openingAngle":0,"skylightType":"walk-on","lanternHeight":0.25,"roofSegmentId":"rseg_qlcqbzy4j2opbyo9","slideFraction":0,"frameThickness":0.035,"glassThickness":0.04,"operationState":0,"slideDirection":"z","lanternTopScale":0,"motorHousingSize":0.08},"skylight_3vpiv265w9yaq8be":{"id":"skylight_3vpiv265w9yaq8be","curb":false,"name":"Skylight","type":"skylight","width":3,"height":0.35,"object":"node","visible":true,"metadata":{},"parentId":"rseg_qlcqbzy4j2opbyo9","position":[1.9600000000000009,0,2.91],"rotation":0,"curbHeight":0,"frameDepth":0.045,"trackWidth":0.04,"openingSide":"top","cutoutOffset":0,"motorHousing":false,"openingAngle":0,"skylightType":"walk-on","lanternHeight":0.25,"roofSegmentId":"rseg_qlcqbzy4j2opbyo9","slideFraction":0,"frameThickness":0.035,"glassThickness":0.04,"operationState":0,"slideDirection":"z","lanternTopScale":0,"motorHousingSize":0.08},"skylight_995tecbx7np1uv6c":{"id":"skylight_995tecbx7np1uv6c","curb":false,"name":"Skylight","type":"skylight","width":1.95,"height":0.35,"object":"node","visible":true,"metadata":{},"parentId":"rseg_qlcqbzy4j2opbyo9","position":[-0.8900000000000006,0,-3.6100000000000003],"rotation":0,"curbHeight":0,"frameDepth":0.045,"trackWidth":0.04,"openingSide":"top","cutoutOffset":0,"motorHousing":false,"openingAngle":0,"skylightType":"walk-on","lanternHeight":0.25,"roofSegmentId":"rseg_qlcqbzy4j2opbyo9","slideFraction":0,"frameThickness":0.035,"glassThickness":0.04,"operationState":0,"slideDirection":"z","lanternTopScale":0,"motorHousingSize":0.08},"skylight_kzgptzbm0ekqto5c":{"id":"skylight_kzgptzbm0ekqto5c","curb":false,"name":"Skylight","type":"skylight","width":2.3,"height":0.35,"object":"node","visible":true,"metadata":{},"parentId":"rseg_r264ln4hdi9s09wj","position":[1.6600000000000001,0,-1.63],"rotation":0,"curbHeight":0,"frameDepth":0.045,"trackWidth":0.04,"openingSide":"top","cutoutOffset":0,"motorHousing":false,"openingAngle":0,"skylightType":"walk-on","lanternHeight":0.25,"roofSegmentId":"rseg_r264ln4hdi9s09wj","slideFraction":0,"frameThickness":0.035,"glassThickness":0.04,"operationState":0,"slideDirection":"z","lanternTopScale":0,"motorHousingSize":0.08},"skylight_xzln5dzu6lhnn959":{"id":"skylight_xzln5dzu6lhnn959","curb":false,"name":"Skylight","type":"skylight","width":3,"height":0.35,"object":"node","visible":true,"metadata":{},"parentId":"rseg_qlcqbzy4j2opbyo9","position":[2.0248127908492926,0,-4.44],"rotation":0,"curbHeight":0,"frameDepth":0.045,"trackWidth":0.04,"openingSide":"top","cutoutOffset":0,"motorHousing":false,"openingAngle":0,"skylightType":"walk-on","lanternHeight":0.25,"roofSegmentId":"rseg_qlcqbzy4j2opbyo9","slideFraction":0,"frameThickness":0.035,"glassThickness":0.04,"operationState":0,"slideDirection":"z","lanternTopScale":0,"motorHousingSize":0.08},"skylight_zhxpo0yigowyfsko":{"id":"skylight_zhxpo0yigowyfsko","curb":false,"name":"Skylight","type":"skylight","width":1.95,"height":0.35,"object":"node","visible":true,"metadata":{},"parentId":"rseg_qlcqbzy4j2opbyo9","position":[-0.9899999999999984,0,1.4038958418532541],"rotation":0,"curbHeight":0,"frameDepth":0.045,"trackWidth":0.04,"openingSide":"top","cutoutOffset":0,"motorHousing":false,"openingAngle":0,"skylightType":"walk-on","lanternHeight":0.25,"roofSegmentId":"rseg_qlcqbzy4j2opbyo9","slideFraction":0,"frameThickness":0.035,"glassThickness":0.04,"operationState":0,"slideDirection":"z","lanternTopScale":0,"motorHousingSize":0.08},"skylight_zng4bb9bg0091xpz":{"id":"skylight_zng4bb9bg0091xpz","curb":false,"name":"Skylight","type":"skylight","width":1.95,"height":0.35,"object":"node","visible":true,"metadata":{},"parentId":"rseg_qlcqbzy4j2opbyo9","position":[-0.9727744339841209,0.15000000596046448,2.0681497888151057],"rotation":0,"curbHeight":0,"frameDepth":0.045,"trackWidth":0.04,"openingSide":"top","cutoutOffset":0,"motorHousing":false,"openingAngle":0,"skylightType":"walk-on","lanternHeight":0.25,"roofSegmentId":"rseg_qlcqbzy4j2opbyo9","slideFraction":0,"frameThickness":0.035,"glassThickness":0.04,"operationState":0,"slideDirection":"z","lanternTopScale":0,"motorHousingSize":0.08},"solarpanel_3f1pjkda065ol6u1":{"id":"solarpanel_3f1pjkda065ol6u1","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[1.8011433603090996,0.1500000059604627,-7.533631591792058],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"},"solarpanel_6q278690k162lil6":{"id":"solarpanel_6q278690k162lil6","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[-1.4543252275548335,0.15000000596046448,5.313400677464678],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"},"solarpanel_otkgl1d0sv2wfgqq":{"id":"solarpanel_otkgl1d0sv2wfgqq","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[-1.4235183029774472,0.15000000596046448,-7.563076325031994],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"},"solarpanel_p56gklaauhob6wel":{"id":"solarpanel_p56gklaauhob6wel","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[1.8187674026855554,0.15000000596046448,5.292129060817251],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"},"solarpanel_s5kqzi4eq1wxuka1":{"id":"solarpanel_s5kqzi4eq1wxuka1","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[-1.4128995083811926,0.15000000596046625,-3.327086985632402],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"},"solarpanel_shim3qipejj18p9a":{"id":"solarpanel_shim3qipejj18p9a","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[1.8649188669503864,0.15000000596046448,1.0161824488493574],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"},"solarpanel_tkn7tdnkpumt0oo3":{"id":"solarpanel_tkn7tdnkpumt0oo3","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[-1.430549253863794,0.15000000596046625,0.9922287379249086],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"},"solarpanel_vkkov9mbny93e8wn":{"id":"solarpanel_vkkov9mbny93e8wn","gapX":0.02,"gapY":0.02,"name":"Solar Panel","rows":2,"type":"solar-panel","object":"node","columns":3,"visible":true,"metadata":{},"parentId":"rseg_8nlt7y8fs1jtextk","position":[1.827018778159994,0.15000000596046448,-3.3158463020423836],"rotation":0,"tiltAngle":15,"frameDepth":0.04,"panelWidth":1,"panelHeight":2,"mountingType":"flush","roofSegmentId":"rseg_8nlt7y8fs1jtextk","surfaceNormal":[0,1,0],"frameThickness":0.04,"standoffHeight":0.05,"panelTypePreset":"residential-large"}} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-26.json b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-26.json new file mode 100644 index 0000000000..26da2b0568 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/review/scene-26.json @@ -0,0 +1 @@ +{"site_z8qe2dvebl25t4o8":{"id":"site_z8qe2dvebl25t4o8","type":"site","object":"node","polygon":{"type":"polygon","points":[[-9.997573852539062,-29.998380661010742],[16.026264190673828,-29.981937408447266],[16.002086639404297,14.003129005432129],[-9.997172355651855,14.003995895385742],[-9.956132888793945,-8.234814643859863]]},"visible":true,"children":["building_e7p75atkqjiu2t6m"],"parentId":null},"slab_0nam1bvylu27ugcy":{"id":"slab_0nam1bvylu27ugcy","name":"Slab 13","type":"slab","holes":[],"slots":{"surface":"library:preset-charcoal"},"object":"node","polygon":[[-15,18],[-15,-40],[-11,-40],[-11,18]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.15,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_21t1rgwbsjsdcb0l":{"id":"slab_21t1rgwbsjsdcb0l","name":"Slab 5","type":"slab","holes":[],"slots":{"surface":"library:preset-nearblack"},"object":"node","polygon":[[-5,-30],[-5,-24],[-10,-24],[-10,-30]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.3,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_3ctxrubeycszmrf8":{"id":"slab_3ctxrubeycszmrf8","name":"Slab 3","type":"slab","holes":[[[14.059982777216987,-27.96279773816207],[11.95998397851817,-27.96504394908807],[11.962176708231645,-30.015042776389297],[14.062175506930462,-30.012796565463297]],[[16.05949161566441,-27.30247492657031],[14.939495402629104,-27.305387448943083],[14.940535589190809,-27.70538609645569],[14.940847645159321,-27.825385690709474],[14.94470381957994,-29.308258676774983],[16.064700032615246,-29.30534615440221],[16.060843858194627,-27.8224731683367],[16.060531802226116,-27.70247357408292]]],"slots":{"surface":"library:flooring-woodparquet76"},"object":"node","polygon":[[-9.915933609008789,13.98099077133405],[-9.915933609008789,-30.01900922866595],[16.08406639099121,-30.053112030029297],[16.08406639099121,13.946887969970703]],"visible":true,"parentId":"level_02mqhbhmfadu3j6g","recessed":false,"elevation":0.15,"thickness":0.05,"holeMetadata":[{"source":"elevator","elevatorId":"elevator_55gh1k39z05j03cs"},{"source":"stair","stairId":"stair_lyv9jl6qrpp3uzqj"}],"autoFromWalls":false},"slab_dh2ne56zlhxtaf8n":{"id":"slab_dh2ne56zlhxtaf8n","name":"Slab 4","type":"slab","holes":[],"slots":{"surface":"library:preset-white"},"object":"node","polygon":[[16,-30],[16,14],[-10,14],[-10,-30]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.15,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_e19xm21md09s7zwh":{"id":"slab_e19xm21md09s7zwh","name":"Slab 11","type":"slab","holes":[],"slots":{"surface":"library:roof-terracottatiles"},"object":"node","polygon":[[-5,-30],[-5,-34],[16,-34],[16,-30]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.3,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_ieeul8ipcehbuzvz":{"id":"slab_ieeul8ipcehbuzvz","name":"Slab 7","type":"slab","holes":[],"slots":{"surface":"library:preset-brickred"},"object":"node","polygon":[[-5,-9.5],[-5,-1],[-10,-1],[-10,-9.5]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.3,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_lmtipqd5dugm5y15":{"id":"slab_lmtipqd5dugm5y15","name":"Slab 10","type":"slab","holes":[],"slots":{"surface":"scene:mat_zax09cyk8xm87cmi"},"object":"node","polygon":[[3.5,-12],[3.5,-7],[10,-7],[10,-12]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.3,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_m4mwszhkkg059eqq":{"id":"slab_m4mwszhkkg059eqq","name":"Slab 14","type":"slab","holes":[],"slots":{"surface":"library:preset-charcoal"},"object":"node","polygon":[[-15,15],[-15,16],[-15,17],[-15,18],[18,18],[18,15]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.3,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_nkpiuz5oa8wz17x1":{"id":"slab_nkpiuz5oa8wz17x1","name":"Slab 12","type":"slab","holes":[],"slots":{"surface":"library:flooring-tile86"},"object":"node","polygon":[[2,-30],[2,-32],[16,-32],[16,-30]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.55,"thickness":0.30000000000000004,"holeMetadata":[],"autoFromWalls":false,"fillToTerrain":true},"slab_pwk9tr2nn2ryo5wx":{"id":"slab_pwk9tr2nn2ryo5wx","name":"Slab 8","type":"slab","holes":[],"slots":{"surface":"scene:mat_6gxbzxjk2mgfkija"},"object":"node","polygon":[[-5,7],[-5,-1],[2.5,-1],[2.5,7]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.3,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_s93u4ogd2xjcigad":{"id":"slab_s93u4ogd2xjcigad","name":"Slab 9","type":"slab","holes":[],"slots":{"surface":"scene:mat_zax09cyk8xm87cmi"},"object":"node","polygon":[[3,-1],[3,7],[10.5,7],[10.5,-1]],"visible":true,"parentId":"level_szqq7obcfp8mvpd5","recessed":false,"elevation":0.3,"thickness":0.05,"holeMetadata":[],"autoFromWalls":false},"slab_ztxxovcvfjju4d7p":{"id":"slab_ztxxovcvfjju4d7p","name":"Slab 6","type":"slab","holes":[],"slots":{"surface":"library:preset-tomato"},"object":"node","polygon":[[8.084066390991211,13.962785549332025],[8.084066390991211,10.946887969970703],[-1.915933609008789,10.962785549332025],[-1.915933609008789,13.962785549332025]],"visible":true,"parentId":"level_02mqhbhmfadu3j6g","recessed":false,"elevation":0.25,"thickness":0.15000000000000002,"holeMetadata":[],"autoFromWalls":false,"fillToTerrain":true},"wall_03dgayu8lgrxiyxa":{"id":"wall_03dgayu8lgrxiyxa","end":[6,-28.5],"name":"Wall 195","type":"wall","slots":{"exterior":"library:preset-white"},"start":[6,-30],"object":"node","visible":true,"backSide":"interior","children":["door_4wo982a4o6opi0rt"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_04av9dno84xeq75y":{"id":"wall_04av9dno84xeq75y","end":[-10,9],"name":"Wall 256","type":"wall","start":[-9.949999809265137,9],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_0hkpe7vsoppipgq2":{"id":"wall_0hkpe7vsoppipgq2","end":[-3.993239689618356,-8.037214450667975],"name":"Wall 40","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-8.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_0mbtav95yncahq5s":{"id":"wall_0mbtav95yncahq5s","end":[12,-19],"name":"Wall 169","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.5,-19],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_0t68qxmzs6bc0l3o":{"id":"wall_0t68qxmzs6bc0l3o","end":[10,-12],"name":"Wall 163","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-12],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_0x86jpede3q4uojx":{"id":"wall_0x86jpede3q4uojx","end":[-10,-16.5],"name":"Wall 132","type":"wall","start":[-9.949999809265137,-16.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_0z8z0ll1429juivu":{"id":"wall_0z8z0ll1429juivu","end":[-4.949999809265137,-19],"name":"Wall 17","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-19],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_156unlha0b3rwxv5":{"id":"wall_156unlha0b3rwxv5","end":[13.5,1.5],"name":"Wall 238","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,4.5],"object":"node","visible":true,"backSide":"unknown","children":["door_jze66v1o4294axex"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_17w05hwf3arabc51":{"id":"wall_17w05hwf3arabc51","end":[16.050000190734863,14],"name":"Wall 4","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[16.050000190734863,-30],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_19mght60o2l76z79":{"id":"wall_19mght60o2l76z79","end":[2.0892350189387727,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[4.089235018938773,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_1f661s29k1apj9us":{"id":"wall_1f661s29k1apj9us","end":[-7,9],"name":"Wall 255","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7,10.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_1gqa1xmrgptloqkw":{"id":"wall_1gqa1xmrgptloqkw","end":[-9.949999809265137,-15],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-13.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_1puqiis34v7aue37":{"id":"wall_1puqiis34v7aue37","end":[16,-17.5],"name":"Wall 172","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.5,-17.5],"object":"node","visible":true,"backSide":"unknown","children":["door_olx32nxcjwyspjha"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_2b0x0fbux7gqvu5o":{"id":"wall_2b0x0fbux7gqvu5o","end":[-9.949999809265137,-12],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-9.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_2pba85cbn90j8gzn":{"id":"wall_2pba85cbn90j8gzn","end":[-10,6],"name":"Wall 149","type":"wall","start":[-9.949999809265137,6],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_2uj1owbj70zqk1to":{"id":"wall_2uj1owbj70zqk1to","end":[16,-32],"name":"Wall 250","type":"wall","slots":{"exterior":"library:preset-glass","interior":"library:preset-glass"},"start":[2,-32],"height":1.5,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_30grjkjqd5fm0d2p":{"id":"wall_30grjkjqd5fm0d2p","end":[16,-20.5],"name":"Wall 175","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.5,-20.5],"object":"node","visible":true,"backSide":"exterior","children":["door_56y209cki0kakrog"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_32mownlyzw2qtltq":{"id":"wall_32mownlyzw2qtltq","end":[-3.993239689618356,-2.0372144506679746],"name":"Wall 46","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-2.0372144506679746],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_39l3sipiqtbh6t2h":{"id":"wall_39l3sipiqtbh6t2h","end":[14.006760310381644,2.9627855493320254],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-0.037214450667974575],"object":"node","visible":true,"backSide":"unknown","children":["door_1510fogkmbpxbswg"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_3c0zjahxfnybvrb7":{"id":"wall_3c0zjahxfnybvrb7","end":[8,-28.5],"name":"Wall 200","type":"wall","slots":{"interior":"library:preset-white"},"start":[8,-27],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_3eoc7nrm3er1l4jw":{"id":"wall_3eoc7nrm3er1l4jw","end":[-7.993239689618356,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-3.993239689618356,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_3gpm7fr6spf026ve":{"id":"wall_3gpm7fr6spf026ve","end":[-3.993239689618356,-5.037214450667975],"name":"Wall 43","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-5.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_3gwugt912xpapy1s":{"id":"wall_3gwugt912xpapy1s","end":[3.5,14],"name":"Wall 210","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3.5,9],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_3l2we30zogpujvx1":{"id":"wall_3l2we30zogpujvx1","end":[-9.949999809265137,-16.5],"name":"Wall 131","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-16.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_3oanrg6njgkpd886":{"id":"wall_3oanrg6njgkpd886","end":[-1.9932396896183562,12.462785549332025],"name":"Wall 385","type":"wall","slots":{"exterior":"library:preset-white"},"start":[-0.9965330018226909,12.472074220873541],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_3ynmp1smp4yt06gk":{"id":"wall_3ynmp1smp4yt06gk","end":[1.0000000000000002,13.962785549332025],"name":"Wall 387","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[1.0000868429864875,12.49068144620753],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_418t4t60vkgyz0x5":{"id":"wall_418t4t60vkgyz0x5","end":[9.5,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[12,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_4isxo8x8msrdp8o3":{"id":"wall_4isxo8x8msrdp8o3","end":[-7,9],"name":"Wall 221","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,9],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_4x296id39l8wufyq":{"id":"wall_4x296id39l8wufyq","end":[-3.993239689618356,0.9627855493320254],"name":"Wall 49","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,0.9627855493320254],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_4zbx30gcmr45ayda":{"id":"wall_4zbx30gcmr45ayda","end":[5.084066390991211,12.446887969970703],"name":"Wall 114","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[5.084066390991211,13.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_509n0cl5nqt2hp6c":{"id":"wall_509n0cl5nqt2hp6c","end":[-9.993239689618356,-30.037214450667975],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-softwhite"},"start":[-9.993239689618356,-22.037214450667975],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_5507z0z4cq7yy6aq":{"id":"wall_5507z0z4cq7yy6aq","end":[1,-15],"name":"Wall 158","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-15],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_55bb10r36ltozu1d":{"id":"wall_55bb10r36ltozu1d","end":[10.006760310381644,2.9627855493320254],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-0.037214450667974575],"object":"node","visible":true,"backSide":"unknown","children":["door_hd27oldvkag50qyb"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_5a2hiidulga7ialk":{"id":"wall_5a2hiidulga7ialk","end":[14.006760310381644,-22.037214450667975],"name":"Wall 52","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[16.006760310381644,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_5ivevoje9s7zj187":{"id":"wall_5ivevoje9s7zj187","end":[14.006760310381644,-9.037214450667975],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-12.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_hu4zz56l5m3opi24"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_5j8gf0m683gw9at5":{"id":"wall_5j8gf0m683gw9at5","end":[-3.993239689618356,0.9627855493320254],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-2.0372144506679746],"object":"node","visible":true,"backSide":"unknown","children":["door_jc4jylzekv2oftf9"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_622stffmpm0dpls5":{"id":"wall_622stffmpm0dpls5","end":[-8,-19],"name":"Wall 17","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-19],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_65k6c1ai7bt3a23y":{"id":"wall_65k6c1ai7bt3a23y","end":[5.0542902733385375,-16.929515049787003],"name":"Wall 259","type":"wall","slots":{"exterior":"library:wood-woodfine22","interior":"library:wood-woodfine22"},"start":[5.0542902733385375,1.0704849502129972],"height":1,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"exterior"},"wall_6bkdw4l4vyqt00uu":{"id":"wall_6bkdw4l4vyqt00uu","end":[2.0892350189387727,10.962785549332025],"name":"Wall 97","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[4.089235018938773,10.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":["door_agk3x89ku16jmsou"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_6e9cniy7878zz8o7":{"id":"wall_6e9cniy7878zz8o7","end":[-9.949999809265137,-9.5],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,3.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_6idg5bc9ouzrma5s":{"id":"wall_6idg5bc9ouzrma5s","end":[6,-27],"name":"Wall 198","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[6,-28.5],"object":"node","visible":true,"backSide":"interior","children":["door_s5fvo04eac5d6svv"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_6r6hglv5en75l2rd":{"id":"wall_6r6hglv5en75l2rd","end":[-5,-30],"name":"Wall 129","type":"wall","start":[-4.949999809265137,-30],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_6rupf7pdmnbx5dxm":{"id":"wall_6rupf7pdmnbx5dxm","end":[13.5,7],"name":"Wall 232","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,9],"object":"node","visible":true,"backSide":"unknown","children":["door_k6licl2utzfzuzjx"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_6ryij8vd37sso8yn":{"id":"wall_6ryij8vd37sso8yn","end":[5,-6],"name":"Wall 247","type":"wall","slots":{"exterior":"library:wood-woodfine2","interior":"library:wood-woodfine2"},"start":[5,-2],"height":1.2,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_6y1t6rg396v7obkc":{"id":"wall_6y1t6rg396v7obkc","end":[4.089235018938773,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[7.084066390991211,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_6y6e4uks55mpdt8c":{"id":"wall_6y6e4uks55mpdt8c","end":[14.006760310381644,-6.037214450667975],"name":"Wall 71","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-6.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_6yki0doy5wtdidxz":{"id":"wall_6yki0doy5wtdidxz","end":[-0.9966198448091781,13.962785549332025],"name":"Wall 394","type":"wall","slots":{"exterior":"library:preset-white"},"start":[0,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_7aov4imwy66vmtax":{"id":"wall_7aov4imwy66vmtax","end":[-5,10.5],"name":"Wall 224","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7,10.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_7c4b0ljl9iaz1iqk":{"id":"wall_7c4b0ljl9iaz1iqk","end":[10.006760310381644,-12.037214450667975],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-15.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_ec6zfwgpd0b6eq45"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_7dyi5zuqb0e6j8ek":{"id":"wall_7dyi5zuqb0e6j8ek","end":[9.5,9],"name":"Wall 205","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[9.5,12.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_7mk8tqvryp4g81aw":{"id":"wall_7mk8tqvryp4g81aw","end":[16,-17.5],"name":"Wall 168","type":"wall","slots":{"interior":"library:preset-white"},"start":[16,-12],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_7toicryz09can4yw":{"id":"wall_7toicryz09can4yw","end":[14.006760310381644,-3.0372144506679746],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-6.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_1wpx57efwlogim0f"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_7yw8js0gfhag433t":{"id":"wall_7yw8js0gfhag433t","end":[16,-26.5],"name":"Wall 188","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.5,-26.5],"object":"node","visible":true,"backSide":"exterior","children":["door_ym7wy7aslkeqwc5s"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_8604tmiumwk7o98q":{"id":"wall_8604tmiumwk7o98q","end":[-3.993239689618356,-14.037214450667975],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-17.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_0p4uk8o2mtg01hdj"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_8agbr0zy65u3momc":{"id":"wall_8agbr0zy65u3momc","end":[8.006760310381644,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[10.006760310381644,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_8b4vwin5avlgghxq":{"id":"wall_8b4vwin5avlgghxq","end":[11,-6],"name":"Wall 244","type":"wall","slots":{"exterior":"library:wood-woodfine2","interior":"library:wood-woodfine2"},"start":[8.5,-6],"height":1.2,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_8f943q80w34y21sy":{"id":"wall_8f943q80w34y21sy","end":[-5,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-0.5,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_8ksgix1e1udocknq":{"id":"wall_8ksgix1e1udocknq","end":[-7,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-5,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_8q570xq30jajpknc":{"id":"wall_8q570xq30jajpknc","end":[-10,-15],"name":"Wall 139","type":"wall","start":[-9.949999809265137,-15],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_9aoyet4u36ousg1c":{"id":"wall_9aoyet4u36ousg1c","end":[-1.9932396896183562,10.962785549332025],"name":"Wall 97","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[2.0892350189387727,10.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":["door_29jy737m2etda24z"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_9eghw3m06og03ss9":{"id":"wall_9eghw3m06og03ss9","end":[13.5,7],"name":"Wall 239","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,7],"object":"node","visible":true,"backSide":"unknown","children":["door_7c0qy514gkbvekpw","window_45z1zf9hncb10109","window_8kllj8r4g23p1bsc","window_g0e9inpqv9ycei10","window_8ip0dggjzcunde4f","window_snon92pb24u98mjx","door_p7mqw5y4k0scw27g"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_9gpdcx9if050sxuo":{"id":"wall_9gpdcx9if050sxuo","end":[-9.949999809265137,9],"name":"Wall 255","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8.5,9],"object":"node","visible":true,"backSide":"unknown","children":["door_fera93ofppuwfggo"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_9lqevl13xue81pjz":{"id":"wall_9lqevl13xue81pjz","end":[14.006760310381644,-0.037214450667974575],"name":"Wall 77","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-0.037214450667974575],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_9ls5sb4ipurh24oa":{"id":"wall_9ls5sb4ipurh24oa","end":[14.006760310381644,-12.037214450667975],"name":"Wall 65","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-12.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_9wrpt556i02d7fmo":{"id":"wall_9wrpt556i02d7fmo","end":[4.089235018938773,10.962785549332025],"name":"Wall 97","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[8.006760310381644,10.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":["door_he4uq5rxpwctemmw"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_9xxe7aklfcy2qlvh":{"id":"wall_9xxe7aklfcy2qlvh","end":[13.5,4.5],"name":"Wall 235","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,6.5],"object":"node","visible":true,"backSide":"unknown","children":["door_qhfgwhvavweqi2bb"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_9zwk9cpeeig7lcfl":{"id":"wall_9zwk9cpeeig7lcfl","end":[-4.949999809265137,-24],"name":"Wall 19","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-4.949999809265137,-19],"object":"node","visible":true,"backSide":"interior","children":["door_r4d4fyjtp1vf3ind"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_a55es2hmgwyb8xuc":{"id":"wall_a55es2hmgwyb8xuc","end":[2.0892350189387727,13.962785549332025],"name":"Wall 100","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[2.0892350189387727,10.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_a9dzy1qkudg5d88w":{"id":"wall_a9dzy1qkudg5d88w","end":[3,-30],"name":"Wall 198","type":"wall","slots":{"interior":"library:preset-white"},"start":[6,-30],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_aoxcrz5ke6025zdw":{"id":"wall_aoxcrz5ke6025zdw","end":[8.006760310381644,12.447195612380893],"name":"Wall 106","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[8.006760310381644,10.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_ayirp3ryb7pcpecl":{"id":"wall_ayirp3ryb7pcpecl","end":[8.5,-6],"name":"Wall 248","type":"wall","slots":{"exterior":"library:wood-woodfine2","interior":"library:wood-woodfine2"},"start":[5,-6],"height":1.2,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_aymusaaum42xkge9":{"id":"wall_aymusaaum42xkge9","end":[-10,-12],"name":"Wall 136","type":"wall","start":[-9.949999809265137,-12],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_b1mxub721ucx0qsw":{"id":"wall_b1mxub721ucx0qsw","end":[10.006760310381644,-18.037214450667975],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_4gqmhova0kql0axj"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_b1sh11q38b6xk7vs":{"id":"wall_b1sh11q38b6xk7vs","end":[-9.993239689618356,-30.037214450667975],"name":"Wall 4","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-softwhite"},"start":[16.006760310381644,-30.037214450667975],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"exterior"},"wall_bc3p0wckzsg2p37t":{"id":"wall_bc3p0wckzsg2p37t","end":[1.0542902733385375,-16.929515049787003],"name":"Wall 261","type":"wall","slots":{"exterior":"library:wood-woodfine22"},"start":[5.0542902733385375,-16.929515049787003],"height":1,"object":"node","visible":true,"backSide":"interior","children":["door_n97lkiscprx1g2tu"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"exterior"},"wall_bjscjn4pk0ehznws":{"id":"wall_bjscjn4pk0ehznws","end":[-9.949999809265137,3.5],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,6],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_blrd670w7782s688":{"id":"wall_blrd670w7782s688","end":[-3.993239689618356,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-1.9932396896183562,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_bltf5l6y2whghxlm":{"id":"wall_bltf5l6y2whghxlm","end":[-5,12],"name":"Wall 227","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7,12],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_bnnq2xjr5bffefog":{"id":"wall_bnnq2xjr5bffefog","end":[-8,-16.5],"name":"Wall 129","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-19],"object":"node","visible":true,"backSide":"exterior","children":["door_ye8dydiulgzypiyj"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_bnojfhbu7aqpkutf":{"id":"wall_bnojfhbu7aqpkutf","end":[1,-13.5],"name":"Wall 151","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[1,-12],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_borgptyhyo8hj6dy":{"id":"wall_borgptyhyo8hj6dy","end":[9.5,12.5],"name":"Wall 205","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[9.5,14],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_brkvlg5w93jav6hr":{"id":"wall_brkvlg5w93jav6hr","end":[-8.5,3.5],"name":"Wall 150","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,3.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_c169x7vx0b1yjsx4":{"id":"wall_c169x7vx0b1yjsx4","end":[-7,10.5],"name":"Wall 255","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7,12],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_c5q0gw0b48oeboc1":{"id":"wall_c5q0gw0b48oeboc1","end":[10.006760310381644,-22.037214450667975],"name":"Wall 52","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_cchblxlo8m27hlha":{"id":"wall_cchblxlo8m27hlha","end":[8.006760310381644,12.447195612380893],"name":"Wall 121","type":"wall","start":[8.084066390991211,12.446887969970703],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_cdwpcphfr1znj3c3":{"id":"wall_cdwpcphfr1znj3c3","end":[16,9],"name":"Wall 221","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,9],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_cf76gd6x4fdw96kc":{"id":"wall_cf76gd6x4fdw96kc","end":[-3.993239689618356,-14.037214450667975],"name":"Wall 34","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-14.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_civert765bk5ynt1":{"id":"wall_civert765bk5ynt1","end":[16,-23.5],"name":"Wall 180","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.5,-23.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_cpxgzih8sc39vmt4":{"id":"wall_cpxgzih8sc39vmt4","end":[-3.993239689618356,-22.037214450667975],"name":"Wall 24","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_cts1uqwd0swjqd0v":{"id":"wall_cts1uqwd0swjqd0v","end":[3,-19],"name":"Wall 165","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10,-19],"object":"node","visible":true,"backSide":"interior","children":["window_kjkf6mu8t247qyr9","window_jx7mn5tnsl9vpgep","door_gg3ttpdq1oo2n9nv"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_cufjhia6cz50pngh":{"id":"wall_cufjhia6cz50pngh","end":[2,-30],"name":"Wall 199","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-30],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_cxbdglvxpk5cpdjl":{"id":"wall_cxbdglvxpk5cpdjl","end":[-4.949999809265137,-26],"name":"Wall 13","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-4.949999809265137,-30],"object":"node","visible":true,"backSide":"interior","children":["window_is6r4pzrb5l6f9bb","window_ot3hpjxq2sjy0vqx"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_cyz17hjy32dfei68":{"id":"wall_cyz17hjy32dfei68","end":[-9.949999809265137,6],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,7],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_d2lkox86xl72aivs":{"id":"wall_d2lkox86xl72aivs","end":[10.006760310381644,13.962785549332025],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,11.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_d57vyvcn5b8vs8tx":{"id":"wall_d57vyvcn5b8vs8tx","end":[-5,-34],"name":"Wall 248","type":"wall","slots":{"exterior":"library:flooring-rusticbrick","interior":"library:flooring-rusticbrick"},"start":[16,-34],"height":1.5,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_d5jzvgzfy8yt3g63":{"id":"wall_d5jzvgzfy8yt3g63","end":[13.5,6.5],"name":"Wall 232","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,7],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_dha7uybg07dlkr68":{"id":"wall_dha7uybg07dlkr68","end":[14.006760310381644,-9.037214450667975],"name":"Wall 68","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-9.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_diorolwov8ydf1x7":{"id":"wall_diorolwov8ydf1x7","end":[3,-19],"name":"Wall 161","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-15],"object":"node","visible":true,"backSide":"interior","children":["door_wghytu8xog8nrpr1"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_dpdh0rzzqz4uxy33":{"id":"wall_dpdh0rzzqz4uxy33","end":[7.084066390991211,12.446887969970703],"name":"Wall 117","type":"wall","slots":{"exterior":"library:preset-white"},"start":[8.006760310381644,12.447195612380893],"object":"node","visible":true,"backSide":"unknown","children":["door_kmp4dcn3hvocs4vj"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_e41q7xdm8i16aq6p":{"id":"wall_e41q7xdm8i16aq6p","end":[16.006760310381644,9.962785549332025],"name":"Wall 4","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-softwhite"},"start":[16.006760310381644,-22.037214450667975],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_e6rh7934u66oyf43":{"id":"wall_e6rh7934u66oyf43","end":[14.006760310381644,-18.037214450667975],"name":"Wall 59","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-18.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_e9mxjb48t84cs9j2":{"id":"wall_e9mxjb48t84cs9j2","end":[16,6.5],"name":"Wall 234","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,6.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_ejveuwbdpe2q9uvx":{"id":"wall_ejveuwbdpe2q9uvx","end":[10.006760310381644,5.962785549332025],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,2.9627855493320254],"object":"node","visible":true,"backSide":"unknown","children":["door_oy3mk5yk568ro4ga"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_ejynry0gowdr7rwq":{"id":"wall_ejynry0gowdr7rwq","end":[6,-27],"name":"Wall 201","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-27],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_eqe9ou8517f0dz0q":{"id":"wall_eqe9ou8517f0dz0q","end":[1,-12],"name":"Wall 150","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-1,-12],"object":"node","visible":true,"backSide":"interior","children":["door_tiqkid55g3q0e7vh"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_ew8kkmf3j4yaj482":{"id":"wall_ew8kkmf3j4yaj482","end":[12,12.5],"name":"Wall 218","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,14],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_f8dd0b053w5y3l8q":{"id":"wall_f8dd0b053w5y3l8q","end":[14.5,-17.5],"name":"Wall 170","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.5,-19],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_fa0wng8sz8fdd05a":{"id":"wall_fa0wng8sz8fdd05a","end":[14.5,-19],"name":"Wall 169","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[16,-19],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_fdo6jlf98v67dmh4":{"id":"wall_fdo6jlf98v67dmh4","end":[1,-17],"name":"Wall 151","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[1,-15],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_fdpfnq8cdbqfux3x":{"id":"wall_fdpfnq8cdbqfux3x","end":[1.0542902733385375,1.0704849502129972],"name":"Wall 262","type":"wall","slots":{"exterior":"library:wood-woodfine22","interior":"library:wood-woodfine22"},"start":[1.0542902733385375,-16.929515049787003],"height":1,"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"exterior"},"wall_fpvt7w7scyip2q9u":{"id":"wall_fpvt7w7scyip2q9u","end":[14.006760310381644,5.962785549332025],"name":"Wall 83","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,5.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_freq10e76fi0qvg6":{"id":"wall_freq10e76fi0qvg6","end":[3,-12],"name":"Wall 153","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[1,-12],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_fv9g4sl0lra823y6":{"id":"wall_fv9g4sl0lra823y6","end":[8.006760310381644,13.962785549332025],"name":"Wall 106","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[8.006760310381644,12.447195612380893],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_fwtf9gx062n2mdol":{"id":"wall_fwtf9gx062n2mdol","end":[1.0542902733385375,1.0704849502129972],"name":"Wall 258","type":"wall","slots":{"exterior":"library:wood-woodfine22","interior":"library:wood-woodfine22"},"start":[5.0542902733385375,1.0704849502129972],"height":1,"object":"node","visible":true,"backSide":"exterior","children":["door_i01iu8wsoo01vonp"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_fy6r367vcb9wh9sj":{"id":"wall_fy6r367vcb9wh9sj","end":[-9.949999809265137,9],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_g2vuodi7efldic0o":{"id":"wall_g2vuodi7efldic0o","end":[12,-20.5],"name":"Wall 176","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-19],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_g3mngz8gpdtkcfrd":{"id":"wall_g3mngz8gpdtkcfrd","end":[-8.5,3.5],"name":"Wall 252","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8.5,7],"object":"node","visible":true,"backSide":"unknown","children":["door_q6jqknbogmk1vrcf"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_g8j2vodr1b0m6f1u":{"id":"wall_g8j2vodr1b0m6f1u","end":[14.5,-23.5],"name":"Wall 183","type":"wall","slots":{"interior":"library:preset-white"},"start":[14.5,-25],"object":"node","visible":true,"backSide":"exterior","children":["door_kb40kb3z7syxl7j6"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_gc9natz9oimfmsvk":{"id":"wall_gc9natz9oimfmsvk","end":[8.006760310381644,12.447195612380893],"name":"Wall 116","type":"wall","start":[8.084066390991211,12.446887969970703],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_ghkk7epi84jv7zeo":{"id":"wall_ghkk7epi84jv7zeo","end":[-9.949999809265137,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-8.5,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_gjo7n6w1er35du6f":{"id":"wall_gjo7n6w1er35du6f","end":[1.0000000000000002,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[2.0892350189387727,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_gq40hq02p2lh7z5y":{"id":"wall_gq40hq02p2lh7z5y","end":[-9.949999809265137,7],"name":"Wall 241","type":"wall","start":[-10,7],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_gsirmpkeyszf0g1l":{"id":"wall_gsirmpkeyszf0g1l","end":[14.006760310381644,-6.037214450667975],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-9.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_jwyfy7vomigipvye"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_gw8mure2jzagm7zq":{"id":"wall_gw8mure2jzagm7zq","end":[-5,12],"name":"Wall 252","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,14],"object":"node","visible":true,"backSide":"unknown","children":["door_ldul0iimmr8t2nph"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_h6qj8vn6ez47afau":{"id":"wall_h6qj8vn6ez47afau","end":[14.5,-25],"name":"Wall 182","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-25],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_h76q5jaz113045zo":{"id":"wall_h76q5jaz113045zo","end":[16.006760310381644,-22.037214450667975],"name":"Wall 4","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-softwhite"},"start":[16.006760310381644,-30.037214450667975],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_h7vfuyuwqd24qxx7":{"id":"wall_h7vfuyuwqd24qxx7","end":[-9.949999809265137,-16.5],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-15],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_h980xzmxbs2tb9if":{"id":"wall_h980xzmxbs2tb9if","end":[-4.949999809265137,-24],"name":"Wall 13","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-4.949999809265137,-26],"object":"node","visible":true,"backSide":"interior","children":["door_1pehz09h02hcxmy3"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_hdhj0g363dvp1al2":{"id":"wall_hdhj0g363dvp1al2","end":[16,-12],"name":"Wall 167","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10,-12],"object":"node","visible":true,"backSide":"exterior","children":["door_5strs0swg8yhvmeg"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_hgcojgwmv43dlhu8":{"id":"wall_hgcojgwmv43dlhu8","end":[14.006760310381644,-15.037214450667975],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-18.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_5wigots5s748hgh4"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_hhyexdx5mg7nz9ha":{"id":"wall_hhyexdx5mg7nz9ha","end":[-5,6],"name":"Wall 244","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,7],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_hmjbmqcsh76a1rsq":{"id":"wall_hmjbmqcsh76a1rsq","end":[8,-28.5],"name":"Wall 196","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[6,-28.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_hqa3dcdj6n8k7p6n":{"id":"wall_hqa3dcdj6n8k7p6n","end":[12,9],"name":"Wall 218","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,12.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_hxcrvaw865d5ild0":{"id":"wall_hxcrvaw865d5ild0","end":[14.5,-23.5],"name":"Wall 180","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-23.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_hzxrpz8a49vhw591":{"id":"wall_hzxrpz8a49vhw591","end":[-1.9932396896183562,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-0.9966198448091781,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_i3j1oukt2gzqqu0u":{"id":"wall_i3j1oukt2gzqqu0u","end":[12,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[16.050000190734863,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_i3qgou8wi6cf65d2":{"id":"wall_i3qgou8wi6cf65d2","end":[-3.993239689618356,-5.037214450667975],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-8.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_f4ji55j0mu131m7l"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_iaphrfbh2yypg6xx":{"id":"wall_iaphrfbh2yypg6xx","end":[-5,-12],"name":"Wall 146","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,-17],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_icw0rtlla0ie4gm7":{"id":"wall_icw0rtlla0ie4gm7","end":[10.006760310381644,-3.0372144506679746],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-6.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_cs9nej88jbdw6rer"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_iqhsxsr9nubkz10l":{"id":"wall_iqhsxsr9nubkz10l","end":[14.006760310381644,8.962785549332025],"name":"Wall 86","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,8.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_irhkb0sv85l5gx3f":{"id":"wall_irhkb0sv85l5gx3f","end":[14.006760310381644,-18.037214450667975],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_lilrbl7kmnlfsegs"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_ixvriacrrxomcgl5":{"id":"wall_ixvriacrrxomcgl5","end":[-4.949999809265137,-26],"name":"Wall 124","type":"wall","start":[-5,-26],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_j4dy3pftqgz5pu4g":{"id":"wall_j4dy3pftqgz5pu4g","end":[14.006760310381644,-0.037214450667974575],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-3.0372144506679746],"object":"node","visible":true,"backSide":"unknown","children":["door_neqzzmhubk6ral29","door_z15l3658qaw6tsyj"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_jgyqeg0ysh723o1u":{"id":"wall_jgyqeg0ysh723o1u","end":[-9.949999809265137,7],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,9],"object":"node","visible":true,"backSide":"exterior","children":["door_vojcho42907qrgln"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_jkmyzfrtgg8gxepu":{"id":"wall_jkmyzfrtgg8gxepu","end":[14.5,-25],"name":"Wall 187","type":"wall","slots":{"interior":"library:preset-white"},"start":[14.5,-26.5],"object":"node","visible":true,"backSide":"exterior","children":["door_q5t8kaabv2k2g3rt"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_jn5660h3jdh8cc50":{"id":"wall_jn5660h3jdh8cc50","end":[16.006760310381644,9.962785549332025],"name":"Wall 95","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,9.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_k3c46cb7vgagz961":{"id":"wall_k3c46cb7vgagz961","end":[5,-2],"name":"Wall 246","type":"wall","slots":{"exterior":"library:wood-woodfine2","interior":"library:wood-woodfine2"},"start":[11,-2],"height":1.2,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_k3gl1lshy5x20tvx":{"id":"wall_k3gl1lshy5x20tvx","end":[-2,-30],"name":"Wall 127","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-2,-26],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_kbh90jfj93hc1kfh":{"id":"wall_kbh90jfj93hc1kfh","end":[10,-19],"name":"Wall 169","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-19],"object":"node","visible":true,"backSide":"interior","children":["door_lhph8ow3u9akye73"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_kxiogrvlnpxtt70g":{"id":"wall_kxiogrvlnpxtt70g","end":[10.006760310381644,-9.037214450667975],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-12.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_ecsxump5i94bh1gf"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_kyler2w087cymm31":{"id":"wall_kyler2w087cymm31","end":[16,-32],"name":"Wall 251","type":"wall","slots":{"exterior":"library:flooring-rusticbrick","interior":"library:flooring-rusticbrick"},"start":[16,-30],"height":1.2,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_li90yamosae8uksx":{"id":"wall_li90yamosae8uksx","end":[-8,-13.5],"name":"Wall 134","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-15],"object":"node","visible":true,"backSide":"exterior","children":["door_q2jawtp9vao8w07z"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_lji3yh2z31t3mzlv":{"id":"wall_lji3yh2z31t3mzlv","end":[14.006760310381644,-15.037214450667975],"name":"Wall 62","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-15.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_llonzondn9vvw3i0":{"id":"wall_llonzondn9vvw3i0","end":[-5,-9.5],"name":"Wall 147","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-9.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_lly71o1pxp7g9e2a":{"id":"wall_lly71o1pxp7g9e2a","end":[14.006760310381644,2.9627855493320254],"name":"Wall 80","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,2.9627855493320254],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_lxxf7sq8az8o0qjd":{"id":"wall_lxxf7sq8az8o0qjd","end":[14.5,-20.5],"name":"Wall 178","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-20.5],"object":"node","visible":true,"backSide":"exterior","children":["door_9c6l98te9qk01405"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_m989lls0un8omdfr":{"id":"wall_m989lls0un8omdfr","end":[-3.993239689618356,13.962785549332025],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,0.9627855493320254],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_mdeo7dk2iippkqw4":{"id":"wall_mdeo7dk2iippkqw4","end":[2,-27],"name":"Wall 193","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[2,-30],"object":"node","visible":true,"backSide":"interior","children":["door_axwmc3besbu7971v"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_mg2gv6cauha4jq4f":{"id":"wall_mg2gv6cauha4jq4f","end":[16,1.5],"name":"Wall 239","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,1.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_mkxnh287pbtbi7ko":{"id":"wall_mkxnh287pbtbi7ko","end":[16.006760310381644,13.962785549332025],"name":"Wall 4","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-softwhite"},"start":[16.006760310381644,11.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_mvotlhfkqh8o4a2w":{"id":"wall_mvotlhfkqh8o4a2w","end":[16.006760310381644,11.962785549332025],"name":"Wall 4","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-softwhite"},"start":[16.006760310381644,9.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_mygsq6yc4p4501l0":{"id":"wall_mygsq6yc4p4501l0","end":[1,-13.5],"name":"Wall 155","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-13.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_n2f0hm0z8c5q6ebg":{"id":"wall_n2f0hm0z8c5q6ebg","end":[16,-19],"name":"Wall 168","type":"wall","slots":{"interior":"library:preset-white"},"start":[16,-17.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_n3tgmdviiki18uvf":{"id":"wall_n3tgmdviiki18uvf","end":[-5,7],"name":"Wall 242","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8.5,7],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_n3utm8hhpirj4pls":{"id":"wall_n3utm8hhpirj4pls","end":[3.5,9],"name":"Wall 209","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[9.5,9],"object":"node","visible":true,"backSide":"unknown","children":["door_rtmq7vo2qr2m2lt3"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_n5xo0waz2nvf1syi":{"id":"wall_n5xo0waz2nvf1syi","end":[10,-19],"name":"Wall 164","type":"wall","slots":{"interior":"library:preset-white"},"start":[10,-12],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_n88j2lwd0biz6xan":{"id":"wall_n88j2lwd0biz6xan","end":[-5,-12],"name":"Wall 149","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,-9.5],"object":"node","visible":true,"backSide":"interior","children":["door_o9bejhalxuoidt0q"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_ndhirrjyogpjhevr":{"id":"wall_ndhirrjyogpjhevr","end":[-9.949999809265137,-19],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-16.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_njrjc5o9wdhh4zem":{"id":"wall_njrjc5o9wdhh4zem","end":[-9.949999809265137,-15],"name":"Wall 138","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-15],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_nko9dtr7yv473c1h":{"id":"wall_nko9dtr7yv473c1h","end":[-7,12],"name":"Wall 255","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7,14],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_nqh20fhwmkyf6ehd":{"id":"wall_nqh20fhwmkyf6ehd","end":[-0.5,9],"name":"Wall 212","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3.5,9],"object":"node","visible":true,"backSide":"unknown","children":["door_iffg9fg71j83tupg"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_oc2ab4wnh08rhebl":{"id":"wall_oc2ab4wnh08rhebl","end":[-8.5,9],"name":"Wall 221","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7,9],"object":"node","visible":true,"backSide":"unknown","children":["door_37prr4ilofnfjugg"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_oequsc9dr33hj2q3":{"id":"wall_oequsc9dr33hj2q3","end":[10.006760310381644,11.962785549332025],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,9.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_oia7xpjw709r6v8e":{"id":"wall_oia7xpjw709r6v8e","end":[1,-15],"name":"Wall 151","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[1,-13.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_ojjtbzpnrs2vikvi":{"id":"wall_ojjtbzpnrs2vikvi","end":[-5,9],"name":"Wall 254","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,10.5],"object":"node","visible":true,"backSide":"unknown","children":["door_urxziuc80iv9gst5"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_osfzli0fedpyrecg":{"id":"wall_osfzli0fedpyrecg","end":[14.006760310381644,5.962785549332025],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,2.9627855493320254],"object":"node","visible":true,"backSide":"unknown","children":["door_t3u7urqslu4kgwpr"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_owi6yxawiyxcix0c":{"id":"wall_owi6yxawiyxcix0c","end":[-7.993239689618356,-2.0372144506679746],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-5.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_mn9mipu04l4z6m1h"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_oyxidchtw8vujl86":{"id":"wall_oyxidchtw8vujl86","end":[3,-27],"name":"Wall 194","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[2,-27],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_oze1nfdlbzkz0e4m":{"id":"wall_oze1nfdlbzkz0e4m","end":[-9.949999809265137,-24],"name":"Wall 15","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-4.949999809265137,-24],"object":"node","visible":true,"backSide":"interior","children":["door_irjcehzgjuznvt0y"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_ozp5qrq19kn4dlbb":{"id":"wall_ozp5qrq19kn4dlbb","end":[3,-13.5],"name":"Wall 154","type":"wall","slots":{"interior":"library:preset-white"},"start":[3,-12],"object":"node","visible":true,"backSide":"interior","children":["door_j0v5zmjxjdbwy1jv"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_p0828lqrh2r3nr2a":{"id":"wall_p0828lqrh2r3nr2a","end":[-0.5,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[3.5,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_pi579mt1hwpuinby":{"id":"wall_pi579mt1hwpuinby","end":[-3.993239689618356,-11.037214450667975],"name":"Wall 37","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-11.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_pippbsum1g55qje8":{"id":"wall_pippbsum1g55qje8","end":[10.006760310381644,-15.037214450667975],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-18.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_spxj5621quc0z56i"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_pjifzy5o7vmnfz0f":{"id":"wall_pjifzy5o7vmnfz0f","end":[14.5,-20.5],"name":"Wall 174","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.5,-19],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_pumsyipf7tg885f8":{"id":"wall_pumsyipf7tg885f8","end":[8,-30],"name":"Wall 197","type":"wall","slots":{"interior":"library:preset-white"},"start":[8,-28.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_pzlinyuc64bq91h2":{"id":"wall_pzlinyuc64bq91h2","end":[-8,-12],"name":"Wall 150","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,-12],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_q4dfvlsn9mxcvhqq":{"id":"wall_q4dfvlsn9mxcvhqq","end":[-7.993239689618356,-17.037214450667975],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_8vo31r77oiwgy7oc"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_qgdbdrcxaluy8i4r":{"id":"wall_qgdbdrcxaluy8i4r","end":[-3.993239689618356,-2.0372144506679746],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-5.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_78qhi3j00zk3t684"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_qnw8polrxuhgqpvr":{"id":"wall_qnw8polrxuhgqpvr","end":[-5,6],"name":"Wall 147","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,3.5],"object":"node","visible":true,"backSide":"exterior","children":["door_gp47gs2mp6cog4g5","door_jwetbmo8qbumfarm"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_r46l3f71jrrib8we":{"id":"wall_r46l3f71jrrib8we","end":[12,-25],"name":"Wall 181","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-23.5],"object":"node","visible":true,"backSide":"exterior","children":["window_4j6w6fol2nczizc4"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_r4erjxgaoht8ivbo":{"id":"wall_r4erjxgaoht8ivbo","end":[12,9],"name":"Wall 207","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[9.5,9],"object":"node","visible":true,"backSide":"unknown","children":["door_w2akyb93e3pdwml1"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_r7yk9vxka9v6snv6":{"id":"wall_r7yk9vxka9v6snv6","end":[-8,-13.5],"name":"Wall 144","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-13.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_rf65f8a3lskp2jd5":{"id":"wall_rf65f8a3lskp2jd5","end":[-9.993239689618356,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-7.993239689618356,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_rfylr5kw4pht6wj9":{"id":"wall_rfylr5kw4pht6wj9","end":[-0.9965330018226909,12.472074220873541],"name":"Wall 396","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-0.9966198448091781,13.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_riobr13j4lpcqr2t":{"id":"wall_riobr13j4lpcqr2t","end":[-0.9965330018226909,12.472074220873541],"name":"Wall 385","type":"wall","slots":{"exterior":"library:preset-white"},"start":[0.00017368597297473531,12.481362892415058],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_rkoharc4e658f336":{"id":"wall_rkoharc4e658f336","end":[-1.9932396896183562,12.462785549332025],"name":"Wall 98","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-1.9932396896183562,10.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_rmadylryovksial6":{"id":"wall_rmadylryovksial6","end":[-9.949999809265137,-13.5],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-12],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_rnrpcgffh8lgpy1g":{"id":"wall_rnrpcgffh8lgpy1g","end":[-10,3.5],"name":"Wall 151","type":"wall","start":[-9.949999809265137,3.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_ro9c1n3spaxahes3":{"id":"wall_ro9c1n3spaxahes3","end":[-7.993239689618356,-22.037214450667975],"name":"Wall 24","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.993239689618356,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_mpe3rqu7r8rd9861"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_rqconmkpc5jnb0qs":{"id":"wall_rqconmkpc5jnb0qs","end":[12,12.5],"name":"Wall 229","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[9.5,12.5],"object":"node","visible":true,"backSide":"unknown","children":["door_1o581ox68r66i89m"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_rykm64hx2dm6nhwc":{"id":"wall_rykm64hx2dm6nhwc","end":[4.089235018938773,12.462785549332025],"name":"Wall 118","type":"wall","slots":{"exterior":"library:preset-white"},"start":[7.084066390991211,12.446887969970703],"object":"node","visible":true,"backSide":"unknown","children":["door_scyjkkzoaq2grxsm","door_5q90ypuvi7ptdfhh","door_0g3mpcsceqcx16gu"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_s2dh90w8vag0exb9":{"id":"wall_s2dh90w8vag0exb9","end":[-5,-1],"name":"Wall 147","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,3.5],"object":"node","visible":true,"backSide":"unknown","children":["window_tmud56rp2kiiclm3","window_6awly60ibve0sjix"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_s5awja53jjxtb1x1":{"id":"wall_s5awja53jjxtb1x1","end":[3,-15],"name":"Wall 157","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-13.5],"object":"node","visible":true,"backSide":"interior","children":["door_ce1jq0k8tk8dliqb"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_s5hvtbsu2dlrsbd3":{"id":"wall_s5hvtbsu2dlrsbd3","end":[14.006760310381644,8.962785549332025],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,5.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":["door_aouf01v6q0qks5ga"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_s74w7tigftf9y3em":{"id":"wall_s74w7tigftf9y3em","end":[3,-20],"name":"Wall 161","type":"wall","slots":{"interior":"library:preset-white"},"start":[3,-19],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_segqfvt40il5xzeb":{"id":"wall_segqfvt40il5xzeb","end":[-7.993239689618356,13.962785549332025],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,0.9627855493320254],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_sjfysyqic6d8r1py":{"id":"wall_sjfysyqic6d8r1py","end":[-0.5,14],"name":"Wall 213","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-0.5,9],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_smf3bj8g583r35l1":{"id":"wall_smf3bj8g583r35l1","end":[14.006760310381644,-12.037214450667975],"name":"Wall 56","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[14.006760310381644,-15.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_kl3ij2xc7qdsw6v6"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_smgsy357zos4jxe8":{"id":"wall_smgsy357zos4jxe8","end":[4.089235018938773,12.462785549332025],"name":"Wall 103","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[4.089235018938773,10.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_su3nuifb83eublyz":{"id":"wall_su3nuifb83eublyz","end":[7.084066390991211,12.446887969970703],"name":"Wall 114","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[7.084066390991211,13.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_tix1upkklo1dmv8d":{"id":"wall_tix1upkklo1dmv8d","end":[14.006760310381644,-3.0372144506679746],"name":"Wall 74","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-3.0372144506679746],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_tjs0pwclvjz1v3l6":{"id":"wall_tjs0pwclvjz1v3l6","end":[-3.993239689618356,-8.037214450667975],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-11.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_d5hl24xrf12lepmg"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_tm0i0ysimmph04rl":{"id":"wall_tm0i0ysimmph04rl","end":[-2,-26],"name":"Wall 125","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-4.949999809265137,-26],"object":"node","visible":true,"backSide":"interior","children":["door_sq8hp4cr91hok7yt"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_tncpwgujsrh2i65b":{"id":"wall_tncpwgujsrh2i65b","end":[0,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[1.0000000000000002,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_toxbmd6cb2wgjbja":{"id":"wall_toxbmd6cb2wgjbja","end":[-7.993239689618356,-17.037214450667975],"name":"Wall 31","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-17.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_ttgx9y48uctgv7sq":{"id":"wall_ttgx9y48uctgv7sq","end":[-9.949999809265137,-9.5],"name":"Wall 146","type":"wall","start":[-10,-9.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_u19kku3mv03ycdvd":{"id":"wall_u19kku3mv03ycdvd","end":[3.5,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[9.5,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_u8fplakcq6b46wky":{"id":"wall_u8fplakcq6b46wky","end":[14.5,-26.5],"name":"Wall 186","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-26.5],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_ud7h4x32zadba63f":{"id":"wall_ud7h4x32zadba63f","end":[-0.9966198448091781,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[0,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_uiehox3xso0k9fov":{"id":"wall_uiehox3xso0k9fov","end":[0,13.962785549332025],"name":"Wall 392","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[0.00017368597297473531,12.481362892415058],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown","supportSlabId":"slab_ztxxovcvfjju4d7p"},"wall_uiot6sscz83a7tta":{"id":"wall_uiot6sscz83a7tta","end":[10.006760310381644,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[16.006760310381644,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_uk2g421te2nctyjf":{"id":"wall_uk2g421te2nctyjf","end":[3,-30],"name":"Wall 192","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[6,-30],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_uljdllftb6z39995":{"id":"wall_uljdllftb6z39995","end":[-4.949999809265137,-30],"name":"Wall 128","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-2,-30],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_uooeq9wvxqpztqok":{"id":"wall_uooeq9wvxqpztqok","end":[-8.5,14],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-7,14],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_usesryb82wccunsb":{"id":"wall_usesryb82wccunsb","end":[6,-30],"name":"Wall 198","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[8,-30],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_uxv2jcmhybxx3q0u":{"id":"wall_uxv2jcmhybxx3q0u","end":[-1,-17],"name":"Wall 148","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-1,-12],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_v7sqna940vejd3a9":{"id":"wall_v7sqna940vejd3a9","end":[-3.993239689618356,-11.037214450667975],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-14.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_089qgnv8i5o4v4zz"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_vavj30weul8onfri":{"id":"wall_vavj30weul8onfri","end":[-1,-17],"name":"Wall 152","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[1,-17],"object":"node","visible":true,"backSide":"interior","children":["door_ben1fuvhpvu4nc3e"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_vcezz72u4682ed5o":{"id":"wall_vcezz72u4682ed5o","end":[10.006760310381644,-6.037214450667975],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-9.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_ic6la3eo1ci04d94"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_vfqiv2dmhhfthgaz":{"id":"wall_vfqiv2dmhhfthgaz","end":[16.006760310381644,11.962785549332025],"name":"Wall 89","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,11.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_vjb1olb1o2h03zcc":{"id":"wall_vjb1olb1o2h03zcc","end":[-7.993239689618356,-8.037214450667975],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-11.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_om6xc8x8ins72scd"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_vl9jchthqec7fhfs":{"id":"wall_vl9jchthqec7fhfs","end":[-1,-12],"name":"Wall 147","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,-12],"object":"node","visible":true,"backSide":"interior","children":["door_ui26uat5g1308msz","window_2rk6cm7ej9bbbtn1"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_vldc7zbyt6fwupwb":{"id":"wall_vldc7zbyt6fwupwb","end":[-8.5,7],"name":"Wall 242","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,7],"object":"node","visible":true,"backSide":"unknown","children":["door_n3wkniv2zhmwd6mn"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_vlwi9f21kz46pzxx":{"id":"wall_vlwi9f21kz46pzxx","end":[6.084066390991211,12.446887969970703],"name":"Wall 114","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[6.084066390991211,13.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_vo1x2v1vdyn8mh59":{"id":"wall_vo1x2v1vdyn8mh59","end":[0.00017368597297473531,12.481362892415058],"name":"Wall 385","type":"wall","slots":{"exterior":"library:preset-white"},"start":[1.0000868429864875,12.49068144620753],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_w6sn8eqrit5h3f0z":{"id":"wall_w6sn8eqrit5h3f0z","end":[-8.5,14],"name":"Wall 222","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8.5,9],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_wa8f2ip8fz03p354":{"id":"wall_wa8f2ip8fz03p354","end":[16,-34],"name":"Wall 252","type":"wall","slots":{"exterior":"library:flooring-rusticbrick","interior":"library:flooring-rusticbrick"},"start":[16,-32],"height":1.5,"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_wcbhs987y1cqzyz1":{"id":"wall_wcbhs987y1cqzyz1","end":[-5,9],"name":"Wall 215","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-0.5,9],"object":"node","visible":true,"backSide":"unknown","children":["door_mx6zqm9wibnmyckh"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_wm5b95419hy24eih":{"id":"wall_wm5b95419hy24eih","end":[-8,-12],"name":"Wall 134","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-13.5],"object":"node","visible":true,"backSide":"exterior","children":["door_hzwjtbi37to0zjvd"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_wo5xu17eg7v8cguy":{"id":"wall_wo5xu17eg7v8cguy","end":[13.5,9],"name":"Wall 221","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,9],"object":"node","visible":true,"backSide":"unknown","children":["door_o1xwx6m71v10el5a"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_wplz7ck66d2kzd05":{"id":"wall_wplz7ck66d2kzd05","end":[16,4.5],"name":"Wall 236","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[13.5,4.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_wvyz5cq7vao7d4gs":{"id":"wall_wvyz5cq7vao7d4gs","end":[10.006760310381644,-0.037214450667974575],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,-3.0372144506679746],"object":"node","visible":true,"backSide":"unknown","children":["door_gd2kn1ehsue66olv"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_x1rlai8ex29tez4y":{"id":"wall_x1rlai8ex29tez4y","end":[10.006760310381644,8.962785549332025],"name":"Wall 54","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[10.006760310381644,5.962785549332025],"object":"node","visible":true,"backSide":"unknown","children":["door_qkln7lmdessf4ljs"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_x682d6mb8akntu7e":{"id":"wall_x682d6mb8akntu7e","end":[-9.949999809265137,-13.5],"name":"Wall 143","type":"wall","start":[-10,-13.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_xa97civ0by5jjzbu":{"id":"wall_xa97civ0by5jjzbu","end":[-5,10.5],"name":"Wall 253","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-5,12],"object":"node","visible":true,"backSide":"unknown","children":["door_ktq2nnb7j6wjesdv"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"unknown"},"wall_xaqp0l73ngc4ul4e":{"id":"wall_xaqp0l73ngc4ul4e","end":[-9.949999809265137,-12],"name":"Wall 135","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-12],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_xdydh5jq5fkrtclh":{"id":"wall_xdydh5jq5fkrtclh","end":[1.0000868429864875,12.49068144620753],"name":"Wall 385","type":"wall","slots":{"exterior":"library:preset-white"},"start":[2,12.5],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_xfu9q2fm0ev5gbyu":{"id":"wall_xfu9q2fm0ev5gbyu","end":[-7.993239689618356,-14.037214450667975],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-17.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_svd6is1978dxr6g1"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_xnpxaeiusfig43z2":{"id":"wall_xnpxaeiusfig43z2","end":[-7.993239689618356,-5.037214450667975],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-8.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_ql2q26c3kcna4q1z"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_xpcjvni8vqbxkaiz":{"id":"wall_xpcjvni8vqbxkaiz","end":[-7.993239689618356,0.9627855493320254],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-2.0372144506679746],"object":"node","visible":true,"backSide":"unknown","children":["door_y14nk1zgj1wytjgn"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_xqgm29iyqdyd70wz":{"id":"wall_xqgm29iyqdyd70wz","end":[-5,-17],"name":"Wall 149","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-1,-17],"object":"node","visible":true,"backSide":"interior","children":["door_llj8iidkroor0kvv","window_5wpah8vmarylko5t"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_xt90bswwx7nzngn8":{"id":"wall_xt90bswwx7nzngn8","end":[-8,-15],"name":"Wall 134","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8,-16.5],"object":"node","visible":true,"backSide":"exterior","children":["door_3e1hdwt3dkpws3da"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_xu5u077s4jsdvdlw":{"id":"wall_xu5u077s4jsdvdlw","end":[8,-27],"name":"Wall 199","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[6,-27],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_xx9n2s5g6hbtaab6":{"id":"wall_xx9n2s5g6hbtaab6","end":[1,-20],"name":"Wall 162","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[3,-20],"object":"node","visible":true,"backSide":"interior","children":["window_l5d1o9eeih5lo0j0"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_y6h0lb7k7bgb9hdm":{"id":"wall_y6h0lb7k7bgb9hdm","end":[7.084066390991211,13.962785549332025],"name":"Wall 2","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[8.006760310381644,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_yb83a7iz9r5itw0q":{"id":"wall_yb83a7iz9r5itw0q","end":[-3.993239689618356,-17.037214450667975],"name":"Wall 26","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-3.993239689618356,-22.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_56f2pwru4mhoc4bq"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_ygjk7e9eqhyi0k5n":{"id":"wall_ygjk7e9eqhyi0k5n","end":[-1.9932396896183562,13.962785549332025],"name":"Wall 98","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-1.9932396896183562,12.462785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_ypopo41vqxne73ub":{"id":"wall_ypopo41vqxne73ub","end":[4.089235018938773,13.962785549332025],"name":"Wall 103","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[4.089235018938773,12.462785549332025],"object":"node","visible":true,"backSide":"unknown","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_z2v3et83odg65v4n":{"id":"wall_z2v3et83odg65v4n","end":[-9.993239689618356,-22.037214450667975],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-softwhite","interior":"library:preset-white"},"start":[-9.993239689618356,13.962785549332025],"object":"node","visible":true,"backSide":"exterior","children":[],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"interior"},"wall_zq9nlb20ez1k3h4h":{"id":"wall_zq9nlb20ez1k3h4h","end":[12,-26.5],"name":"Wall 185","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-25],"object":"node","visible":true,"backSide":"exterior","children":["window_pejp73vpvoctrzno"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_zr8loqrq610daiw5":{"id":"wall_zr8loqrq610daiw5","end":[-9.949999809265137,3.5],"name":"Wall 150","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-8.5,3.5],"object":"node","visible":true,"backSide":"interior","children":[],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_zr8vtxrraazbn4ju":{"id":"wall_zr8vtxrraazbn4ju","end":[1,-17],"name":"Wall 163","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[1,-20],"object":"node","visible":true,"backSide":"interior","children":["door_wqsnb8raham18y8n"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"exterior"},"wall_ztozr0y2y9c8uqc0":{"id":"wall_ztozr0y2y9c8uqc0","end":[-7.993239689618356,-11.037214450667975],"name":"Wall 28","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-7.993239689618356,-14.037214450667975],"object":"node","visible":true,"backSide":"unknown","children":["door_0c6hxq4hvklgxx4o"],"parentId":"level_02mqhbhmfadu3j6g","frontSide":"unknown"},"wall_zxuckkxr599dyb05":{"id":"wall_zxuckkxr599dyb05","end":[12,-23.5],"name":"Wall 179","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[12,-20.5],"object":"node","visible":true,"backSide":"exterior","children":["door_dd9w4uwavt7q2hdg","window_la38t2n2qoonghi0"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"wall_zxzx7h2iw58a6muu":{"id":"wall_zxzx7h2iw58a6muu","end":[-9.949999809265137,-24],"name":"Wall 3","type":"wall","slots":{"exterior":"library:preset-white","interior":"library:preset-white"},"start":[-9.949999809265137,-19],"object":"node","visible":true,"backSide":"exterior","children":["door_87k8yh4na244zvfd"],"parentId":"level_szqq7obcfp8mvpd5","frontSide":"interior"},"level_02mqhbhmfadu3j6g":{"id":"level_02mqhbhmfadu3j6g","name":"Level A","type":"level","level":1,"height":3,"object":"node","visible":true,"children":["wall_b1sh11q38b6xk7vs","stair_600flkqcrkku2m8q","wall_z2v3et83odg65v4n","wall_509n0cl5nqt2hp6c","wall_ro9c1n3spaxahes3","wall_cpxgzih8sc39vmt4","wall_3eoc7nrm3er1l4jw","wall_rf65f8a3lskp2jd5","wall_yb83a7iz9r5itw0q","wall_q4dfvlsn9mxcvhqq","wall_toxbmd6cb2wgjbja","wall_xfu9q2fm0ev5gbyu","wall_8604tmiumwk7o98q","wall_cf76gd6x4fdw96kc","wall_ztozr0y2y9c8uqc0","wall_v7sqna940vejd3a9","wall_pi579mt1hwpuinby","wall_vjb1olb1o2h03zcc","wall_tjs0pwclvjz1v3l6","wall_0hkpe7vsoppipgq2","wall_xnpxaeiusfig43z2","wall_i3qgou8wi6cf65d2","wall_3gpm7fr6spf026ve","wall_owi6yxawiyxcix0c","wall_qgdbdrcxaluy8i4r","wall_32mownlyzw2qtltq","wall_xpcjvni8vqbxkaiz","wall_segqfvt40il5xzeb","wall_5j8gf0m683gw9at5","wall_m989lls0un8omdfr","wall_4x296id39l8wufyq","wall_h76q5jaz113045zo","wall_5a2hiidulga7ialk","wall_c5q0gw0b48oeboc1","wall_uiot6sscz83a7tta","wall_b1mxub721ucx0qsw","wall_irhkb0sv85l5gx3f","wall_e6rh7934u66oyf43","wall_pippbsum1g55qje8","wall_hgcojgwmv43dlhu8","wall_lji3yh2z31t3mzlv","wall_7c4b0ljl9iaz1iqk","wall_smf3bj8g583r35l1","wall_9ls5sb4ipurh24oa","wall_kxiogrvlnpxtt70g","wall_5ivevoje9s7zj187","wall_dha7uybg07dlkr68","wall_vcezz72u4682ed5o","wall_gsirmpkeyszf0g1l","wall_6y6e4uks55mpdt8c","wall_icw0rtlla0ie4gm7","wall_7toicryz09can4yw","wall_tix1upkklo1dmv8d","wall_wvyz5cq7vao7d4gs","wall_j4dy3pftqgz5pu4g","wall_9lqevl13xue81pjz","wall_55bb10r36ltozu1d","wall_39l3sipiqtbh6t2h","wall_lly71o1pxp7g9e2a","wall_ejveuwbdpe2q9uvx","wall_osfzli0fedpyrecg","wall_fpvt7w7scyip2q9u","wall_x1rlai8ex29tez4y","wall_s5hvtbsu2dlrsbd3","wall_iqhsxsr9nubkz10l","wall_d2lkox86xl72aivs","wall_vfqiv2dmhhfthgaz","wall_oequsc9dr33hj2q3","wall_e41q7xdm8i16aq6p","wall_jn5660h3jdh8cc50","wall_mvotlhfkqh8o4a2w","wall_mkxnh287pbtbi7ko","wall_blrd670w7782s688","wall_9wrpt556i02d7fmo","wall_6bkdw4l4vyqt00uu","wall_19mght60o2l76z79","wall_8agbr0zy65u3momc","wall_a55es2hmgwyb8xuc","slab_3ctxrubeycszmrf8","wall_9aoyet4u36ousg1c","wall_y6h0lb7k7bgb9hdm","wall_6y1t6rg396v7obkc","wall_su3nuifb83eublyz","wall_smgsy357zos4jxe8","wall_ypopo41vqxne73ub","wall_aoxcrz5ke6025zdw","wall_fv9g4sl0lra823y6","wall_gc9natz9oimfmsvk","wall_dpdh0rzzqz4uxy33","wall_rykm64hx2dm6nhwc","wall_cchblxlo8m27hlha","wall_vlwi9f21kz46pzxx","wall_4zbx30gcmr45ayda","slab_ztxxovcvfjju4d7p","wall_fwtf9gx062n2mdol","wall_65k6c1ai7bt3a23y","wall_bc3p0wckzsg2p37t","wall_fdpfnq8cdbqfux3x","wall_rkoharc4e658f336","wall_ygjk7e9eqhyi0k5n","wall_xdydh5jq5fkrtclh","wall_gjo7n6w1er35du6f","wall_3ynmp1smp4yt06gk","wall_vo1x2v1vdyn8mh59","wall_tncpwgujsrh2i65b","wall_uiehox3xso0k9fov","wall_ud7h4x32zadba63f","wall_hzxrpz8a49vhw591","wall_6yki0doy5wtdidxz","wall_riobr13j4lpcqr2t","wall_3oanrg6njgkpd886","wall_rfylr5kw4pht6wj9"],"parentId":"building_e7p75atkqjiu2t6m","baseElevation":0},"level_szqq7obcfp8mvpd5":{"id":"level_szqq7obcfp8mvpd5","name":"Level B","type":"level","level":0,"height":3,"object":"node","visible":true,"children":["ceiling_86uq44bc5ysakhyf","stair_lyv9jl6qrpp3uzqj","wall_oze1nfdlbzkz0e4m","wall_zxzx7h2iw58a6muu","wall_9zwk9cpeeig7lcfl","slab_dh2ne56zlhxtaf8n","slab_21t1rgwbsjsdcb0l","wall_17w05hwf3arabc51","wall_cxbdglvxpk5cpdjl","wall_h980xzmxbs2tb9if","wall_ixvriacrrxomcgl5","wall_tm0i0ysimmph04rl","wall_k3gl1lshy5x20tvx","wall_uljdllftb6z39995","wall_6r6hglv5en75l2rd","wall_622stffmpm0dpls5","wall_bnnq2xjr5bffefog","wall_ndhirrjyogpjhevr","wall_0x86jpede3q4uojx","wall_3l2we30zogpujvx1","wall_xaqp0l73ngc4ul4e","wall_aymusaaum42xkge9","wall_xt90bswwx7nzngn8","wall_h7vfuyuwqd24qxx7","wall_njrjc5o9wdhh4zem","wall_8q570xq30jajpknc","wall_li90yamosae8uksx","wall_wm5b95419hy24eih","wall_rmadylryovksial6","wall_1gqa1xmrgptloqkw","wall_x682d6mb8akntu7e","wall_r7yk9vxka9v6snv6","wall_ttgx9y48uctgv7sq","wall_llonzondn9vvw3i0","wall_n88j2lwd0biz6xan","wall_pzlinyuc64bq91h2","wall_6e9cniy7878zz8o7","wall_rnrpcgffh8lgpy1g","wall_qnw8polrxuhgqpvr","wall_bjscjn4pk0ehznws","wall_2pba85cbn90j8gzn","wall_0z8z0ll1429juivu","wall_s2dh90w8vag0exb9","wall_iaphrfbh2yypg6xx","wall_2b0x0fbux7gqvu5o","wall_vl9jchthqec7fhfs","wall_uxv2jcmhybxx3q0u","wall_xqgm29iyqdyd70wz","wall_vavj30weul8onfri","wall_freq10e76fi0qvg6","wall_ozp5qrq19kn4dlbb","wall_bnojfhbu7aqpkutf","wall_mygsq6yc4p4501l0","wall_s5awja53jjxtb1x1","wall_oia7xpjw709r6v8e","wall_fdo6jlf98v67dmh4","wall_5507z0z4cq7yy6aq","wall_xx9n2s5g6hbtaab6","wall_zr8vtxrraazbn4ju","wall_0t68qxmzs6bc0l3o","wall_n5xo0waz2nvf1syi","wall_diorolwov8ydf1x7","wall_s74w7tigftf9y3em","wall_cts1uqwd0swjqd0v","wall_hdhj0g363dvp1al2","wall_fa0wng8sz8fdd05a","wall_f8dd0b053w5y3l8q","wall_7mk8tqvryp4g81aw","wall_n2f0hm0z8c5q6ebg","wall_1puqiis34v7aue37","wall_pjifzy5o7vmnfz0f","wall_30grjkjqd5fm0d2p","wall_0mbtav95yncahq5s","wall_kbh90jfj93hc1kfh","wall_g2vuodi7efldic0o","wall_lxxf7sq8az8o0qjd","wall_zxuckkxr599dyb05","wall_r46l3f71jrrib8we","wall_h6qj8vn6ez47afau","wall_hxcrvaw865d5ild0","wall_civert765bk5ynt1","wall_g8j2vodr1b0m6f1u","wall_zq9nlb20ez1k3h4h","wall_u8fplakcq6b46wky","wall_jkmyzfrtgg8gxepu","wall_7yw8js0gfhag433t","wall_uk2g421te2nctyjf","wall_mdeo7dk2iippkqw4","wall_oyxidchtw8vujl86","wall_a9dzy1qkudg5d88w","wall_cufjhia6cz50pngh","wall_usesryb82wccunsb","wall_03dgayu8lgrxiyxa","wall_hmjbmqcsh76a1rsq","wall_pumsyipf7tg885f8","wall_6idg5bc9ouzrma5s","wall_xu5u077s4jsdvdlw","wall_3c0zjahxfnybvrb7","wall_ejynry0gowdr7rwq","wall_i3j1oukt2gzqqu0u","wall_418t4t60vkgyz0x5","wall_r4erjxgaoht8ivbo","wall_n3utm8hhpirj4pls","wall_u19kku3mv03ycdvd","wall_3gwugt912xpapy1s","wall_nqh20fhwmkyf6ehd","wall_p0828lqrh2r3nr2a","wall_sjfysyqic6d8r1py","wall_wcbhs987y1cqzyz1","wall_ghkk7epi84jv7zeo","wall_w6sn8eqrit5h3f0z","wall_eqe9ou8517f0dz0q","wall_borgptyhyo8hj6dy","wall_7dyi5zuqb0e6j8ek","wall_ew8kkmf3j4yaj482","wall_hqa3dcdj6n8k7p6n","wall_rqconmkpc5jnb0qs","slab_ieeul8ipcehbuzvz","wall_wo5xu17eg7v8cguy","wall_cdwpcphfr1znj3c3","wall_e9mxjb48t84cs9j2","wall_9xxe7aklfcy2qlvh","wall_wplz7ck66d2kzd05","wall_156unlha0b3rwxv5","wall_mg2gv6cauha4jq4f","wall_6rupf7pdmnbx5dxm","wall_d5jzvgzfy8yt3g63","wall_9eghw3m06og03ss9","wall_cyz17hjy32dfei68","wall_gq40hq02p2lh7z5y","wall_hhyexdx5mg7nz9ha","slab_pwk9tr2nn2ryo5wx","slab_s93u4ogd2xjcigad","slab_lmtipqd5dugm5y15","wall_8b4vwin5avlgghxq","wall_k3c46cb7vgagz961","wall_6ryij8vd37sso8yn","wall_ayirp3ryb7pcpecl","wall_d57vyvcn5b8vs8tx","wall_2uj1owbj70zqk1to","wall_kyler2w087cymm31","wall_wa8f2ip8fz03p354","slab_e19xm21md09s7zwh","slab_nkpiuz5oa8wz17x1","wall_vldc7zbyt6fwupwb","wall_brkvlg5w93jav6hr","wall_zr8loqrq610daiw5","wall_g3mngz8gpdtkcfrd","wall_n3tgmdviiki18uvf","wall_uooeq9wvxqpztqok","wall_oc2ab4wnh08rhebl","wall_nko9dtr7yv473c1h","wall_c169x7vx0b1yjsx4","wall_1f661s29k1apj9us","wall_8f943q80w34y21sy","wall_8ksgix1e1udocknq","wall_4isxo8x8msrdp8o3","wall_bltf5l6y2whghxlm","wall_7aov4imwy66vmtax","wall_gw8mure2jzagm7zq","wall_xa97civ0by5jjzbu","wall_ojjtbzpnrs2vikvi","wall_fy6r367vcb9wh9sj","wall_jgyqeg0ysh723o1u","wall_9gpdcx9if050sxuo","wall_04av9dno84xeq75y","slab_0nam1bvylu27ugcy","slab_m4mwszhkkg059eqq"],"parentId":"building_e7p75atkqjiu2t6m","baseElevation":0},"stair_600flkqcrkku2m8q":{"id":"stair_600flkqcrkku2m8q","name":"Staircase 1","type":"stair","width":1,"object":"node","visible":true,"children":["sseg_hgb0b9ctczw7fuf1","sseg_mx7eh2jrmqtgkjrj","sseg_22c9xuziiulu0008","sseg_y5acvfodo6zfxc4e","sseg_7fvgbx8tjnvhrclm"],"parentId":"level_02mqhbhmfadu3j6g","position":[14.495912551879883,0,-26.958070755004883],"rotation":3.138992184254612,"stairType":"straight","stepCount":10,"thickness":0.25,"toLevelId":"level_7ykh7xr9sa5h3l9o","totalRise":2.5,"sweepAngle":1.5707963267948966,"fillToFloor":true,"fromLevelId":"level_c4j8imqs0sze5hz0","innerRadius":0.9,"railingMode":"none","openingOffset":0.06,"railingHeight":0.92,"topLandingMode":"none","slabOpeningMode":"destination","topLandingDepth":0.9,"showCenterColumn":true,"showStepSupports":true},"stair_lyv9jl6qrpp3uzqj":{"id":"stair_lyv9jl6qrpp3uzqj","name":"Staircase 1","type":"stair","width":1,"object":"node","visible":true,"children":["sseg_ae96magw3516dl15","sseg_eh1h0mai5fls7ri2","sseg_uqm7p1esuj2x4tzm","sseg_koxonfks6v7hdzd9","sseg_kep4siod8rulwfl0"],"parentId":"level_szqq7obcfp8mvpd5","position":[14.5,0,-27.5],"rotation":3.138992184254612,"stairType":"straight","stepCount":10,"thickness":0.25,"toLevelId":"level_7ykh7xr9sa5h3l9o","totalRise":2.5,"sweepAngle":1.5707963267948966,"fillToFloor":true,"fromLevelId":"level_c4j8imqs0sze5hz0","innerRadius":0.9,"railingMode":"none","openingOffset":0.06,"railingHeight":0.92,"topLandingMode":"none","slabOpeningMode":"destination","topLandingDepth":0.9,"showCenterColumn":true,"showStepSupports":true},"ceiling_86uq44bc5ysakhyf":{"id":"ceiling_86uq44bc5ysakhyf","name":"Room 1 Ceiling","type":"ceiling","holes":[[[16.05949161566441,-27.30247492657031],[14.939495402629104,-27.305387448943083],[14.940535589190809,-27.70538609645569],[14.940847645159321,-27.825385690709474],[14.94470381957994,-29.308258676774983],[16.064700032615246,-29.30534615440221],[16.060843858194627,-27.8224731683367],[16.060531802226116,-27.70247357408292]]],"height":2.99,"object":"node","polygon":[[16,-30],[16,14],[-10,14],[-10,-30]],"visible":true,"children":[],"parentId":"level_szqq7obcfp8mvpd5","holeMetadata":[{"source":"stair","stairId":"stair_lyv9jl6qrpp3uzqj"}],"autoFromWalls":false},"building_e7p75atkqjiu2t6m":{"id":"building_e7p75atkqjiu2t6m","type":"building","object":"node","visible":true,"children":["level_szqq7obcfp8mvpd5","elevator_55gh1k39z05j03cs","elevator_lxww6nxx23kuopbq","elevator_6fvgkycp14fvb13d","level_02mqhbhmfadu3j6g"],"parentId":"site_z8qe2dvebl25t4o8","position":[0,0,0],"rotation":[0,0,0]},"door_089qgnv8i5o4v4zz":{"id":"door_089qgnv8i5o4v4zz","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_v7sqna940vejd3a9","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_v7sqna940vejd3a9","position":[0.8811273574829102,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_0c6hxq4hvklgxx4o":{"id":"door_0c6hxq4hvklgxx4o","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_ztozr0y2y9c8uqc0","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_ztozr0y2y9c8uqc0","position":[0.6385164260864258,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_0g3mpcsceqcx16gu":{"id":"door_0g3mpcsceqcx16gu","name":"Door 4","side":"back","type":"door","width":0.7,"handle":true,"height":2.1,"object":"node","wallId":"wall_rykm64hx2dm6nhwc","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_rykm64hx2dm6nhwc","position":[2.489674776051815,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_0p4uk8o2mtg01hdj":{"id":"door_0p4uk8o2mtg01hdj","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_8604tmiumwk7o98q","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_8604tmiumwk7o98q","position":[2.1332950592041016,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_1510fogkmbpxbswg":{"id":"door_1510fogkmbpxbswg","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_39l3sipiqtbh6t2h","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_39l3sipiqtbh6t2h","position":[2.3600567540718345,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_1o581ox68r66i89m":{"id":"door_1o581ox68r66i89m","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_rqconmkpc5jnb0qs","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_rqconmkpc5jnb0qs","position":[0.5927753448486328,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_1pehz09h02hcxmy3":{"id":"door_1pehz09h02hcxmy3","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_h980xzmxbs2tb9if","visible":true,"doorType":"double","panicBar":false,"parentId":"wall_h980xzmxbs2tb9if","position":[0.9533233642578125,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_1wpx57efwlogim0f":{"id":"door_1wpx57efwlogim0f","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_7toicryz09can4yw","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_7toicryz09can4yw","position":[2.287257309873226,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_29jy737m2etda24z":{"id":"door_29jy737m2etda24z","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_9aoyet4u36ousg1c","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_9aoyet4u36ousg1c","position":[0.5776613354682922,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_37prr4ilofnfjugg":{"id":"door_37prr4ilofnfjugg","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_oc2ab4wnh08rhebl","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_oc2ab4wnh08rhebl","position":[0.6705293655395508,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_3e1hdwt3dkpws3da":{"id":"door_3e1hdwt3dkpws3da","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_xt90bswwx7nzngn8","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_xt90bswwx7nzngn8","position":[0.760951042175293,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_4gqmhova0kql0axj":{"id":"door_4gqmhova0kql0axj","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_b1mxub721ucx0qsw","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_b1mxub721ucx0qsw","position":[3.3304220399452475,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_4wo982a4o6opi0rt":{"id":"door_4wo982a4o6opi0rt","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_03dgayu8lgrxiyxa","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_03dgayu8lgrxiyxa","position":[0.7239723205566406,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_56f2pwru4mhoc4bq":{"id":"door_56f2pwru4mhoc4bq","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_yb83a7iz9r5itw0q","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_yb83a7iz9r5itw0q","position":[4.295257568359375,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_56y209cki0kakrog":{"id":"door_56y209cki0kakrog","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_30grjkjqd5fm0d2p","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_30grjkjqd5fm0d2p","position":[0.8150434494018555,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_5q90ypuvi7ptdfhh":{"id":"door_5q90ypuvi7ptdfhh","name":"Door 4","side":"back","type":"door","width":0.7,"handle":true,"height":2.1,"object":"node","wallId":"wall_rykm64hx2dm6nhwc","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_rykm64hx2dm6nhwc","position":[1.4888425446265443,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_5strs0swg8yhvmeg":{"id":"door_5strs0swg8yhvmeg","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_hdhj0g363dvp1al2","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_hdhj0g363dvp1al2","position":[1.1016225814819336,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_5wigots5s748hgh4":{"id":"door_5wigots5s748hgh4","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_hgcojgwmv43dlhu8","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_hgcojgwmv43dlhu8","position":[2.3524385652138022,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_78qhi3j00zk3t684":{"id":"door_78qhi3j00zk3t684","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_qgdbdrcxaluy8i4r","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_qgdbdrcxaluy8i4r","position":[2.091153383255005,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_7c0qy514gkbvekpw":{"id":"door_7c0qy514gkbvekpw","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_9eghw3m06og03ss9","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_9eghw3m06og03ss9","position":[17.471562385559082,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_87k8yh4na244zvfd":{"id":"door_87k8yh4na244zvfd","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_zxzx7h2iw58a6muu","visible":true,"doorType":"double","panicBar":false,"parentId":"wall_zxzx7h2iw58a6muu","position":[4.011247634887695,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_8vo31r77oiwgy7oc":{"id":"door_8vo31r77oiwgy7oc","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_q4dfvlsn9mxcvhqq","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_q4dfvlsn9mxcvhqq","position":[4.398799896240234,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_9c6l98te9qk01405":{"id":"door_9c6l98te9qk01405","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_lxxf7sq8az8o0qjd","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_lxxf7sq8az8o0qjd","position":[1.75,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_agk3x89ku16jmsou":{"id":"door_agk3x89ku16jmsou","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_6bkdw4l4vyqt00uu","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_6bkdw4l4vyqt00uu","position":[0.8601059913635254,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_aouf01v6q0qks5ga":{"id":"door_aouf01v6q0qks5ga","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_s5hvtbsu2dlrsbd3","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_s5hvtbsu2dlrsbd3","position":[0.7231193742347983,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_axwmc3besbu7971v":{"id":"door_axwmc3besbu7971v","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_mdeo7dk2iippkqw4","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_mdeo7dk2iippkqw4","position":[1.946279525756836,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ben1fuvhpvu4nc3e":{"id":"door_ben1fuvhpvu4nc3e","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_vavj30weul8onfri","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_vavj30weul8onfri","position":[1.4697567224502563,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ce1jq0k8tk8dliqb":{"id":"door_ce1jq0k8tk8dliqb","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_s5awja53jjxtb1x1","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_s5awja53jjxtb1x1","position":[0.6244239807128906,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_cs9nej88jbdw6rer":{"id":"door_cs9nej88jbdw6rer","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_icw0rtlla0ie4gm7","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_icw0rtlla0ie4gm7","position":[1.9610544404579429,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_d5hl24xrf12lepmg":{"id":"door_d5hl24xrf12lepmg","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_tjs0pwclvjz1v3l6","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_tjs0pwclvjz1v3l6","position":[2.25,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_dd9w4uwavt7q2hdg":{"id":"door_dd9w4uwavt7q2hdg","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_zxuckkxr599dyb05","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_zxuckkxr599dyb05","position":[0.7246780395507812,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ec6zfwgpd0b6eq45":{"id":"door_ec6zfwgpd0b6eq45","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_7c4b0ljl9iaz1iqk","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_7c4b0ljl9iaz1iqk","position":[0.9143091401649741,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ecsxump5i94bh1gf":{"id":"door_ecsxump5i94bh1gf","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_kxiogrvlnpxtt70g","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_kxiogrvlnpxtt70g","position":[2.0725151261879233,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_f4ji55j0mu131m7l":{"id":"door_f4ji55j0mu131m7l","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_i3qgou8wi6cf65d2","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_i3qgou8wi6cf65d2","position":[0.8513803482055664,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_fera93ofppuwfggo":{"id":"door_fera93ofppuwfggo","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_9gpdcx9if050sxuo","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_9gpdcx9if050sxuo","position":[0.7441234588623047,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_gd2kn1ehsue66olv":{"id":"door_gd2kn1ehsue66olv","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_wvyz5cq7vao7d4gs","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_wvyz5cq7vao7d4gs","position":[1.0169935187889365,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_gg3ttpdq1oo2n9nv":{"id":"door_gg3ttpdq1oo2n9nv","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_cts1uqwd0swjqd0v","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_cts1uqwd0swjqd0v","position":[1.2690773010253906,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_gp47gs2mp6cog4g5":{"id":"door_gp47gs2mp6cog4g5","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_qnw8polrxuhgqpvr","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_qnw8polrxuhgqpvr","position":[1.3956818580627441,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_hd27oldvkag50qyb":{"id":"door_hd27oldvkag50qyb","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_55bb10r36ltozu1d","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_55bb10r36ltozu1d","position":[1.9750543794227866,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_he4uq5rxpwctemmw":{"id":"door_he4uq5rxpwctemmw","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_9wrpt556i02d7fmo","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_9wrpt556i02d7fmo","position":[3.335055064409964,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_hu4zz56l5m3opi24":{"id":"door_hu4zz56l5m3opi24","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_5ivevoje9s7zj187","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_5ivevoje9s7zj187","position":[2.323713894803646,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_hzwjtbi37to0zjvd":{"id":"door_hzwjtbi37to0zjvd","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_wm5b95419hy24eih","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_wm5b95419hy24eih","position":[0.7735691070556641,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_i01iu8wsoo01vonp":{"id":"door_i01iu8wsoo01vonp","name":"Door 44","side":"front","type":"door","width":0.9,"handle":true,"height":1,"object":"node","wallId":"wall_fwtf9gx062n2mdol","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_fwtf9gx062n2mdol","position":[1.9146251465380004,0.5,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":0.5,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ic6la3eo1ci04d94":{"id":"door_ic6la3eo1ci04d94","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_vcezz72u4682ed5o","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_vcezz72u4682ed5o","position":[0.976520176847103,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_iffg9fg71j83tupg":{"id":"door_iffg9fg71j83tupg","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_nqh20fhwmkyf6ehd","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_nqh20fhwmkyf6ehd","position":[2.6734284162521362,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_irjcehzgjuznvt0y":{"id":"door_irjcehzgjuznvt0y","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_oze1nfdlbzkz0e4m","visible":true,"doorType":"double","panicBar":false,"parentId":"wall_oze1nfdlbzkz0e4m","position":[3.9620161056518555,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_j0v5zmjxjdbwy1jv":{"id":"door_j0v5zmjxjdbwy1jv","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_ozp5qrq19kn4dlbb","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_ozp5qrq19kn4dlbb","position":[0.6325960159301758,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_jc4jylzekv2oftf9":{"id":"door_jc4jylzekv2oftf9","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_5j8gf0m683gw9at5","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_5j8gf0m683gw9at5","position":[0.9947000741958618,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_jwetbmo8qbumfarm":{"id":"door_jwetbmo8qbumfarm","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_qnw8polrxuhgqpvr","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_qnw8polrxuhgqpvr","position":[1.3956818580627441,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_jwyfy7vomigipvye":{"id":"door_jwyfy7vomigipvye","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_gsirmpkeyszf0g1l","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_gsirmpkeyszf0g1l","position":[0.6561523637367515,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_jze66v1o4294axex":{"id":"door_jze66v1o4294axex","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_156unlha0b3rwxv5","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_156unlha0b3rwxv5","position":[1.2170429229736328,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_k6licl2utzfzuzjx":{"id":"door_k6licl2utzfzuzjx","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_6rupf7pdmnbx5dxm","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_6rupf7pdmnbx5dxm","position":[0.6722345352172852,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_kb40kb3z7syxl7j6":{"id":"door_kb40kb3z7syxl7j6","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_g8j2vodr1b0m6f1u","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_g8j2vodr1b0m6f1u","position":[0.6791534423828125,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_kl3ij2xc7qdsw6v6":{"id":"door_kl3ij2xc7qdsw6v6","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_smf3bj8g583r35l1","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_smf3bj8g583r35l1","position":[0.6849008760048179,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_kmp4dcn3hvocs4vj":{"id":"door_kmp4dcn3hvocs4vj","name":"Door 4","side":"back","type":"door","width":0.7,"handle":true,"height":2.1,"object":"node","wallId":"wall_dpdh0rzzqz4uxy33","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_dpdh0rzzqz4uxy33","position":[0.45,1.05,0],"rotation":[0,9.42477796076938,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ktq2nnb7j6wjesdv":{"id":"door_ktq2nnb7j6wjesdv","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_xa97civ0by5jjzbu","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_xa97civ0by5jjzbu","position":[0.747563362121582,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ldul0iimmr8t2nph":{"id":"door_ldul0iimmr8t2nph","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_gw8mure2jzagm7zq","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_gw8mure2jzagm7zq","position":[1.2508010864257812,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_lhph8ow3u9akye73":{"id":"door_lhph8ow3u9akye73","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_kbh90jfj93hc1kfh","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_kbh90jfj93hc1kfh","position":[0.8455972671508789,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_lilrbl7kmnlfsegs":{"id":"door_lilrbl7kmnlfsegs","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_irhkb0sv85l5gx3f","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_irhkb0sv85l5gx3f","position":[3.3463007173134116,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_llj8iidkroor0kvv":{"id":"door_llj8iidkroor0kvv","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_xqgm29iyqdyd70wz","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_xqgm29iyqdyd70wz","position":[3.0471043586730957,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_mn9mipu04l4z6m1h":{"id":"door_mn9mipu04l4z6m1h","name":"Door 4","side":"front","type":"door","slots":{"panel":"library:preset-white"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_owi6yxawiyxcix0c","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_owi6yxawiyxcix0c","position":[2.4196155071258545,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_mpe3rqu7r8rd9861":{"id":"door_mpe3rqu7r8rd9861","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_ro9c1n3spaxahes3","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_ro9c1n3spaxahes3","position":[0.6996278762817383,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_mx6zqm9wibnmyckh":{"id":"door_mx6zqm9wibnmyckh","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_wcbhs987y1cqzyz1","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_wcbhs987y1cqzyz1","position":[3.0955445766448975,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_n3wkniv2zhmwd6mn":{"id":"door_n3wkniv2zhmwd6mn","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_vldc7zbyt6fwupwb","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_vldc7zbyt6fwupwb","position":[0.7544441223144531,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_n97lkiscprx1g2tu":{"id":"door_n97lkiscprx1g2tu","name":"Door 44","side":"front","type":"door","width":0.9,"handle":true,"height":1,"object":"node","wallId":"wall_bc3p0wckzsg2p37t","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_bc3p0wckzsg2p37t","position":[2.049512365013342,0.5,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":0.5,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_neqzzmhubk6ral29":{"id":"door_neqzzmhubk6ral29","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_j4dy3pftqgz5pu4g","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_j4dy3pftqgz5pu4g","position":[0.7172366342140464,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_o1xwx6m71v10el5a":{"id":"door_o1xwx6m71v10el5a","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_wo5xu17eg7v8cguy","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_wo5xu17eg7v8cguy","position":[0.7295598983764648,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_o9bejhalxuoidt0q":{"id":"door_o9bejhalxuoidt0q","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_n88j2lwd0biz6xan","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_n88j2lwd0biz6xan","position":[1.1348953247070312,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_olx32nxcjwyspjha":{"id":"door_olx32nxcjwyspjha","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_1puqiis34v7aue37","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_1puqiis34v7aue37","position":[0.799713134765625,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_om6xc8x8ins72scd":{"id":"door_om6xc8x8ins72scd","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_vjb1olb1o2h03zcc","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_vjb1olb1o2h03zcc","position":[2.3628177642822266,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_oy3mk5yk568ro4ga":{"id":"door_oy3mk5yk568ro4ga","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_ejveuwbdpe2q9uvx","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_ejveuwbdpe2q9uvx","position":[0.9330991468025474,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_p7mqw5y4k0scw27g":{"id":"door_p7mqw5y4k0scw27g","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_9eghw3m06og03ss9","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_9eghw3m06og03ss9","position":[1.4671173095703125,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_q2jawtp9vao8w07z":{"id":"door_q2jawtp9vao8w07z","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_li90yamosae8uksx","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_li90yamosae8uksx","position":[0.734227180480957,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_q5t8kaabv2k2g3rt":{"id":"door_q5t8kaabv2k2g3rt","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_jkmyzfrtgg8gxepu","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_jkmyzfrtgg8gxepu","position":[0.7236175537109375,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_q6jqknbogmk1vrcf":{"id":"door_q6jqknbogmk1vrcf","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_g3mngz8gpdtkcfrd","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_g3mngz8gpdtkcfrd","position":[2.126814842224121,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_qhfgwhvavweqi2bb":{"id":"door_qhfgwhvavweqi2bb","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_9xxe7aklfcy2qlvh","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_9xxe7aklfcy2qlvh","position":[0.936830997467041,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_qkln7lmdessf4ljs":{"id":"door_qkln7lmdessf4ljs","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_x1rlai8ex29tez4y","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_x1rlai8ex29tez4y","position":[0.91799276335108,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ql2q26c3kcna4q1z":{"id":"door_ql2q26c3kcna4q1z","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_xnpxaeiusfig43z2","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_xnpxaeiusfig43z2","position":[0.6433897018432617,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_r4d4fyjtp1vf3ind":{"id":"door_r4d4fyjtp1vf3ind","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_9zwk9cpeeig7lcfl","visible":true,"doorType":"double","panicBar":false,"parentId":"wall_9zwk9cpeeig7lcfl","position":[3.9527225494384766,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_rtmq7vo2qr2m2lt3":{"id":"door_rtmq7vo2qr2m2lt3","name":"Door 4","side":"front","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_n3utm8hhpirj4pls","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_n3utm8hhpirj4pls","position":[4.79487943649292,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_s5fvo04eac5d6svv":{"id":"door_s5fvo04eac5d6svv","name":"Door 4","side":"front","type":"door","slots":{"panel":"library:preset-white"},"width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_6idg5bc9ouzrma5s","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_6idg5bc9ouzrma5s","position":[0.8810462951660156,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_scyjkkzoaq2grxsm":{"id":"door_scyjkkzoaq2grxsm","name":"Door 4","side":"back","type":"door","width":0.7,"handle":true,"height":2.1,"object":"node","wallId":"wall_rykm64hx2dm6nhwc","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_rykm64hx2dm6nhwc","position":[0.4901637071608803,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_spxj5621quc0z56i":{"id":"door_spxj5621quc0z56i","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_pippbsum1g55qje8","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_pippbsum1g55qje8","position":[2.049110051114681,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_sq8hp4cr91hok7yt":{"id":"door_sq8hp4cr91hok7yt","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_tm0i0ysimmph04rl","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_tm0i0ysimmph04rl","position":[1.7130351066589355,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_svd6is1978dxr6g1":{"id":"door_svd6is1978dxr6g1","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_xfu9q2fm0ev5gbyu","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_xfu9q2fm0ev5gbyu","position":[2.4098501205444336,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_t3u7urqslu4kgwpr":{"id":"door_t3u7urqslu4kgwpr","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_osfzli0fedpyrecg","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_osfzli0fedpyrecg","position":[0.6531630715919761,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_tiqkid55g3q0e7vh":{"id":"door_tiqkid55g3q0e7vh","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_eqe9ou8517f0dz0q","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_eqe9ou8517f0dz0q","position":[0.588341236114502,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ui26uat5g1308msz":{"id":"door_ui26uat5g1308msz","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_vl9jchthqec7fhfs","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_vl9jchthqec7fhfs","position":[1.0372097492218018,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_urxziuc80iv9gst5":{"id":"door_urxziuc80iv9gst5","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_ojjtbzpnrs2vikvi","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_ojjtbzpnrs2vikvi","position":[0.7659139633178711,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_vojcho42907qrgln":{"id":"door_vojcho42907qrgln","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_jgyqeg0ysh723o1u","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_jgyqeg0ysh723o1u","position":[1.0476202964782715,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_w2akyb93e3pdwml1":{"id":"door_w2akyb93e3pdwml1","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_r4erjxgaoht8ivbo","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_r4erjxgaoht8ivbo","position":[1.5834226608276367,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_wghytu8xog8nrpr1":{"id":"door_wghytu8xog8nrpr1","name":"Door 4","side":"back","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_diorolwov8ydf1x7","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_diorolwov8ydf1x7","position":[0.6329193115234375,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_wqsnb8raham18y8n":{"id":"door_wqsnb8raham18y8n","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_zr8vtxrraazbn4ju","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_zr8vtxrraazbn4ju","position":[2.325193405151367,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"right","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_y14nk1zgj1wytjgn":{"id":"door_y14nk1zgj1wytjgn","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_xpcjvni8vqbxkaiz","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_xpcjvni8vqbxkaiz","position":[0.596373438835144,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ye8dydiulgzypiyj":{"id":"door_ye8dydiulgzypiyj","name":"Door 4","side":"back","type":"door","width":1.5,"handle":true,"height":2.1,"object":"node","wallId":"wall_bnnq2xjr5bffefog","visible":true,"doorType":"sliding","panicBar":false,"parentId":"wall_bnnq2xjr5bffefog","position":[1.212900161743164,1.05,0],"rotation":[0,3.141592653589793,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.76,"columnRatios":[1],"dividerThickness":0.025},{"type":"panel","panelDepth":0.012,"panelInset":0.035,"heightRatio":0.24,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":2,"threshold":false,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"visible","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.03,0.04],"frameThickness":0.05,"operationState":0.65,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_ym7wy7aslkeqwc5s":{"id":"door_ym7wy7aslkeqwc5s","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_7yw8js0gfhag433t","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_7yw8js0gfhag433t","position":[0.8966856002807617,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"inward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"door_z15l3658qaw6tsyj":{"id":"door_z15l3658qaw6tsyj","name":"Door 4","side":"front","type":"door","width":0.9,"handle":true,"height":2.1,"object":"node","wallId":"wall_j4dy3pftqgz5pu4g","visible":true,"doorType":"hinged","panicBar":false,"parentId":"wall_j4dy3pftqgz5pu4g","position":[0.7172366342140464,1.05,0],"rotation":[0,0,0],"segments":[{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.4,"columnRatios":[1],"dividerThickness":0.03},{"type":"panel","panelDepth":0.01,"panelInset":0.04,"heightRatio":0.6,"columnRatios":[1],"dividerThickness":0.03}],"leafCount":1,"threshold":true,"archHeight":0.45,"doorCloser":false,"frameDepth":0.07,"handleSide":"right","hingesSide":"left","swingAngle":0,"trackStyle":"none","openingKind":"door","cornerRadius":0.15,"doorCategory":"interior","handleHeight":1.05,"openingShape":"rectangle","contentPadding":[0.04,0.04],"frameThickness":0.05,"operationState":0,"panicBarHeight":1,"slideDirection":"left","swingDirection":"outward","openingTopRadii":[0.15,0.15],"thresholdHeight":0.02,"constructionType":"framed","garagePanelCount":4,"openingRadiusMode":"all","dimensionReference":"nominal","openingRevealRadius":0.025},"sseg_22c9xuziiulu0008":{"id":"sseg_22c9xuziiulu0008","type":"stair-segment","width":1,"height":0,"length":1,"object":"node","visible":true,"parentId":"stair_600flkqcrkku2m8q","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":false,"segmentType":"landing","attachmentSide":"right"},"sseg_7fvgbx8tjnvhrclm":{"id":"sseg_7fvgbx8tjnvhrclm","type":"stair-segment","width":1,"height":0,"length":0.4,"object":"node","visible":true,"parentId":"stair_600flkqcrkku2m8q","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":false,"segmentType":"landing","attachmentSide":"front"},"sseg_ae96magw3516dl15":{"id":"sseg_ae96magw3516dl15","type":"stair-segment","width":1,"height":1.3012369807517068,"length":1.7494087426645786,"object":"node","visible":true,"parentId":"stair_lyv9jl6qrpp3uzqj","position":[0,0,0],"rotation":0,"stepCount":6,"thickness":0.25,"fillToFloor":false,"segmentType":"stair","attachmentSide":"front"},"sseg_eh1h0mai5fls7ri2":{"id":"sseg_eh1h0mai5fls7ri2","type":"stair-segment","width":1,"height":0,"length":1,"object":"node","visible":true,"parentId":"stair_lyv9jl6qrpp3uzqj","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":false,"segmentType":"landing","attachmentSide":"front"},"sseg_hgb0b9ctczw7fuf1":{"id":"sseg_hgb0b9ctczw7fuf1","type":"stair-segment","width":1,"height":1.3012369807517068,"length":1.7494087426645786,"object":"node","visible":true,"parentId":"stair_600flkqcrkku2m8q","position":[0,0,0],"rotation":0,"stepCount":6,"thickness":0.25,"fillToFloor":false,"segmentType":"stair","attachmentSide":"front"},"sseg_kep4siod8rulwfl0":{"id":"sseg_kep4siod8rulwfl0","type":"stair-segment","width":1,"height":0,"length":0.4,"object":"node","visible":true,"parentId":"stair_lyv9jl6qrpp3uzqj","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":false,"segmentType":"landing","attachmentSide":"front"},"sseg_koxonfks6v7hdzd9":{"id":"sseg_koxonfks6v7hdzd9","type":"stair-segment","width":1,"height":1.4340194773617378,"length":1.4828778755051992,"object":"node","visible":true,"parentId":"stair_lyv9jl6qrpp3uzqj","position":[0,0,0],"rotation":0,"stepCount":6,"thickness":0.25,"fillToFloor":false,"segmentType":"stair","attachmentSide":"right"},"sseg_mx7eh2jrmqtgkjrj":{"id":"sseg_mx7eh2jrmqtgkjrj","type":"stair-segment","width":1.048436139294001,"height":0,"length":1,"object":"node","visible":true,"parentId":"stair_600flkqcrkku2m8q","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":false,"segmentType":"landing","attachmentSide":"front"},"sseg_uqm7p1esuj2x4tzm":{"id":"sseg_uqm7p1esuj2x4tzm","type":"stair-segment","width":1,"height":0,"length":1,"object":"node","visible":true,"parentId":"stair_lyv9jl6qrpp3uzqj","position":[0,0,0],"rotation":0,"stepCount":0,"thickness":0.32,"fillToFloor":false,"segmentType":"landing","attachmentSide":"right"},"sseg_y5acvfodo6zfxc4e":{"id":"sseg_y5acvfodo6zfxc4e","type":"stair-segment","width":1,"height":1.4340194773617378,"length":1.4828778755051992,"object":"node","visible":true,"parentId":"stair_600flkqcrkku2m8q","position":[0,0,0],"rotation":0,"stepCount":6,"thickness":0.25,"fillToFloor":false,"segmentType":"stair","attachmentSide":"right"},"window_2rk6cm7ej9bbbtn1":{"id":"window_2rk6cm7ej9bbbtn1","name":"Window 5","side":"front","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_vl9jchthqec7fhfs","visible":true,"parentId":"wall_vl9jchthqec7fhfs","position":[2.842123031616211,1.25,0],"rotation":[0,0,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_45z1zf9hncb10109":{"id":"window_45z1zf9hncb10109","name":"Window 5","side":"back","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_9eghw3m06og03ss9","visible":true,"parentId":"wall_9eghw3m06og03ss9","position":[14.7422456741333,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_4j6w6fol2nczizc4":{"id":"window_4j6w6fol2nczizc4","name":"Window 5","side":"back","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_r46l3f71jrrib8we","visible":true,"parentId":"wall_r46l3f71jrrib8we","position":[0.75,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_5wpah8vmarylko5t":{"id":"window_5wpah8vmarylko5t","name":"Window 5","side":"front","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_xqgm29iyqdyd70wz","visible":true,"parentId":"wall_xqgm29iyqdyd70wz","position":[1.0000321865081787,1.25,0],"rotation":[0,0,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_6awly60ibve0sjix":{"id":"window_6awly60ibve0sjix","name":"Window 5","side":"back","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_s2dh90w8vag0exb9","visible":true,"parentId":"wall_s2dh90w8vag0exb9","position":[3.4197906106710434,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_8ip0dggjzcunde4f":{"id":"window_8ip0dggjzcunde4f","name":"Window 5","side":"back","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_9eghw3m06og03ss9","visible":true,"parentId":"wall_9eghw3m06og03ss9","position":[7.100254535675049,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_8kllj8r4g23p1bsc":{"id":"window_8kllj8r4g23p1bsc","name":"Window 5","side":"back","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_9eghw3m06og03ss9","visible":true,"parentId":"wall_9eghw3m06og03ss9","position":[12.075881481170654,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_g0e9inpqv9ycei10":{"id":"window_g0e9inpqv9ycei10","name":"Window 5","side":"front","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_9eghw3m06og03ss9","visible":true,"parentId":"wall_9eghw3m06og03ss9","position":[9.647584915161133,1.25,0],"rotation":[0,0,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_is6r4pzrb5l6f9bb":{"id":"window_is6r4pzrb5l6f9bb","name":"Window 5","side":"back","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_cxbdglvxpk5cpdjl","visible":true,"parentId":"wall_cxbdglvxpk5cpdjl","position":[3.0356369018554688,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_jx7mn5tnsl9vpgep":{"id":"window_jx7mn5tnsl9vpgep","name":"Window 5","side":"front","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_cts1uqwd0swjqd0v","visible":true,"parentId":"wall_cts1uqwd0swjqd0v","position":[3.4964442253112793,1.25,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_kjkf6mu8t247qyr9":{"id":"window_kjkf6mu8t247qyr9","name":"Window 5","side":"front","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_cts1uqwd0swjqd0v","visible":true,"parentId":"wall_cts1uqwd0swjqd0v","position":[5.52027702331543,1.25,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_l5d1o9eeih5lo0j0":{"id":"window_l5d1o9eeih5lo0j0","name":"Window 5","side":"back","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_xx9n2s5g6hbtaab6","visible":true,"parentId":"wall_xx9n2s5g6hbtaab6","position":[1.016250729560852,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_la38t2n2qoonghi0":{"id":"window_la38t2n2qoonghi0","name":"Window 5","side":"back","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_zxuckkxr599dyb05","visible":true,"parentId":"wall_zxuckkxr599dyb05","position":[2.108003616333008,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_ot3hpjxq2sjy0vqx":{"id":"window_ot3hpjxq2sjy0vqx","name":"Window 5","side":"front","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_cxbdglvxpk5cpdjl","visible":true,"parentId":"wall_cxbdglvxpk5cpdjl","position":[1.0857696533203125,1.25,0],"rotation":[0,0,0],"rowRatios":[0.5,0.5],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_pejp73vpvoctrzno":{"id":"window_pejp73vpvoctrzno","name":"Window 5","side":"front","sill":true,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_zq9nlb20ez1k3h4h","visible":true,"parentId":"wall_zq9nlb20ez1k3h4h","position":[0.75,1.25,0],"rotation":[0,0,0],"rowRatios":[1],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.07,"hingesSide":"left","windowType":"fixed","openingKind":"window","columnRatios":[0.5,0.5],"cornerRadius":0.15,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.05,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0.025,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_snon92pb24u98mjx":{"id":"window_snon92pb24u98mjx","name":"Window 5","side":"back","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_9eghw3m06og03ss9","visible":true,"parentId":"wall_9eghw3m06og03ss9","position":[4.36246931552887,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"window_tmud56rp2kiiclm3":{"id":"window_tmud56rp2kiiclm3","name":"Window 5","side":"back","sill":false,"type":"window","width":1.5,"height":1.5,"object":"node","wallId":"wall_s2dh90w8vag0exb9","visible":true,"parentId":"wall_s2dh90w8vag0exb9","position":[1.6550798416137695,1.25,0],"rotation":[0,3.141592653589793,0],"rowRatios":[0.75,0.25],"sillDepth":0.08,"archHeight":0.35,"frameDepth":0.11,"hingesSide":"left","windowType":"casement","openingKind":"window","columnRatios":[1],"cornerRadius":0.38,"openingShape":"rectangle","casementStyle":"single","sillThickness":0.03,"frameThickness":0.06,"operationState":0,"awningDirection":"up","constructionType":"framed","openingRadiusMode":"all","dimensionReference":"nominal","openingCornerRadii":[0.15,0.15,0.15,0.15],"openingRevealRadius":0,"rowDividerThickness":0.03,"columnDividerThickness":0.03},"elevator_55gh1k39z05j03cs":{"id":"elevator_55gh1k39z05j03cs","name":"Elevator 1","type":"elevator","depth":1.79,"speed":2.2,"width":1.84,"object":"node","dwellMs":1400,"visible":true,"parentId":"building_e7p75atkqjiu2t6m","position":[13.011079742724316,0.15,-28.988920257275684],"rotation":3.1405230291353594,"cabHeight":2.25,"doorStyle":"center-opening","doorWidth":0.95,"toLevelId":"level_uhllre2i4c3ddgib","doorHeight":2.15,"shaftStyle":"solid","fromLevelId":"level_szqq7obcfp8mvpd5","defaultLevelId":"level_szqq7obcfp8mvpd5","doorDurationMs":900,"doorPanelStyle":"glass-frame","disabledLevelIds":[],"shaftWallThickness":0.05,"serviceOnlyLevelIds":[]},"elevator_6fvgkycp14fvb13d":{"id":"elevator_6fvgkycp14fvb13d","name":"Elevator 1","type":"elevator","depth":1.84,"speed":2.2,"width":1.84,"object":"node","dwellMs":1400,"visible":true,"parentId":"building_e7p75atkqjiu2t6m","position":[9.011079742724316,0.15,-28.988920257275684],"rotation":3.1405230291353594,"cabHeight":2.35,"doorStyle":"center-opening","doorWidth":0.95,"toLevelId":"level_uhllre2i4c3ddgib","doorHeight":2.1,"shaftStyle":"solid","fromLevelId":"level_szqq7obcfp8mvpd5","defaultLevelId":"level_szqq7obcfp8mvpd5","doorDurationMs":900,"doorPanelStyle":"glass-frame","disabledLevelIds":[],"shaftWallThickness":0.09,"serviceOnlyLevelIds":[]},"elevator_lxww6nxx23kuopbq":{"id":"elevator_lxww6nxx23kuopbq","name":"Elevator 1","type":"elevator","depth":1.84,"speed":2.2,"width":1.84,"object":"node","dwellMs":1400,"visible":true,"parentId":"building_e7p75atkqjiu2t6m","position":[11.011079742724316,0.15,-28.988920257275684],"rotation":3.1405230291353594,"cabHeight":2.35,"doorStyle":"center-opening","doorWidth":0.95,"toLevelId":"level_uhllre2i4c3ddgib","doorHeight":2.1,"shaftStyle":"solid","fromLevelId":"level_szqq7obcfp8mvpd5","defaultLevelId":"level_szqq7obcfp8mvpd5","doorDurationMs":900,"doorPanelStyle":"glass-frame","disabledLevelIds":[],"shaftWallThickness":0.09,"serviceOnlyLevelIds":[]}} diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/scene-02.json b/packages/core/src/lib/__fixtures__/plate-corpus/scene-02.json new file mode 100644 index 0000000000..463679d86a --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/scene-02.json @@ -0,0 +1,138 @@ +[ + { + "start": [2, 7.5], + "end": [-2, 7.5] + }, + { + "start": [-5.05, 2.5], + "end": [-5.05, 0.5] + }, + { + "start": [-2.525, 0.5], + "end": [-2.525, -0.8595930435954162] + }, + { + "start": [-2, 7.5], + "end": [-4.6000000000000005, 7.5] + }, + { + "start": [-2, 4], + "end": [-2, 7.5] + }, + { + "start": [6.75, 1.25], + "end": [5.75, 1.25] + }, + { + "start": [-6, 2.5], + "end": [-6, -7] + }, + { + "start": [1.75, -7], + "end": [1.75, -5] + }, + { + "start": [-6, 7.5], + "end": [-6, 6] + }, + { + "start": [-6, 6], + "end": [-6, 2.5] + }, + { + "start": [-4.6000000000000005, 6], + "end": [-6, 6] + }, + { + "start": [-1, 2.5], + "end": [-2, 2.5] + }, + { + "start": [-12, 8.5], + "end": [-18.06217782649107, 4.999999999999998] + }, + { + "start": [-2.525, 0.5], + "end": [0, 0.5] + }, + { + "start": [-4.6000000000000005, 7.5], + "end": [-4.6000000000000005, 6] + }, + { + "start": [0, -5], + "end": [1.75, -5] + }, + { + "start": [-2.525, -0.8595930435954162], + "end": [-6, -0.8595930435954164] + }, + { + "start": [-1, 4], + "end": [-1, 2.5] + }, + { + "start": [-18.06217782649107, 4.999999999999998], + "end": [-9, 8.5] + }, + { + "start": [1.75, -5], + "end": [6.75, -5] + }, + { + "start": [-5.05, 0.5], + "end": [-2.525, 0.5] + }, + { + "start": [0, 0.5], + "end": [0, -5] + }, + { + "start": [6.75, 1.25], + "end": [6.75, 7.5] + }, + { + "start": [-2, 2.5], + "end": [-5.05, 2.5] + }, + { + "start": [-9, 8.5], + "end": [-12, 8.5] + }, + { + "start": [-2, 2.5], + "end": [-2, 4] + }, + { + "start": [6.75, -5], + "end": [6.75, 1.25] + }, + { + "start": [6.75, 7.5], + "end": [2, 7.5] + }, + { + "start": [-6, -7], + "end": [1.75, -7] + }, + { + "start": [-1, 4], + "end": [-2, 4] + }, + { + "start": [-4.6000000000000005, 7.5], + "end": [-6, 7.5] + }, + { + "start": [-5.05, 2.5], + "end": [-6, 2.5] + }, + { + "start": [2, 6.5], + "end": [2, 7.5] + }, + { + "start": [-6, 0.5], + "end": [-5.05, 0.5] + } +] diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/scene-14.json b/packages/core/src/lib/__fixtures__/plate-corpus/scene-14.json new file mode 100644 index 0000000000..cb19461808 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/scene-14.json @@ -0,0 +1,155 @@ +[ + { + "start": [11.204553899173982, 13], + "end": [15.204553899173982, 13], + "curveOffset": -1.35 + }, + { + "start": [-6.008493816733815, 5.999995024486382], + "end": [-6.010251158127018, 8.99999399506977] + }, + { + "start": [-14.795446100826018, 5.999999886808649], + "end": [-14.795446100826018, 11.702318988694401] + }, + { + "start": [-2.795446100826018, -10.297681011305599], + "end": [-5.795446100826018, -10.297681011305599], + "curveOffset": -1.35 + }, + { + "start": [7.355749731364023, -10.297681011305599], + "end": [3, -10.297681011305599] + }, + { + "start": [3, -10.297681011305599], + "end": [-0.644250268635977, -10.297681011305599] + }, + { + "start": [0.20455389917398215, 13.702318988694401], + "end": [11.204553899173982, 13.702318988694401] + }, + { + "start": [11, -10.297681011305599], + "end": [7.355749731364023, -10.297681011305599] + }, + { + "start": [15, 0], + "end": [11, 0] + }, + { + "start": [3, 0], + "end": [3, -5] + }, + { + "start": [-14.795446100826016, 5.999999886808651], + "end": [-15, 6] + }, + { + "start": [3, -5], + "end": [3, -10.297681011305599] + }, + { + "start": [-5.795446100826018, -10.297681011305599], + "end": [-5.795446100826018, -8.297681011305599] + }, + { + "start": [-0.644250268635977, -10.297681011305599], + "end": [-2.795446100826018, -10.297681011305599] + }, + { + "start": [11.204553899173982, 13.702318988694401], + "end": [11.204553899173982, 13] + }, + { + "start": [-6, -8.5], + "end": [-6.004979133947409, -2.9166803958702303e-6] + }, + { + "start": [11, 0], + "end": [11, -10.297681011305599] + }, + { + "start": [-6.010251158127018, 8.99999399506977], + "end": [-6.010283076318778, 9.05448229358335] + }, + { + "start": [-5.795446100826018, 13.702318988694401], + "end": [0.20455389917398215, 13.702318988694401], + "curveOffset": -1.35 + }, + { + "start": [15.204553899173982, 4.702318988694401], + "end": [15.204553899173982, -4.797681011305599] + }, + { + "start": [15.473228858572657, -5.028167637154423], + "end": [15.204553899173982, -10.297681011305599], + "curveOffset": -1.2127264906170296 + }, + { + "start": [7.355749731364023, -10.297681011305599], + "end": [7.355749731364023, -10.382656974675651] + }, + { + "start": [11, -10.297681011305599], + "end": [11, -10.5] + }, + { + "start": [-14.795446100826018, -7.797681011305599], + "end": [-14.795446100826018, 5.999999886808649] + }, + { + "start": [-6.002050231625404, -5.000001200986047], + "end": [3, -5] + }, + { + "start": [-6.004979133947409, -2.9166803958702303e-6], + "end": [-6.008493816733815, 5.999995024486382] + }, + { + "start": [-5.795446100826018, -8.297681011305599], + "end": [-14.795446100826018, -7.797681011305599] + }, + { + "start": [-0.644250268635977, -10.297681011305599], + "end": [-0.644250268635977, -10.382656974675651] + }, + { + "start": [-6.010251158127018, 8.99999399506977], + "end": [-6, 11.5] + }, + { + "start": [-6.004979133947409, -2.9166803958702303e-6], + "end": [3, 0] + }, + { + "start": [3, -10.297681011305599], + "end": [3, -10.5] + }, + { + "start": [15.204553899173982, 13], + "end": [15.204553899173982, 4.702318988694401] + }, + { + "start": [15.204553899173982, -4.797681011305599], + "end": [15.473228858572657, -5.028167637154423], + "curveOffset": -0.004509289608953861 + }, + { + "start": [-6.008493816733815, 5.999995024486382], + "end": [-14.795446100826016, 5.999999886808651] + }, + { + "start": [-14.795446100826018, 11.702318988694401], + "end": [-5.795446100826018, 11.702318988694401] + }, + { + "start": [15.204553899173982, -10.297681011305599], + "end": [11, -10.297681011305599] + }, + { + "start": [-5.795446100826018, 11.702318988694401], + "end": [-5.795446100826018, 13.702318988694401] + } +] diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/scene-15.json b/packages/core/src/lib/__fixtures__/plate-corpus/scene-15.json new file mode 100644 index 0000000000..124fb7f031 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/scene-15.json @@ -0,0 +1,136 @@ +[ + { + "start": [11.500170165205361, -2.5172557281265853], + "end": [11.50034033041072, 4.9654885437468295], + "thickness": 0.3 + }, + { + "start": [-12.10692010091972, 4.796798391140731], + "end": [-10.351434346296093, 4.75], + "thickness": 0.3 + }, + { + "start": [15, -16.5], + "end": [15.083184195624955, -16.378423098701987], + "thickness": 0.3 + }, + { + "start": [15, -10], + "end": [15, -16.5], + "thickness": 0.3 + }, + { + "start": [-12, -8], + "end": [5.5, -8], + "thickness": 0.3 + }, + { + "start": [11.5, -10], + "end": [15, -10], + "thickness": 0.3 + }, + { + "start": [11.50034033041072, 4.9654885437468295], + "end": [15, 5], + "thickness": 0.3 + }, + { + "start": [-3.25, -16.5], + "end": [-3.25, -11.75] + }, + { + "start": [15, 5], + "end": [15, -2.5], + "thickness": 0.3 + }, + { + "start": [-3.25, -16.5], + "end": [15, -16.5], + "thickness": 0.3 + }, + { + "start": [-12, -10], + "end": [-12.095594760434041, 4.797018721123448], + "thickness": 0.3 + }, + { + "start": [11.5, -10], + "end": [11.500170165205361, -2.5172557281265853], + "thickness": 0.3 + }, + { + "start": [5.5, -16.5], + "end": [5.5, -10], + "thickness": 0.3 + }, + { + "start": [-10.351434346296093, 4.75], + "end": [11.50034033041072, 4.9654885437468295], + "thickness": 0.3 + }, + { + "start": [11.500170165205361, -2.5172557281265853], + "end": [14.5, -2.5], + "thickness": 0.3 + }, + { + "start": [5.5, -10], + "end": [5.5831841956249555, -9.878423098701989], + "thickness": 0.3 + }, + { + "start": [-12, -16.5], + "end": [-12, -10], + "thickness": 0.3 + }, + { + "start": [5.5, -10], + "end": [11.5, -10], + "thickness": 0.3 + }, + { + "start": [-12, -10], + "end": [-12, -8], + "thickness": 0.3 + }, + { + "start": [5.5, -10], + "end": [5.5, -8], + "thickness": 0.3 + }, + { + "start": [14.5, -2.5], + "end": [15, -2.5], + "thickness": 0.3 + }, + { + "start": [-12.10692010091972, 4.796798391140731], + "end": [-12.095594760434041, 4.797018721123448], + "thickness": 0.3 + }, + { + "start": [15, -2.5], + "end": [15, -10], + "thickness": 0.3 + }, + { + "start": [5.5, 5], + "end": [5.461079169382685, -9.999848352106541], + "thickness": 0.3 + }, + { + "start": [5.5, -10], + "end": [5.461079169382685, -9.999848352106541], + "thickness": 0.3 + }, + { + "start": [-12, -16.5], + "end": [-3.25, -16.5], + "thickness": 0.3 + }, + { + "start": [760.9372889375386, 10.625232057109535], + "end": [760.7581636476259, 19.832580384596376], + "thickness": 0.3 + } +] diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/scene-18.json b/packages/core/src/lib/__fixtures__/plate-corpus/scene-18.json new file mode 100644 index 0000000000..3963c27369 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/scene-18.json @@ -0,0 +1,650 @@ +[ + { + "start": [19.939939880371096, -10.01599154297472], + "end": [19.939939880371096, -10.65] + }, + { + "start": [0.7000000000000001, 9.700000000000001], + "end": [3.8578607224926524, 7.876711368560791] + }, + { + "start": [-7.608717441558838, -1.5650770664215088], + "end": [-7.726979255676269, -1.552593469619751] + }, + { + "start": [11.455429626075546, 9.814319660127849], + "end": [10.63615894317627, 11.3], + "thickness": 0.24384000000000003 + }, + { + "start": [-5.690646057128905, 10.032234191894531], + "end": [-3.5444197036071614, 9.551735754538917] + }, + { + "start": [-7.615394592285156, 10], + "end": [-7.615394592285156, 10.463148043048914], + "thickness": 0.24384000000000003 + }, + { + "start": [19.939939880371096, -10.65], + "end": [18.639955520629883, -10.65] + }, + { + "start": [17.948421478271484, -15.3209810256958], + "end": [13.83637523651123, -15.3209810256958], + "thickness": 0.24384000000000003, + "curveOffset": -0.9 + }, + { + "start": [9.69220875686434, -10.241491738846507], + "end": [4.176782608032227, -10.36285808441983] + }, + { + "start": [3.9054956436157227, 1.025624394416809], + "end": [9.304726600646973, 1.025624394416809] + }, + { + "start": [13.241896629333496, -15.3209810256958], + "end": [13.241896629333496, -14.866497039794922] + }, + { + "start": [-14.619835853576662, -1.614558184822898], + "end": [-14.63151028861872, -2.2177757846462076] + }, + { + "start": [3.8578607224926524, 7.876711368560791], + "end": [18.701940536499023, -0.6939775716690804] + }, + { + "start": [-4.848674692301671, 0.5492042303085316], + "end": [-6, 0.5492042303085315] + }, + { + "start": [-6.151180744171143, 10.032234191894531], + "end": [-5.69064605712891, 10.032234191894531], + "thickness": 0.24384000000000003, + "curveOffset": 0 + }, + { + "start": [14.825214385986328, 10.323075294494629], + "end": [14.921806968615234, 10.34895719900488] + }, + { + "start": [11.853577613830566, -5.648394584655762], + "end": [14.573285102844238, -5.648394584655762] + }, + { + "start": [-2.35, 11.327921867370605], + "end": [5.95, 11.327921867370605], + "thickness": 0.24384000000000003 + }, + { + "start": [-22.019411087036133, 10.05], + "end": [-20.75, 10.033278465270996] + }, + { + "start": [10.682235717773438, 7.876711368560791], + "end": [10.682235717773438, 8.628822326660156] + }, + { + "start": [-5.69064605712891, 10.032234191894531], + "end": [-3.5447208881378174, 10.032234191894531], + "thickness": 0.24384000000000003, + "curveOffset": 0 + }, + { + "start": [14.573285102844238, -5.648394584655762], + "end": [14.573285102844238, -3.512423038482666] + }, + { + "start": [9.304726600646973, 1.025624394416809], + "end": [9.304726600646973, 0.6499999999999988] + }, + { + "start": [9.694305221027042, -9.110234951220384], + "end": [9.692208756864343, -10.241491738846507], + "thickness": 0.3048 + }, + { + "start": [18.63868522644043, -8.3], + "end": [18.63962827379595, -10.044604756811339], + "thickness": 0.3048 + }, + { + "start": [18.63962827379595, -10.044604756811339], + "end": [18.639955520629883, -10.65], + "thickness": 0.3048 + }, + { + "start": [-6.151180744171143, 10.135338972575628], + "end": [-6.151180744171143, 10.032234191894531], + "thickness": 0.24384000000000003 + }, + { + "start": [-22.019411087036133, 10.05], + "end": [-31.900000000000002, 15.9] + }, + { + "start": [13.241896629333496, -10.16338124776528], + "end": [9.69220875686434, -10.241491738846507] + }, + { + "start": [-20.75, -2.187173366546631], + "end": [-20.759313551722524, -1.6255436662607732] + }, + { + "start": [9.69984245300293, -6.1223320960998535], + "end": [11.853577613830566, -6.050000000000001] + }, + { + "start": [13.241896629333496, -14.866497039794922], + "end": [9.683637619018555, -14.866497039794922], + "thickness": 0.3048 + }, + { + "start": [-14.63151028861872, -2.2177757846462076], + "end": [-20.75, -2.187173366546631] + }, + { + "start": [15.350000000000001, 6.742701530456543], + "end": [18.947187423706055, 6.742701530456543] + }, + { + "start": [18.639628273795942, -10.044604756811337], + "end": [13.241896629333496, -10.16338124776528] + }, + { + "start": [-6.151180744171143, 12.494219779968262], + "end": [-6.151180744171143, 10.135338972575628], + "thickness": 0.24384000000000003 + }, + { + "start": [14.825214385986328, 10.323075294494629], + "end": [14.82521438598099, 10.186612903992376], + "thickness": 0.24384000000000003 + }, + { + "start": [7.279928684234619, -6.1223320960998535], + "end": [9.69984245300293, -6.1223320960998535] + }, + { + "start": [5.95, 7.876711368560791], + "end": [8.316117858886718, 7.876711368560791] + }, + { + "start": [-3.543369770050049, 7.876711368560791], + "end": [3.857860722492652, 7.876711368560791] + }, + { + "start": [18.701940536499023, -0.693977571669079], + "end": [18.701940536499023, -1.8273159265518188] + }, + { + "start": [4.1767826080322275, -9.61469416155134], + "end": [9.694305221027037, -9.110234951220384] + }, + { + "start": [9.683637619018555, -14.866497039794922], + "end": [9.683637619018555, -15.425471305847168], + "thickness": 0.3048 + }, + { + "start": [22.85, -3.088988095238096], + "end": [22.85, -5.717136859893799], + "thickness": 0.24384000000000003 + }, + { + "start": [-4.848674692301673, -1.3452532612321277], + "end": [-4.848674692301671, 0.5492042303085316] + }, + { + "start": [18.6165771484375, -5.661283493041992], + "end": [18.6165771484375, -8.3] + }, + { + "start": [-20.75, 10.698215484619144], + "end": [-14.689992904663086, 10.698215484619144] + }, + { + "start": [18.639955520629883, -10.65], + "end": [18.639955520629883, -15.3209810256958], + "thickness": 0.3048 + }, + { + "start": [9.692208756864343, -10.241491738846507], + "end": [9.683637619018555, -14.866497039794922], + "thickness": 0.3048 + }, + { + "start": [9.279699325561523, -3.5124230384826665], + "end": [9.279699325561523, -3.405505418777466] + }, + { + "start": [1.6, 8.4], + "end": [0.7000000000000001, 9.700000000000001] + }, + { + "start": [-21.388275146484375, 2.1807816782228784], + "end": [-22.019411087036133, 2.1807816782228784] + }, + { + "start": [-7.608717441558838, -3.929737091064453], + "end": [1.5867223739624023, -3.929737091064453], + "thickness": 0.24384000000000003 + }, + { + "start": [19.939939880371096, -8.3], + "end": [19.939939880371096, -10.01599154297472] + }, + { + "start": [-6, 0.5492042303085315], + "end": [-7.726979255676269, 0.5492042303085313] + }, + { + "start": [22.85, -5.717136859893799], + "end": [20.5, -8.25], + "thickness": 0.24384000000000003, + "curveOffset": -0.6000000000000001 + }, + { + "start": [9.694305221027037, -9.110234951220384], + "end": [10.9, -9] + }, + { + "start": [-7.615394592285156, 12.494219779968262], + "end": [-16.68751501719158, 12.494219779968263], + "thickness": 0.24384000000000003 + }, + { + "start": [18.701940536499023, -1.8273159265518188], + "end": [19.784996032714844, -1.8273159265518188] + }, + { + "start": [1.5867223739624023, -3.929737091064453], + "end": [1.5867223739624023, -1.263342022895813] + }, + { + "start": [4.1767826080322275, 0.65], + "end": [3.9054956436157227, 0.65] + }, + { + "start": [18.947187423706055, 2.4522054195404053], + "end": [18.701940536499023, 2.4522054195404053] + }, + { + "start": [9.304726600646973, 0.6499999999999988], + "end": [8.996274948120117, 0.6499999999999989] + }, + { + "start": [15.845355033874512, -6.966160297393799], + "end": [15.845355033874512, -5.661283493041992] + }, + { + "start": [3.857860722492652, 7.876711368560791], + "end": [5.95, 7.876711368560791] + }, + { + "start": [7.279928684234619, -3.419575452804565], + "end": [7.279928684234619, -6.1223320960998535] + }, + { + "start": [14.82521438598099, 10.186612903992376], + "end": [18.480077743530273, 10.183781476684036], + "thickness": 0.24384000000000003 + }, + { + "start": [-7.749723434448242, -3.929737091064453], + "end": [-7.608717441558838, -3.929737091064453], + "thickness": 0.24384000000000003 + }, + { + "start": [-7.615394592285156, 10.463148043048914], + "end": [-7.615394592285156, 12.494219779968262], + "thickness": 0.24384000000000003 + }, + { + "start": [-3.5447208881378174, 10.032234191894531], + "end": [-3.544499964680044, 9.679781242184253], + "thickness": 0.24384000000000003 + }, + { + "start": [-7.726979255676268, -1.3452532612321277], + "end": [-4.848674692301673, -1.3452532612321277] + }, + { + "start": [-20.75, 10.033278465270996], + "end": [-20.75, 10.698215484619144] + }, + { + "start": [-7.615394592285156, 7.876711368560791], + "end": [-3.543369770050049, 7.876711368560791] + }, + { + "start": [18.639955520629883, -15.3209810256958], + "end": [17.948421478271484, -15.3209810256958], + "thickness": 0.24384000000000003 + }, + { + "start": [15.350000000000001, 9], + "end": [15.350000000000001, 6.742701530456543] + }, + { + "start": [11.853577613830566, -6.050000000000001], + "end": [11.853577613830566, -5.648394584655762] + }, + { + "start": [17.36077308654785, -4.79001522064209], + "end": [17.36077308654785, -5.661283493041992] + }, + { + "start": [9.683637619018555, -15.425471305847168], + "end": [4.176782608032227, -15.425471305847168], + "thickness": 0.762 + }, + { + "start": [15.845355033874512, -4.79001522064209], + "end": [17.36077308654785, -4.79001522064209] + }, + { + "start": [18.6165771484375, -5.661283493041992], + "end": [15.845355033874512, -5.661283493041992] + }, + { + "start": [-16.68751501719158, 12.494219779968263], + "end": [-7.615394592285156, 10.463148043048914] + }, + { + "start": [-7.726979255676269, 0.5492042303085313], + "end": [-7.726979255676268, -1.3452532612321277] + }, + { + "start": [10.63615894317627, 11.3], + "end": [14.825214385986328, 11.71553897857666], + "thickness": 0.24384000000000003, + "curveOffset": -0.7000000000000001 + }, + { + "start": [-16.68751501719158, 12.494219779968263], + "end": [-19.594457626342773, 12.494219779968263], + "thickness": 0.24384000000000003 + }, + { + "start": [20.150000000000002, -8.3], + "end": [18.63868522644043, -8.3], + "thickness": 0.24384000000000003 + }, + { + "start": [10.682235717773438, 8.628822326660156], + "end": [15.350000000000001, 9], + "curveOffset": -1.6 + }, + { + "start": [14.825214385986328, 11.71553897857666], + "end": [14.825214385986328, 10.323075294494629], + "thickness": 0.24384000000000003 + }, + { + "start": [-14.689992904663086, 10.698215484619144], + "end": [-14.689992904663086, 10] + }, + { + "start": [-14.689992904663086, 10], + "end": [-7.615394592285156, 10] + }, + { + "start": [4.176782608032227, -10.36285808441983], + "end": [4.176782608032227, -9.61469416155134], + "thickness": 0.762 + }, + { + "start": [13.83637523651123, -15.3209810256958], + "end": [13.241896629333496, -15.3209810256958], + "thickness": 0.24384000000000003 + }, + { + "start": [-22.019411087036133, 2.1807816782228784], + "end": [-22.019411087036133, 10.05] + }, + { + "start": [3.9054956436157227, 0.65], + "end": [3.9054956436157227, 1.025624394416809] + }, + { + "start": [18.6165771484375, -5.287202835083008], + "end": [18.6165771484375, -5.661283493041992] + }, + { + "start": [-21.377561569213867, -1.625199007987976], + "end": [-21.388275146484375, 2.1807816782228784] + }, + { + "start": [19.939939880371092, -10.01599154297472], + "end": [18.639628273795942, -10.044604756811337] + }, + { + "start": [19.784996032714844, -5.287202835083008], + "end": [18.6165771484375, -5.287202835083008] + }, + { + "start": [18.947187423706055, 6.742701530456543], + "end": [18.947187423706055, 2.4522054195404053], + "curveOffset": -2 + }, + { + "start": [-7.7269792556762695, -1.6021500971500968], + "end": [-14.619835853576662, -1.614558184822898], + "thickness": 0.0999744 + }, + { + "start": [18.701940536499023, 2.4522054195404053], + "end": [18.701940536499023, -0.693977571669079] + }, + { + "start": [-3.544499964680044, 9.679781242184253], + "end": [-3.5444197036071654, 9.551735754538917], + "thickness": 0.24384000000000003 + }, + { + "start": [5.95, 9.282072067260742], + "end": [8.329593658447266, 9.282072067260742], + "thickness": 0.24384000000000003, + "curveOffset": 0 + }, + { + "start": [1.5867223739624023, 0.5492042303085324], + "end": [-4.848674692301671, 0.5492042303085316] + }, + { + "start": [5.95, 9.282072067260742], + "end": [5.95, 7.876711368560791], + "thickness": 0.24384000000000003 + }, + { + "start": [8.329593658447266, 9.282072067260742], + "end": [8.316117858886718, 7.876711368560791], + "thickness": 0.24384000000000003 + }, + { + "start": [8.996274948120117, 0.6499999999999989], + "end": [8.996274948120117, -3.419575452804565] + }, + { + "start": [13.241896629333496, -10.163381247765278], + "end": [13.241896629333496, -6.966160297393799] + }, + { + "start": [4.176782608032227, -9.61469416155134], + "end": [4.1767826080322275, 0.65], + "thickness": 0.762 + }, + { + "start": [-7.608717441558838, -3.929737091064453], + "end": [-7.608717441558838, -1.5650770664215088], + "thickness": 0.24384000000000003 + }, + { + "start": [-6.6000000000000005, -10.600000000000001], + "end": [4.1767826080322275, -9.61469416155134] + }, + { + "start": [15.845355033874512, -5.661283493041992], + "end": [15.845355033874512, -4.79001522064209] + }, + { + "start": [8.996274948120117, 0.6499999999999989], + "end": [4.1767826080322275, 0.65] + }, + { + "start": [-20.759313551722524, -1.6255436662607732], + "end": [-21.377561569213867, -1.625199007987976] + }, + { + "start": [9.279699325561523, -3.405505418777466], + "end": [8.996274948120117, -3.419575452804565] + }, + { + "start": [3.9054956436157227, 0.5492042303085327], + "end": [3.9054956436157227, 0.65] + }, + { + "start": [1.5867223739624023, -1.263342022895813], + "end": [1.5867223739624023, 0.5492042303085324] + }, + { + "start": [22.85, 0.9], + "end": [22.85, -3.088988095238096], + "thickness": 0.24384000000000003 + }, + { + "start": [18.480077743530273, 10.183781476684036], + "end": [22.85, 0.9], + "thickness": 0.24384000000000003, + "curveOffset": -3.1 + }, + { + "start": [-7.615394592285156, 10], + "end": [-7.615394592285156, 7.876711368560791] + }, + { + "start": [9.69984245300293, -6.1223320960998535], + "end": [9.694305221027042, -9.110234951220384], + "thickness": 0.3048 + }, + { + "start": [34.300000000000004, -9.700000000000001], + "end": [19.939939880371092, -10.01599154297472] + }, + { + "start": [-19.48325538635254, -3.989025115966797], + "end": [-7.749723434448242, -3.989025115966797], + "thickness": 0.24384000000000003 + }, + { + "start": [-31.900000000000002, 15.9], + "end": [-16.68751501719158, 12.494219779968263] + }, + { + "start": [8.316117858886718, 7.876711368560791], + "end": [10.682235717773438, 7.876711368560791] + }, + { + "start": [-3.5444197036071614, 9.551735754538917], + "end": [1.6, 8.4] + }, + { + "start": [22.850000000000005, -3.088988095238097], + "end": [34.300000000000004, -9.700000000000001] + }, + { + "start": [4.176782608032227, -15.425471305847168], + "end": [4.176782608032227, -10.36285808441983], + "thickness": 0.762 + }, + { + "start": [-2.35, 9.679781242184253], + "end": [-2.35, 11.327921867370605], + "thickness": 0.24384000000000003 + }, + { + "start": [14.263835057201632, 10.187047805274954], + "end": [14.82521438598099, 10.186612903992376], + "thickness": 0.24384000000000003 + }, + { + "start": [5.95, 11.327921867370605], + "end": [5.95, 9.282072067260742], + "thickness": 0.24384000000000003 + }, + { + "start": [13.241896629333496, -14.866497039794922], + "end": [13.241896629333496, -10.163381247765278] + }, + { + "start": [17.36077308654785, -5.661283493041992], + "end": [18.6165771484375, -5.661283493041992] + }, + { + "start": [19.784996032714844, -1.8273159265518188], + "end": [19.784996032714844, -5.287202835083008] + }, + { + "start": [20.5, -8.25], + "end": [20.150000000000002, -8.3], + "thickness": 0.24384000000000003 + }, + { + "start": [13.241896629333496, -6.966160297393799], + "end": [15.845355033874512, -6.966160297393799] + }, + { + "start": [-6.151180744171143, 10.135338972575628], + "end": [-5.690646057128905, 10.032234191894531] + }, + { + "start": [-3.5444197036071654, 9.551735754538917], + "end": [-3.543369770050049, 7.876711368560791], + "thickness": 0.24384000000000003 + }, + { + "start": [-7.726979255676268, -1.3452532612321277], + "end": [-7.726979255676269, -1.552593469619751] + }, + { + "start": [20.150000000000002, -8.3], + "end": [19.939939880371096, -8.3], + "thickness": 0.24384000000000003 + }, + { + "start": [4.176782608032227, -10.36285808441983], + "end": [-6.6000000000000005, -10.600000000000001] + }, + { + "start": [18.701940536499023, -0.6939775716690804], + "end": [22.850000000000005, -3.088988095238097] + }, + { + "start": [-6, 0.5492042303085315], + "end": [-22.019411087036133, 10.05] + }, + { + "start": [8.996274948120117, -3.419575452804565], + "end": [7.279928684234619, -3.419575452804565] + }, + { + "start": [-3.544499964680044, 9.679781242184253], + "end": [-2.35, 9.679781242184253], + "thickness": 0.24384000000000003 + }, + { + "start": [14.573285102844238, -3.512423038482666], + "end": [9.279699325561523, -3.5124230384826665] + }, + { + "start": [3.9054956436157227, 0.5492042303085327], + "end": [1.5867223739624023, 0.5492042303085324] + }, + { + "start": [-7.615394592285156, 10.463148043048914], + "end": [-6.151180744171143, 10.135338972575628] + } +] diff --git a/packages/core/src/lib/__fixtures__/plate-corpus/scene-28.json b/packages/core/src/lib/__fixtures__/plate-corpus/scene-28.json new file mode 100644 index 0000000000..69fb3b9a55 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/plate-corpus/scene-28.json @@ -0,0 +1,219 @@ +[ + { + "start": [-6, 13], + "end": [-6, 9] + }, + { + "start": [-1.0093021500951498, 10.599566410016669], + "end": [-3.4000000000000004, 10.600000000000001] + }, + { + "start": [8, 5], + "end": [8, 4.7] + }, + { + "start": [-8.946613029388908, 8.895270547439068], + "end": [-8.946613029388908, -0.9057604797302758] + }, + { + "start": [-3.5, 9], + "end": [-8.946613029388908, 9] + }, + { + "start": [-8.946613029388908, 9], + "end": [-9, 9] + }, + { + "start": [-1, 9], + "end": [-3.4000000000000004, 9.003571428571428] + }, + { + "start": [-1.5, 8], + "end": [1.012131616401668, 8.000147197783704] + }, + { + "start": [-9, 7], + "end": [-11, 7] + }, + { + "start": [8.013190775511173, 6.999912997936027], + "end": [8.053386970611092, 13.094239520269724] + }, + { + "start": [1.0242632328033359, 7.000294395567409], + "end": [4.000000007203713, 7.000132004563863] + }, + { + "start": [-8.946613029388908, 9], + "end": [-8.946613029388908, 8.895270547439068] + }, + { + "start": [-8.946613029388908, 10], + "end": [-8.946613029388908, 9.1] + }, + { + "start": [-11, 7], + "end": [-11, 10] + }, + { + "start": [1.012131616401668, 8.000147197783704], + "end": [1.0533869706110917, 4.6000000000000005] + }, + { + "start": [-3.4000000000000004, 9.003571428571428], + "end": [-3.5, 9] + }, + { + "start": [1.0533869706110917, 13.094239520269724], + "end": [-8.946613029388908, 13.094239520269724] + }, + { + "start": [4.000000007203713, 7.000132004563863], + "end": [4, 5] + }, + { + "start": [1.0533869706110917, 4.7], + "end": [1.0533869706110917, 4.6000000000000005] + }, + { + "start": [1.0533869706110917, 10.094239520269724], + "end": [1.0533869706110917, 11.3], + "curveOffset": 0 + }, + { + "start": [-6, 9], + "end": [-8.946613029388908, 9] + }, + { + "start": [-3.4000000000000004, 10.600000000000001], + "end": [-3.4000000000000004, 9.003571428571428] + }, + { + "start": [1.0533869706110917, 11.4], + "end": [1.0533869706110917, 13.094239520269724] + }, + { + "start": [1.0533869706110917, 11.3], + "end": [1.0533869706110917, 11.4] + }, + { + "start": [2.0533869706110917, -0.9057604797302758], + "end": [8.053386970611092, -0.9057604797302758] + }, + { + "start": [-3.5, 9], + "end": [-3.4000000000000004, 9.003571428571428] + }, + { + "start": [-3.4000000000000004, 9.003571428571428], + "end": [-3.5, 9] + }, + { + "start": [-1.0118290086549215, 10.653777112513982], + "end": [-1.0093021500951498, 10.599566410016669] + }, + { + "start": [-8.946613029388908, -0.9057604797302758], + "end": [1.0533869706110917, -0.9057604797302758] + }, + { + "start": [8.053386970611092, -0.9057604797302758], + "end": [8, 5] + }, + { + "start": [1.0533869706110917, 11.3], + "end": [1.0518091097261457, 11.26444468840426] + }, + { + "start": [8.053386970611092, 13.094239520269724], + "end": [1.0533869706110917, 13.094239520269724] + }, + { + "start": [1.0533869706110917, -0.9057604797302758], + "end": [2.0533869706110917, -0.9057604797302758] + }, + { + "start": [-8.946613029388908, 9.1], + "end": [-8.946613029388908, 9] + }, + { + "start": [1.0533869706110917, 4.6000000000000005], + "end": [1.0533869706110917, -0.9057604797302758] + }, + { + "start": [1.0533869706110917, 9.594239520269724], + "end": [1.0533869706110917, 10.094239520269724] + }, + { + "start": [1.0533869706110917, 10.094239520269724], + "end": [1.0533869706110917, 9.094239520269724] + }, + { + "start": [-3.5, 9], + "end": [-6, 9] + }, + { + "start": [-11, 13.100000000000001], + "end": [-9, 13.100000000000001] + }, + { + "start": [1.0518091097261457, 11.26444468840426], + "end": [1.052125690820555, 11.285384971821378] + }, + { + "start": [-8.946613029388908, 9], + "end": [-9, 9] + }, + { + "start": [1.0533869706110917, 11.4], + "end": [-0.8999999999999999, 11.4] + }, + { + "start": [1, 9], + "end": [1.012131616401668, 8.000147197783704] + }, + { + "start": [-8.946613029388908, 8.895270547439068], + "end": [-8.8, 8.9] + }, + { + "start": [-11, 10], + "end": [-11, 13.100000000000001] + }, + { + "start": [-1, 9], + "end": [-3.4000000000000004, 9.003571428571428] + }, + { + "start": [-0.9, 10.600000000000001], + "end": [-1.0093021500951498, 10.599566410016669] + }, + { + "start": [-8.946613029388908, 13.094239520269724], + "end": [-8.946613029388908, 10] + }, + { + "start": [8, 5], + "end": [8.013190775511173, 6.999912997936027] + }, + { + "start": [-0.8999999999999999, 11.4], + "end": [-0.9, 10.600000000000001] + }, + { + "start": [4.000000007203713, 7.000132004563863], + "end": [8.013190775511173, 6.999912997936027] + }, + { + "start": [-3.4000000000000004, 9.003571428571428], + "end": [-3.4000000000000004, 8.9] + }, + { + "start": [8, 5], + "end": [1.1, 4.9] + }, + { + "start": [-8.946613029388908, 10], + "end": [-11, 10] + } +] diff --git a/packages/core/src/lib/__fixtures__/stacked-walls-doubled-span.json b/packages/core/src/lib/__fixtures__/stacked-walls-doubled-span.json new file mode 100644 index 0000000000..157ca68430 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/stacked-walls-doubled-span.json @@ -0,0 +1,214 @@ +[ + { + "id": "wall_0buah0gayd67zein", + "start": [1.2000000000000002, -50.800000000000004], + "end": [1.1500000000000001, -53], + "thickness": 0.3 + }, + { + "id": "wall_0t51llovtq1mngit", + "start": [48.750801224, -47.75], + "end": [48.750801224, -44.25] + }, + { + "id": "wall_0z0tb5hczhzkicv2", + "start": [-27, 47.85], + "end": [-27.0499821824094, 47.84905630404082], + "thickness": 0.3 + }, + { + "id": "wall_3i49b359jdotrjoz", + "start": [1, -31.5], + "end": [13.5, -32], + "thickness": 0.12 + }, + { + "id": "wall_539wcnubv6b884n2", + "start": [-27.700000000000003, 12.200000000000001], + "end": [8.75, 12.100000000000001], + "thickness": 0.12 + }, + { + "id": "wall_799jvtp9vv9wnksn", + "start": [8.75, 12.100000000000001], + "end": [8.4, -14.4], + "thickness": 0.12 + }, + { + "id": "wall_799uk401ql6c949h", + "start": [48.750801224, -44.25], + "end": [45.25, -44.25] + }, + { + "id": "wall_7pnqwpdbujknrq88", + "start": [38.6, -16.650000000000002], + "end": [69.15, -19.150000000000002], + "thickness": 0.3 + }, + { + "id": "wall_8hgdfw3o2ocsct40", + "start": [-76, -52.2], + "end": [-5.15, -52.900000000000006], + "thickness": 0.12 + }, + { + "id": "wall_8ztrulaey5d9ux7e", + "start": [-100.45, 12.350000000000001], + "end": [-27.6, 12.3], + "thickness": 0.3 + }, + { + "id": "wall_9q8u1qbjqqy4grgy", + "start": [-17.940739880614473, 58.7283329621516], + "end": [12.353257533635814, 58.619450892274706], + "thickness": 0.3 + }, + { + "id": "wall_9z6b4hlttqiyo7jq", + "start": [23.650000000000002, -16.150000000000002], + "end": [38.7, -16.75], + "thickness": 0.3 + }, + { + "id": "wall_admede8av81da371", + "start": [-14.5, 37], + "end": [-40.5, 33.5], + "thickness": 0.12 + }, + { + "id": "wall_au2morrgo42rk77l", + "start": [-30.150000000000002, -14.700000000000001], + "end": [-72.65, -15.100000000000001], + "thickness": 0.12 + }, + { + "id": "wall_aur1a95teabwrky7", + "start": [8.4, -14.4], + "end": [-30.150000000000002, -14.700000000000001], + "thickness": 0.12 + }, + { + "id": "wall_cotdh4f47wmpflb2", + "start": [45.25, -44.25], + "end": [45.25, -47.75] + }, + { + "id": "wall_ee4zhhjb4fi90xaj", + "start": [12.5, 58.5], + "end": [42.54774891337004, 53.99676577557223], + "thickness": 0.12 + }, + { + "id": "wall_fit4cp0ihxlptarx", + "start": [42.289604045895906, -17.327145619968125], + "end": [43.12614505534458, 12.790235276523092], + "thickness": 0.3 + }, + { + "id": "wall_gkwh0jc3nutyhnv1", + "start": [69.15, -19.150000000000002], + "end": [78.15, 59.800000000000004], + "thickness": 0.3 + }, + { + "id": "wall_hruj7zdbskukpqh1", + "start": [-17.85, 48.1], + "end": [-27.0499821824094, 47.84905630404082], + "thickness": 0.3 + }, + { + "id": "wall_i07e8aphv2jtgrks", + "start": [78.15, 59.800000000000004], + "end": [43.1, 62.150000000000006], + "thickness": 0.3 + }, + { + "id": "wall_jqpbh4kr4jw05on5", + "start": [-101.15, 46.45], + "end": [-100.45, 12.350000000000001], + "thickness": 0.3 + }, + { + "id": "wall_lfv6im8ottlj9h84", + "start": [1.1500000000000001, -53], + "end": [-5.15, -52.900000000000006], + "thickness": 0.3 + }, + { + "id": "wall_lk2qegwqhtytteuk", + "start": [-27.0499821824094, 47.84905630404082], + "end": [-101.15, 46.45], + "thickness": 0.3 + }, + { + "id": "wall_lv02jj2ifiy3g2z2", + "start": [44, 74], + "end": [43.022004954942034, 60.99850951659875], + "thickness": 0.3 + }, + { + "id": "wall_mfson1hg9mtsold5", + "start": [45.25, -47.75], + "end": [48.750801224, -47.75] + }, + { + "id": "wall_nldk13dw2re5vghr", + "start": [13.5, 79], + "end": [44, 74], + "thickness": 0.3 + }, + { + "id": "wall_o1bwdbvo6i4s6k20", + "start": [22.900000000000002, -41.400000000000006], + "end": [23.650000000000002, -16.150000000000002], + "thickness": 0.3 + }, + { + "id": "wall_pr7pgj38irmu73rk", + "start": [1.2000000000000002, -31.650000000000002], + "end": [1.2000000000000002, -50.800000000000004], + "thickness": 0.3 + }, + { + "id": "wall_q81j8ks3nm7w4063", + "start": [43.022004954942034, 60.99850951659875], + "end": [42.54774891337004, 53.99676577557223], + "thickness": 0.3 + }, + { + "id": "wall_qfbvbfkowayvtkj4", + "start": [13.5, -41], + "end": [23, -41.5], + "thickness": 0.12 + }, + { + "id": "wall_t0lz7lwyfyjsue39", + "start": [13.5, -32], + "end": [13.5, -41], + "thickness": 0.12 + }, + { + "id": "wall_ty7f4dxd59anir0z", + "start": [-17.8, 58.800000000000004], + "end": [-17.85, 48.1], + "thickness": 0.3 + }, + { + "id": "wall_v0g2xga8vnehv0zb", + "start": [-72.65, -15.100000000000001], + "end": [-76, -52.2], + "thickness": 0.12 + }, + { + "id": "wall_vcums7iypmry4ih7", + "start": [43.1, 62.150000000000006], + "end": [43.022004954942034, 60.99850951659875], + "thickness": 0.3 + }, + { + "id": "wall_z30bamriqv0cy5ko", + "start": [12.5, 58.5], + "end": [13.5, 79], + "thickness": 0.3 + } +] diff --git a/packages/core/src/lib/__fixtures__/structure-test-06-walls.json b/packages/core/src/lib/__fixtures__/structure-test-06-walls.json new file mode 100644 index 0000000000..2d3c8278d8 --- /dev/null +++ b/packages/core/src/lib/__fixtures__/structure-test-06-walls.json @@ -0,0 +1,272 @@ +[ +{ +"id": "wall_0bw8xk5jy75tml0l", +"start": [ +-4.3, +-0.5 +], +"end": [ +-2.4000000000000004, +-0.5 +] +}, +{ +"id": "wall_134udpqg2d6uj0rg", +"start": [ +-4.3, +3.7961320877075195 +], +"end": [ +-4.3, +3.7066304968853787 +] +}, +{ +"id": "wall_17l71osx961nut0i", +"start": [ +-9.43950080871582, +9.274081230163574 +], +"end": [ +-9.130577087402344, +9.274081230163574 +] +}, +{ +"id": "wall_19wiqyoanxuvhdyu", +"start": [ +-8.832283020019531, +7.5752716064453125 +], +"end": [ +-9.388261795043945, +7.5752716064453125 +] +}, +{ +"id": "wall_1dpzapxwuurh2b1i", +"start": [ +1.2857474088668823, +3.741950273513794 +], +"end": [ +1.50185227394104, +3.7364373207092285 +] +}, +{ +"id": "wall_1tdxn0zd7iocci1a", +"start": [ +1.4946867227554321, +6.4365010261535645 +], +"end": [ +1.2184314563333623, +6.4365010261535645 +], +"curveOffset": 0 +}, +{ +"id": "wall_43wuow7l81niwkwq", +"start": [ +-4.270412261516859, +9.830339087577286 +], +"end": [ +1.218431456333362, +9.801971998038184 +], +"thickness": 0.3 +}, +{ +"id": "wall_4nzqp8290ccn916r", +"start": [ +1.50185227394104, +3.7364373207092285 +], +"end": [ +1.4946867227554321, +6.4365010261535645 +] +}, +{ +"id": "wall_5w7o6b80riwrjwpr", +"start": [ +-4.3, +-0.5 +], +"end": [ +-4.3, +3.7066304968853787 +] +}, +{ +"id": "wall_80ejhuehwf2b5oqo", +"start": [ +-9.388261795043945, +7.5752716064453125 +], +"end": [ +-9.388261795043945, +9.261122703552246 +] +}, +{ +"id": "wall_8b8sgc5n0e2jt7r6", +"start": [ +1.2184314563333623, +6.4365010261535645 +], +"end": [ +1.218431456333362, +9.801971998038184 +] +}, +{ +"id": "wall_cz7kdj1t6g6xvrcx", +"start": [ +1.285523056983948, +3.2646865844726562 +], +"end": [ +1.2857474088668823, +3.741950273513794 +] +}, +{ +"id": "wall_e25bnhb7wwvell5i", +"start": [ +-2.3000000000000003, +0.4 +], +"end": [ +0.5562703013420105, +0.4 +], +"thickness": 0.3 +}, +{ +"id": "wall_evweopqau81len8e", +"start": [ +-8.8, +3.8000000000000003 +], +"end": [ +-4.3, +3.7961320877075195 +] +}, +{ +"id": "wall_f3qlniryhtzq86ut", +"start": [ +-4.3, +3.7961320877075195 +], +"end": [ +-4.270412261516859, +9.830339087577286 +] +}, +{ +"id": "wall_f3ytpyt5py5xbk3c", +"start": [ +-2.4000000000000004, +1.1191966533660889 +], +"end": [ +-2.4000000000000004, +-0.5 +], +"thickness": 0.3 +}, +{ +"id": "wall_fsvkkra39wvn18x2", +"start": [ +0.5562703013420105, +0.4 +], +"end": [ +0.5562703013420105, +0.9192224870513782 +] +}, +{ +"id": "wall_jga25xx62nobck6l", +"start": [ +1.2855230569839478, +0.9192224870513782 +], +"end": [ +1.285523056983948, +3.2646865844726562 +] +}, +{ +"id": "wall_la8gx1noezd905fm", +"start": [ +-8.8, +3.8000000000000003 +], +"end": [ +-8.832283020019531, +7.5752716064453125 +] +}, +{ +"id": "wall_uawqw2awuqnxozqd", +"start": [ +-5.06746244430542, +9.834458351135254 +], +"end": [ +-4.270412261516859, +9.830339087577286 +], +"thickness": 0.3 +}, +{ +"id": "wall_wbto8go16ltl0nb1", +"start": [ +0.5562703013420105, +0.9192224870513782 +], +"end": [ +1.2855230569839478, +0.9192224870513782 +] +}, +{ +"id": "wall_xnc8188qfkunhxcg", +"start": [ +-9.130577087402344, +9.274081230163574 +], +"end": [ +-9.110458374023438, +10.478736877441406 +] +}, +{ +"id": "wall_xvz8d8o2cue9p5l7", +"start": [ +-9.110458374023438, +10.478736877441406 +], +"end": [ +-5.06746244430542, +10.478736877441406 +] +}, +{ +"id": "wall_ytjwyc8vmryjtv2l", +"start": [ +-5.06746244430542, +10.478736877441406 +], +"end": [ +-5.06746244430542, +9.834458351135254 +], +"thickness": 0.3 +} +] \ No newline at end of file diff --git a/packages/core/src/lib/absorb-wall-separators.ts b/packages/core/src/lib/absorb-wall-separators.ts new file mode 100644 index 0000000000..e031ee7baa --- /dev/null +++ b/packages/core/src/lib/absorb-wall-separators.ts @@ -0,0 +1,74 @@ +import type { WallNode } from '../schema' +import { SeparatorNode } from '../schema/nodes/separator' +import { omitUndefined } from '../utils/omit-undefined' +import { sampleWallPointsForRoomDetection } from './room-graph' +import type { NodePatch, SceneNodes } from './structure-kernel' + +export function absorbWallSeparators(nodes: SceneNodes, levelId: string, mintId: () => string) { + const walls = Object.values(nodes).filter( + (n): n is WallNode => n.type === 'wall' && n.parentId === levelId, + ) + const lines = walls.flatMap((wall) => { + const points = sampleWallPointsForRoomDetection(wall) + return points.slice(1).map((end, i) => [points[i]!, end] as const) + }) + const patches: NodePatch[] = [] + const next = { ...nodes } + for (const node of Object.values(nodes)) { + if (node.type !== 'separator' || node.parentId !== levelId) continue + const [x, y] = node.start, + dx = node.end[0] - x, + dy = node.end[1] - y + const length = Math.hypot(dx, dy) + if (length < 1e-7) continue + let ranges: [number, number][] = [[0, 1]] + for (const [a, b] of lines) { + if ([a, b].some((p) => Math.abs((p.x - x) * dy - (p.y - y) * dx) / length > 1e-6)) continue + const ts = [a, b].map((p) => ((p.x - x) * dx + (p.y - y) * dy) / (length * length)) + const lo = Math.min(...ts), + hi = Math.max(...ts) + ranges = ranges.flatMap(([start, end]) => { + if (hi <= start + 1e-7 || lo >= end - 1e-7) return [[start, end]] + return [ + ...(lo > start + 1e-7 ? [[start, lo] as [number, number]] : []), + ...(hi < end - 1e-7 ? [[hi, end] as [number, number]] : []), + ] + }) + } + if (ranges.length === 1 && ranges[0]![0] === 0 && ranges[0]![1] === 1) continue + if (!ranges.length) { + delete next[node.id] + patches.push({ op: 'delete', id: node.id }) + } + for (const [i, [a, b]] of ranges.entries()) { + const separator = omitUndefined( + SeparatorNode.parse({ + ...node, + id: i ? mintId() : node.id, + start: [x + dx * a, y + dy * a], + end: [x + dx * b, y + dy * b], + }), + ) + next[separator.id] = separator + patches.push( + i + ? { op: 'create', node: separator } + : { op: 'update', id: node.id, data: { start: separator.start, end: separator.end } }, + ) + } + } + if (patches.length) { + const level = next[levelId] + if (level?.type === 'level') { + const children = [ + ...level.children.filter((id) => !!next[id]), + ...patches.flatMap((p) => + p.op === 'create' && p.node.type === 'separator' ? [p.node.id] : [], + ), + ] + next[levelId] = { ...level, children } + patches.push({ op: 'update', id: level.id, data: { children } }) + } + } + return { nodes: patches.length ? next : nodes, patches } +} diff --git a/packages/core/src/lib/canonical-opening-ring.ts b/packages/core/src/lib/canonical-opening-ring.ts new file mode 100644 index 0000000000..9948057157 --- /dev/null +++ b/packages/core/src/lib/canonical-opening-ring.ts @@ -0,0 +1,21 @@ +import type { Ring } from './polygon-boolean' + +export function canonicalOpeningRing(polygon: Ring): Ring { + const ring = polygon.map(([x, z]): [number, number] => [ + Math.round(x * 10_000) / 10_000, + Math.round(z * 10_000) / 10_000, + ]) + if ( + ring.length > 1 && + ring[0]![0] === ring[ring.length - 1]![0] && + ring[0]![1] === ring[ring.length - 1]![1] + ) + ring.pop() + if (ring.length < 3) return ring + const rotations = [ring, [...ring].reverse()].flatMap((points) => + points.map((_, index) => [...points.slice(index), ...points.slice(0, index)]), + ) + return rotations.sort((left, right) => + JSON.stringify(left).localeCompare(JSON.stringify(right)), + )[0]! +} diff --git a/packages/core/src/lib/ceiling-children.ts b/packages/core/src/lib/ceiling-children.ts new file mode 100644 index 0000000000..755d16394a --- /dev/null +++ b/packages/core/src/lib/ceiling-children.ts @@ -0,0 +1,52 @@ +import type { AnyNodeId, CeilingNode as CeilingNodeType } from '../schema' +import { containsPoint, distanceToBoundary, type Ring } from './polygon-boolean' +import { type Point2D, pointFromTuple, pointToTuple } from './room-graph' + +export function partitionCeilingChildren( + ceiling: CeilingNodeType, + roomIndices: number[], + detected: Array<{ poly: Point2D[]; holes: Ring[] }>, + fallbackRoomIndex: number | undefined, + childPosition: (childId: AnyNodeId) => [number, number] | undefined, +) { + const assignments = new Map() + for (const roomIndex of roomIndices) assignments.set(roomIndex, []) + + for (const childId of ceiling.children) { + const tuple = childPosition?.(childId) + const point = tuple ? pointFromTuple(tuple) : undefined + const boundaryRoomIndices = point + ? roomIndices.filter((roomIndex) => { + const room = detected[roomIndex] + return room + ? distanceToBoundary( + [{ outer: room.poly.map(pointToTuple), holes: room.holes }], + pointToTuple(point), + ) <= 1e-7 + : false + }) + : [] + const interiorRoomIndex = + point && boundaryRoomIndices.length === 0 + ? roomIndices.find((roomIndex) => { + const room = detected[roomIndex] + return room + ? containsPoint( + [{ outer: room.poly.map(pointToTuple), holes: room.holes }], + pointToTuple(point), + ) + : false + }) + : undefined + const roomIndex = + interiorRoomIndex ?? + (fallbackRoomIndex !== undefined && boundaryRoomIndices.includes(fallbackRoomIndex) + ? fallbackRoomIndex + : boundaryRoomIndices[0]) ?? + fallbackRoomIndex ?? + roomIndices[0] + if (roomIndex !== undefined) assignments.get(roomIndex)?.push(childId) + } + + return assignments +} diff --git a/packages/core/src/lib/ceiling-surface.test.ts b/packages/core/src/lib/ceiling-surface.test.ts new file mode 100644 index 0000000000..d542749ffe --- /dev/null +++ b/packages/core/src/lib/ceiling-surface.test.ts @@ -0,0 +1,238 @@ +import { describe, expect, test } from 'bun:test' +import { setZoneIntent } from '../commands/structure/set-zone-intent' +import { transformZone } from '../commands/structure/transform-zone' +import type { AnyNode, AnyNodeId } from '../schema' +import { CeilingNode, LevelNode, WallNode, ZoneNode } from '../schema' +import useScene from '../store/use-scene' +import { + ceilingPaintRegions, + ceilingRegionRole, + computeCeilingSurfaceCells, + parseCeilingRegionRole, +} from './ceiling-surface' +import { area } from './polygon-boolean' +import { type NodePatch, reconcileLevelStructure, type SceneNodes } from './structure-kernel' + +const levelId = 'level_ceiling_regions' +const ring: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +const rect = (x: number, z: number, w: number, d: number): [number, number][] => [ + [x, z], + [x + w, z], + [x + w, z + d], + [x, z + d], +] + +function fixture() { + const walls = ring.map((start, i) => + WallNode.parse({ + id: `wall_${i}`, + parentId: levelId, + start, + end: ring[(i + 1) % 4], + thickness: 0.2, + }), + ) + const level = LevelNode.parse({ id: levelId, children: walls.map((wall) => wall.id) }) + return Object.fromEntries([level, ...walls].map((node) => [node.id, node])) as SceneNodes +} +function apply(nodes: SceneNodes, patches: NodePatch[]): Record { + const result = { ...nodes } + for (const patch of patches) { + if (patch.op === 'delete') delete result[patch.id] + else if (patch.op === 'create') result[patch.node.id] = patch.node + else { + const node = { ...result[patch.id], ...patch.data } as AnyNode + for (const key of Object.keys(patch.data)) + if (patch.data[key as keyof typeof patch.data] === undefined) + delete (node as unknown as Record)[key] + result[patch.id] = node + } + } + return result +} +function run(nodes: SceneNodes) { + let count = 0 + const plan = reconcileLevelStructure({ + levelId, + nodes, + mintId: (kind) => { + let id: string + do id = `${kind}_${String(++count).padStart(4, '0')}` + while (nodes[id]) + return id + }, + }) + return apply(nodes, plan.patches) +} +const zones = (nodes: SceneNodes) => + Object.values(nodes).filter((node): node is ZoneNode => node.type === 'zone') +const ceilings = (nodes: SceneNodes) => + Object.values(nodes).filter((node): node is CeilingNode => node.type === 'ceiling') +const regionArea = (zone: ZoneNode) => + area((zone.ceiling?.regions ?? []).map((region) => ({ outer: region.polygon, holes: [] }))) + +function paintedRoom() { + const nodes = run(fixture()) + const zone = zones(nodes)[0]! + // One patch across the whole room width, one only on its left end. + nodes[zone.id] = { + ...zone, + seed: [1, 2], + ceiling: { + regions: [ + { id: 'band', polygon: rect(0, 1, 8, 2), finish: 'library:blue' }, + { id: 'corner', polygon: rect(0, 0, 1, 1), finish: 'library:red' }, + ], + }, + } + return { nodes, zoneId: zone.id } +} + +describe('ceiling surface cells', () => { + test('regions take what later ones leave; the ceiling keeps the rest', () => { + const cells = computeCeilingSurfaceCells( + rect(0, 0, 4, 4), + [rect(3, 3, 0.5, 0.5)], + [ + { id: 'a', polygon: rect(0, 0, 2, 4), finish: 'library:a' }, + { id: 'b', polygon: rect(1, 0, 2, 4), finish: 'library:b' }, + { id: 'outside', polygon: rect(10, 10, 1, 1), finish: 'library:c' }, + ], + ) + const byRole = new Map(cells.map((cell) => [cell.role, cell])) + expect([...byRole.keys()].sort()).toEqual(['region:a', 'region:b', 'surface']) + expect(area(byRole.get('region:b')!.polygons)).toBeCloseTo(8) + expect(area(byRole.get('region:a')!.polygons)).toBeCloseTo(4) + // 16 − 12 painted − the 0.25 hole. + expect(area(byRole.get('surface')!.polygons)).toBeCloseTo(3.75) + expect(byRole.get('region:b')!.finish).toBe('library:b') + }) + + test('roles round-trip, and an automatic ceiling reads its room while a manual one reads itself', () => { + expect(parseCeilingRegionRole(ceilingRegionRole('r1'))).toBe('r1') + expect(parseCeilingRegionRole('surface')).toBeNull() + const zone = ZoneNode.parse({ + id: 'zone_room', + name: 'Room', + polygon: ring, + ceiling: { regions: [{ id: 'z', polygon: ring, finish: 'library:z' }] }, + }) + const auto = CeilingNode.parse({ + id: 'ceiling_auto', + polygon: ring, + boundary: 'auto', + zoneId: zone.id, + regions: [{ id: 'ignored', polygon: ring, finish: 'library:x' }], + }) + const manual = CeilingNode.parse({ + id: 'ceiling_manual', + polygon: ring, + regions: [{ id: 'own', polygon: ring, finish: 'library:y' }], + }) + const nodes = { [zone.id]: zone, [auto.id]: auto, [manual.id]: manual } + expect(ceilingPaintRegions(auto, nodes).map((region) => region.id)).toEqual(['z']) + expect(ceilingPaintRegions(manual, nodes).map((region) => region.id)).toEqual(['own']) + }) +}) + +describe('ceiling regions follow their room', () => { + test('a rebuilt ceiling keeps drawing the room regions (the room owns them)', () => { + const { nodes, zoneId } = paintedRoom() + const before = ceilings(nodes).find((ceiling) => ceiling.zoneId === zoneId)! + const { [before.id]: _, ...withoutCeiling } = nodes + const rebuilt = run(withoutCeiling) + const ceiling = ceilings(rebuilt).find((node) => node.zoneId === zoneId)! + expect(ceiling).toBeDefined() + expect(ceilingPaintRegions(ceiling, rebuilt).map((region) => region.id)).toEqual([ + 'band', + 'corner', + ]) + expect(run(rebuilt)).toEqual(rebuilt) + }) + + test('divide clips each room its part; merge brings them back together', () => { + const { nodes, zoneId } = paintedRoom() + const divider = WallNode.parse({ + id: 'wall_divider', + parentId: levelId, + start: [2, 0], + end: [2, 4], + }) + const divided = run({ ...nodes, [divider.id]: divider }) + const rooms = zones(divided) + expect(rooms).toHaveLength(2) + const kept = rooms.find((room) => room.id === zoneId)! + const other = rooms.find((room) => room.id !== zoneId)! + // The band spans both rooms; the corner stays in the seed room. + expect(kept.ceiling?.regions?.map((region) => region.id)).toEqual(['band', 'corner']) + expect(other.ceiling?.regions?.map((region) => region.id)).toEqual(['band']) + expect(regionArea(kept) + regionArea(other)).toBeCloseTo(16 + 1) + expect(run(divided)).toEqual(divided) + + const { wall_divider: _, ...merged } = divided + const rejoined = run(merged) + const survivor = zones(rejoined)[0]! + expect(zones(rejoined)).toHaveLength(1) + expect(regionArea(survivor)).toBeCloseTo(17) + expect(new Set(survivor.ceiling?.regions?.map((region) => region.id))).toEqual( + new Set(['band', 'corner']), + ) + }) + + test('moving the room moves its ceiling regions; raising its floor leaves them', () => { + const { nodes, zoneId } = paintedRoom() + let count = 0 + const plan = transformZone(nodes, { + zoneId, + translate: [10, 0], + mintId: (kind: string) => `${kind}_moved_${++count}`, + }) + const moved = apply(nodes, plan.changes as NodePatch[]) + const zone = moved[zoneId] as ZoneNode + expect(zone.ceiling?.regions?.[1]?.polygon).toEqual(rect(10, 0, 1, 1)) + + const raised = setZoneIntent(nodes, { zoneId, patch: { floor: { elevation: 0.3 } } }) + const after = apply(nodes, raised.changes as NodePatch[]) + expect((after[zoneId] as ZoneNode).ceiling).toEqual((nodes[zoneId] as ZoneNode).ceiling) + }) + + test('set_zone_intent writes and clears ceiling regions without touching the floor', () => { + const { nodes, zoneId } = paintedRoom() + const regions = [{ id: 'mcp', polygon: rect(3, 1, 2, 2), finish: 'library:green' }] + const set = setZoneIntent(nodes, { zoneId, patch: { ceiling: { regions } } }) + expect(set.changes).toEqual([{ op: 'update', id: zoneId, data: { ceiling: { regions } } }]) + const cleared = setZoneIntent(nodes, { zoneId, patch: { ceiling: null } }) + expect(cleared.changes).toEqual([{ op: 'update', id: zoneId, data: { ceiling: undefined } }]) + expect(() => + setZoneIntent(nodes, { + zoneId, + patch: { ceiling: { regions: [{ id: 'bad', polygon: 'x' }] } } as never, + }), + ).toThrow() + }) +}) + +test('a room ceiling made manual keeps its painted parts on itself', () => { + const { nodes, zoneId } = paintedRoom() + const ceiling = ceilings(nodes).find((node) => node.zoneId === zoneId)! + const saved = useScene.getState() + globalThis.requestAnimationFrame ??= (callback: FrameRequestCallback) => { + callback(0) + return 0 + } + try { + useScene.setState({ nodes, readOnly: false } as never) + useScene.getState().detachDerivedNode(ceiling.id as AnyNodeId, { polygon: rect(0, 0, 6, 4) }) + const detached = useScene.getState().nodes[ceiling.id as AnyNodeId] as CeilingNode + expect(detached.boundary).toBeUndefined() + expect(detached.regions?.map((region) => region.id)).toEqual(['band', 'corner']) + expect(ceilingPaintRegions(detached, useScene.getState().nodes)).toEqual(detached.regions!) + } finally { + useScene.setState(saved, true) + } +}) diff --git a/packages/core/src/lib/ceiling-surface.ts b/packages/core/src/lib/ceiling-surface.ts new file mode 100644 index 0000000000..f291761edf --- /dev/null +++ b/packages/core/src/lib/ceiling-surface.ts @@ -0,0 +1,99 @@ +import type { AnyNode, CeilingNode } from '../schema' +import type { SurfacePaintRegion } from '../schema/nodes/surface-paint-region' +import { + area, + difference, + intersection, + type MultiPolygon, + type Ring, + union, +} from './polygon-boolean' + +/** + * Who paints which part of a ceiling's underside. A ceiling draws its own + * finish (`slots.surface`) except where a paint region covers it; regions later + * in the list win. An automatic ceiling is rebuilt from its room, so the room + * holds its regions (`zone.ceiling.regions`); a manual ceiling holds its own + * (`ceiling.regions`). Pure 2D in level XZ — the renderer triangulates the + * cells, the paint path reads the roles. + */ + +export const CEILING_SURFACE_ROLE = 'surface' +const MIN_CELL_AREA = 1e-6 + +export function ceilingRegionRole(regionId: string): string { + return `region:${regionId}` +} + +export function parseCeilingRegionRole(role: string): string | null { + return role.startsWith('region:') && role.length > 'region:'.length + ? role.slice('region:'.length) + : null +} + +/** Whether a ceiling's regions live on its room (an automatic ceiling) rather than on itself. */ +export function ceilingRegionsOwner( + ceiling: Pick, +): { kind: 'zone'; id: string } | { kind: 'ceiling'; id: string } { + return ceiling.boundary === 'auto' && ceiling.zoneId + ? { kind: 'zone', id: ceiling.zoneId } + : { kind: 'ceiling', id: ceiling.id } +} + +/** The paint regions a ceiling draws: its room's for an automatic ceiling, its own otherwise. */ +export function ceilingPaintRegions( + ceiling: Pick, + nodes: Readonly>, +): readonly SurfacePaintRegion[] { + const owner = ceilingRegionsOwner(ceiling) + if (owner.kind === 'ceiling') return ceiling.regions ?? [] + const zone = nodes[owner.id] + return zone?.type === 'zone' ? (zone.ceiling?.regions ?? []) : [] +} + +export type CeilingSurfaceCell = { + /** `surface` (the ceiling's own finish) or `region:`. */ + role: string + /** The region's finish; absent for the ceiling's own `surface`. */ + finish?: SurfacePaintRegion['finish'] + polygons: MultiPolygon +} + +/** + * Disjoint cells covering the ceiling (outline minus `holes`): each region + * takes what the later ones left, and `surface` is the rest. Regions that miss + * the ceiling produce no cell. + */ +export function computeCeilingSurfaceCells( + outline: readonly [number, number][], + holes: readonly (readonly [number, number][])[], + regions: readonly SurfacePaintRegion[], +): CeilingSurfaceCell[] { + const surface: MultiPolygon = [ + { + outer: outline.map(([x, z]) => [x, z]) as Ring, + holes: holes.map((hole) => [...hole] as Ring), + }, + ] + let remaining = holes.length ? union([surface]) : surface + const cells: CeilingSurfaceCell[] = [] + for (let index = regions.length - 1; index >= 0; index -= 1) { + const region = regions[index]! + if (region.polygon.length < 3 || !remaining.length) continue + const part = intersection(union([region.polygon as Ring]), remaining) + if (area(part) < MIN_CELL_AREA) continue + cells.push({ role: ceilingRegionRole(region.id), finish: region.finish, polygons: part }) + remaining = difference(remaining, part) + } + if (area(remaining) >= MIN_CELL_AREA) + cells.push({ role: CEILING_SURFACE_ROLE, polygons: remaining }) + return cells.reverse() +} + +/** What the partition of one ceiling depends on — its outline, holes and regions. */ +export function ceilingSurfaceSignature( + ceiling: Pick, + regions: readonly SurfacePaintRegion[], +): string { + return JSON.stringify([ceiling.polygon, ceiling.holes ?? [], regions]) +} diff --git a/packages/core/src/lib/floor-construction-lift.ts b/packages/core/src/lib/floor-construction-lift.ts new file mode 100644 index 0000000000..cacfeebaf8 --- /dev/null +++ b/packages/core/src/lib/floor-construction-lift.ts @@ -0,0 +1,65 @@ +import type { AnyNode, SlabNode } from '../schema' +import { sampleFenceCenterline } from '../systems/fence/fence-centerline' +import { getWallCurveFrameAt } from '../systems/wall/wall-curve' +import { footprintLift } from './floor-foundation-datum' +import { area, containsPoint, distanceToBoundary, intersection } from './polygon-boolean' + +const memo = new WeakMap>() + +// Construction wholly inside a footprint keeps its authored ground-relative +// height. Deriving this translation avoids feeding lifted decks or ground-pinned +// walls back into the automatic datum that defines the footprint's lift. +export function floorConstructionLift( + nodes: Readonly>, + node: AnyNode, +): number { + let cache = memo.get(nodes) + if (!cache) { + cache = new WeakMap() + memo.set(nodes, cache) + } + const hit = cache.get(node) + if (hit !== undefined) return hit + let lift = 0 + for (const base of Object.values(nodes)) { + if ( + base.type !== 'slab' || + base.plateRole !== 'base' || + base.floorHeight === undefined || + base.parentId !== node.parentId + ) + continue + const polygon = [{ outer: base.polygon, holes: [] }] + const inside = (point: [number, number]) => + containsPoint(polygon, point) || distanceToBoundary(polygon, point) < 1e-6 + let covered = false + if (node.type === 'slab') + covered = + area(intersection(polygon, node.polygon)) >= + area([{ outer: node.polygon, holes: [] }]) - 1e-6 + else if (node.type === 'wall') + covered = Array.from({ length: node.curveOffset ? 33 : 3 }, (_, i) => { + const p = getWallCurveFrameAt(node, i / (node.curveOffset ? 32 : 2)).point + return inside([p.x, p.y]) + }).every(Boolean) + else if (node.type === 'fence') + covered = sampleFenceCenterline(node, 64).every((point) => inside([point.x, point.y])) + else if ('position' in node && Array.isArray(node.position)) + covered = inside([node.position[0], node.position[2]]) + if (covered) { + lift = footprintLift(nodes, base) + break + } + } + cache.set(node, lift) + return lift +} + +export function liftedManualSlab( + nodes: Readonly>, + slab: SlabNode, +): SlabNode { + if (slab.plateRole || slab.autoFromWalls || slab.boundary === 'auto') return slab + const lift = floorConstructionLift(nodes, slab) + return lift ? { ...slab, elevation: slab.elevation + lift } : slab +} diff --git a/packages/core/src/lib/floor-footprint-creator.test.ts b/packages/core/src/lib/floor-footprint-creator.test.ts new file mode 100644 index 0000000000..b934cff7ed --- /dev/null +++ b/packages/core/src/lib/floor-footprint-creator.test.ts @@ -0,0 +1,186 @@ +import { expect, test } from 'bun:test' +import { duplicateZone } from '../commands/structure/duplicate-zone' +import { setZoneIntent, type ZoneIntentPatch } from '../commands/structure/set-zone-intent' +import { applyToScratch, structureChangeBatch } from '../commands/structure/shared' +import type { AnyNode, SlabNode, ZoneNode } from '../schema' +import { floorStepFixture } from '../systems/slab/__fixtures__/floor-step' +import { cloneLevelSubtree, cloneSceneGraph } from '../utils/clone-scene-graph' +import { reconcileStructureWithStableIds } from '../utils/structure-id' +import { floorFootprintCreatorId } from './floor-footprint-key' +import { floorFootprintName } from './floor-footprint-name' +import { keyedFloorPlateId } from './floor-plate-id' +import { roomFloorChoices } from './room-floor-choices' + +const reconcile = (nodes: Record) => + reconcileStructureWithStableIds({ nodes }).nodes +const room = (nodes: Record, id: string) => nodes[id] as ZoneNode +const base = (nodes: Record, zoneId: string) => + Object.values(nodes).find( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && !!node.zoneIds?.includes(zoneId), + )! +function intent(nodes: Record, zoneId: string, patch: ZoneIntentPatch) { + const plan = setZoneIntent(nodes, { zoneId, patch }) + expect(plan.conflicts ?? []).toEqual([]) + return reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))) +} + +function fixture(join = true) { + const f = floorStepFixture(true) + const nodes = Object.fromEntries(Object.entries(f.nodes).filter(([, n]) => n.type !== 'slab')) + const creatorId = f.zones[1]!.id + const largerId = f.zones[0]!.id + nodes[f.boundary.id] = { ...f.boundary, start: [6, 0], end: [6, 4] } + for (const [id, name, x0, x1] of [ + [creatorId, 'Lanai', 6, 8], + [largerId, 'Living room', 0, 6], + ] as const) + nodes[id] = { + ...room(nodes, id), + name, + floor: undefined, + polygon: [ + [x0, 0], + [x1, 0], + [x1, 4], + [x0, 4], + ], + } + let keyed = intent(reconcile(nodes), creatorId, { floor: { footprint: 'new' } }) + const key = room(keyed, creatorId).floor!.footprint! + if (join) keyed = intent(keyed, largerId, { floor: { footprint: key } }) + return { nodes: keyed, creatorId, largerId, key, levelId: f.level.id } +} + +test('a larger joining room keeps the creator name in plate and room floor choices', () => { + const { nodes, creatorId, largerId, key } = fixture() + expect(floorFootprintCreatorId(key)).toBe(creatorId) + expect(base(nodes, largerId).zoneIds).toContain(creatorId) + expect(floorFootprintName(nodes, base(nodes, largerId))).toBe('Lanai floor') + for (const id of [creatorId, largerId]) + expect(roomFloorChoices(nodes, id)[0]).toMatchObject({ + key, + name: 'Lanai floor', + current: true, + }) + const renamed = intent(nodes, creatorId, { name: 'Porch' }) + expect(floorFootprintName(renamed, base(renamed, largerId))).toBe('Porch floor') + const plate = { ...base(nodes, largerId), name: 'Garden foundation' } + expect(floorFootprintName({ ...nodes, [plate.id]: plate }, plate)).toBe('Garden foundation') + expect(roomFloorChoices({ ...nodes, [plate.id]: plate }, largerId)[0]!.name).toBe( + 'Garden foundation', + ) +}) + +test('the creator leaving falls back; creating another floor never rejoins the old key', () => { + const { nodes, creatorId, largerId, key } = fixture() + const left = intent(nodes, creatorId, { floor: { footprint: null } }) + expect(floorFootprintName(left, base(left, largerId))).toBe('Living room floor') + for (const before of [nodes, left]) { + const fresh = intent(before, creatorId, { floor: { footprint: 'new' } }) + expect(room(fresh, creatorId).floor!.footprint).not.toBe(key) + expect(floorFootprintCreatorId(room(fresh, creatorId).floor!.footprint!)).toBe(creatorId) + expect(room(fresh, largerId).floor!.footprint).toBe(key) + expect(floorFootprintName(fresh, base(fresh, largerId))).toBe('Living room floor') + expect(floorFootprintName(fresh, base(fresh, creatorId))).toBe('Lanai floor') + } +}) + +test.each([ + 'deleted', + 'other level', + 'no floor', + 'unnamed', +])('an unavailable creator (%s) uses the largest named room', (state) => { + const { nodes, creatorId, largerId } = fixture() + const creator = room(nodes, creatorId) + if (state === 'deleted') delete nodes[creatorId] + else + nodes[creatorId] = { + ...creator, + ...(state === 'other level' ? { parentId: 'level_elsewhere' } : {}), + ...(state === 'no floor' ? { hasFloor: false as const } : {}), + ...(state === 'unnamed' ? { name: '' } : {}), + } + expect(floorFootprintName(nodes, base(nodes, largerId))).toBe('Living room floor') +}) + +test('literal own has no creator and retains the largest-room fallback', () => { + const { nodes, creatorId, largerId } = fixture() + for (const id of [creatorId, largerId]) + nodes[id] = { ...room(nodes, id), floor: { footprint: 'own' } } + const loaded = reconcile(nodes) + expect(floorFootprintCreatorId('own')).toBeUndefined() + expect(floorFootprintName(loaded, base(loaded, largerId))).toBe('Living room floor') + expect(roomFloorChoices(loaded, creatorId)[0]!.name).toBe('Living room floor') +}) + +test('a disconnected room duplicate keeps the original creator rather than its own name', () => { + const { nodes, creatorId, key } = fixture(false) + let count = 0 + const plan = duplicateZone(nodes, { + zoneId: creatorId, + translate: [12, 0], + mintId: (kind) => `${kind}_creator_copy_${count++}`, + }) + expect(plan.conflicts ?? []).toEqual([]) + let copied = reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))) + copied = intent(copied, plan.zoneId, { name: 'Guest room' }) + expect(room(copied, plan.zoneId).floor!.footprint).toBe(key) + expect(base(copied, plan.zoneId).zoneIds).not.toContain(creatorId) + expect(floorFootprintName(copied, base(copied, plan.zoneId))).toBe('Lanai floor') + expect(roomFloorChoices(copied, plan.zoneId)[0]!.name).toBe('Lanai floor') +}) + +test.each([ + 'level', + 'scene', +])('%s clone remints keys with the cloned creator and stable plate IDs', (kind) => { + const { nodes, creatorId, largerId, key, levelId } = fixture() + const clonedNodes = + kind === 'level' + ? cloneLevelSubtree(nodes, levelId).clonedNodes + : Object.values(cloneSceneGraph({ nodes, rootNodeIds: [levelId] }).nodes) + let cloned = Object.fromEntries(clonedNodes.map((node) => [node.id, node])) + const creator = clonedNodes.find( + (node) => node.type === 'zone' && node.name === 'Lanai', + ) as ZoneNode + const larger = clonedNodes.find( + (node) => node.type === 'zone' && node.name === 'Living room', + ) as ZoneNode + expect(creator.id).not.toBe(creatorId) + expect(larger.id).not.toBe(largerId) + expect(creator.floor!.footprint).not.toBe(key) + expect(larger.floor!.footprint).toBe(creator.floor!.footprint) + expect(floorFootprintCreatorId(creator.floor!.footprint!)).toBe(creator.id) + const plateId = keyedFloorPlateId(creator.parentId!, creator.floor!.footprint!) + expect(cloned[plateId]?.type).toBe('slab') + cloned = reconcile(cloned) + expect(base(cloned, creator.id).id).toBe(plateId) + expect(floorFootprintName(cloned, base(cloned, larger.id))).toBe('Lanai floor') + cloned = intent(cloned, creator.id, { name: 'Cloned porch' }) + expect(floorFootprintName(cloned, base(cloned, larger.id))).toBe('Cloned porch floor') + expect(floorFootprintName(nodes, base(nodes, largerId))).toBe('Lanai floor') +}) + +test.each([ + 'own', + 'departed', + 'deleted', +])('cloning %s creator history preserves fallback naming', (state) => { + const { nodes, creatorId, largerId, levelId } = fixture() + if (state === 'own') { + for (const id of [creatorId, largerId]) + nodes[id] = { ...room(nodes, id), floor: { footprint: 'own' } } + } else if (state === 'departed') + nodes[creatorId] = { ...room(nodes, creatorId), floor: undefined } + else delete nodes[creatorId] + const clonedNodes = Object.values(cloneSceneGraph({ nodes, rootNodeIds: [levelId] }).nodes) + const cloned = Object.fromEntries(clonedNodes.map((node) => [node.id, node])) + const larger = clonedNodes.find( + (node) => node.type === 'zone' && node.name === 'Living room', + ) as ZoneNode + expect(floorFootprintName(cloned, base(cloned, larger.id))).toBe('Living room floor') + if (state !== 'departed') + expect(floorFootprintCreatorId(larger.floor!.footprint!)).toBeUndefined() +}) diff --git a/packages/core/src/lib/floor-footprint-key.ts b/packages/core/src/lib/floor-footprint-key.ts new file mode 100644 index 0000000000..7234cf7af9 --- /dev/null +++ b/packages/core/src/lib/floor-footprint-key.ts @@ -0,0 +1,11 @@ +import { generateId } from '../schema/base' + +export function mintFloorFootprintKey(creatorId?: string): string { + // A room can create another floor while other rooms still use its previous key. + const key = generateId('floor') + return creatorId ? `${key}:${creatorId}` : key +} + +export function floorFootprintCreatorId(key: string): string | undefined { + return /^floor_[^:]+:(zone_.+)$/.exec(key)?.[1] +} diff --git a/packages/core/src/lib/floor-footprint-name.test.ts b/packages/core/src/lib/floor-footprint-name.test.ts new file mode 100644 index 0000000000..a325bcd172 --- /dev/null +++ b/packages/core/src/lib/floor-footprint-name.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from 'bun:test' +import { type AnyNode, SlabNode, ZoneNode } from '../schema' +import { floorFootprintName } from './floor-footprint-name' + +const square = (x: number, size: number): [number, number][] => [ + [x, 0], + [x + size, 0], + [x + size, size], + [x, size], +] + +const plate = (id: string, polygon: [number, number][], zoneIds: string[] = [], name?: string) => + SlabNode.parse({ id, parentId: 'level_a', plateRole: 'base', polygon, zoneIds, name }) + +const room = (id: string, polygon: [number, number][], name: string) => + ZoneNode.parse({ id, spaceRole: 'room', polygon, name }) + +const scene = (...nodes: AnyNode[]) => Object.fromEntries(nodes.map((node) => [node.id, node])) + +test.each([ + 'Room 3 Slab', + 'Kitchen slab', + 'Floor plate 12', + 'Slab 4', + 'Floor', +])('generated legacy name %s uses the shared footprint name', (name) => { + const base = plate('slab_base', square(0, 4), [], name) + expect(floorFootprintName(scene(base), base)).toBe('Floor area') + const shed = room('zone_shed', base.polygon, 'Shed') + const withShed = { ...base, zoneIds: [shed.id] } + expect(floorFootprintName(scene(withShed, shed), withShed)).toBe('Shed floor') + expect(floorFootprintName(scene(base), { ...base, name: 'Garden foundation' })).toBe( + 'Garden foundation', + ) +}) + +test('footprints never read as levels: Shared floor, then the largest room, then Floor area', () => { + const kitchen = room('zone_kitchen', square(0, 6), 'Kitchen') + const hall = room('zone_hall', square(6, 2), 'Hall') + const nine = room('zone_nine', square(20, 3), 'Room 9') + const pantry = room('zone_pantry', square(23, 1), 'Pantry') + const house = plate('slab_house', square(0, 8), [kitchen.id, hall.id]) + const annex = plate('slab_annex', square(20, 4), [pantry.id, nine.id]) + const pad = plate('slab_pad', square(40, 2)) + const nodes = scene(kitchen, hall, nine, pantry, house, annex, pad) + expect(floorFootprintName(nodes, house)).toBe('Shared floor') + expect(floorFootprintName(nodes, annex)).toBe('Room 9 floor') + expect(floorFootprintName(nodes, pad)).toBe('Floor area') + const blank = room('zone_blank', square(20, 3), '') + const unnamed = { ...annex, zoneIds: [blank.id] } + expect(floorFootprintName({ ...nodes, [blank.id]: blank }, unnamed)).toBe('Floor area') +}) diff --git a/packages/core/src/lib/floor-footprint-name.ts b/packages/core/src/lib/floor-footprint-name.ts new file mode 100644 index 0000000000..8936d689a8 --- /dev/null +++ b/packages/core/src/lib/floor-footprint-name.ts @@ -0,0 +1,68 @@ +import type { AnyNode, SlabNode, ZoneNode } from '../schema' +import { floorFootprintCreatorId } from './floor-footprint-key' +import { area } from './polygon-boolean' + +const GENERATED_NAME = /^(floor plate|slab|floor)\b|slab$/i + +const polygonArea = (outer: SlabNode['polygon'], holes: SlabNode['holes'] = []) => + area([{ outer, holes }]) + +/** + * What a base-plate footprint is called everywhere (panel, "Sits on", scene + * graph, MCP messages). Never "Floor N": that reads as a level. A name the + * user gave the plate wins; the level's largest multi-room footprint is the + * "Shared floor". Keyed floors use their creator's current name while that + * room remains on the key, including disconnected pieces. Otherwise use the + * largest named room ("Kitchen floor"), or "Floor area" with no rooms. + */ +export function floorFootprintName( + nodes: Readonly>, + plate: SlabNode, +): string { + const own = plate.name?.trim() + if (own && !GENERATED_NAME.test(own)) return own + const rooms = (plate.zoneIds ?? []) + .flatMap((id) => { + const zone = nodes[id] + return zone?.type === 'zone' && zone.spaceRole === 'room' && zone.floor?.support !== 'open' + ? [zone as ZoneNode] + : [] + }) + .sort((a, b) => polygonArea(b.polygon) - polygonArea(a.polygon) || a.id.localeCompare(b.id)) + if ( + rooms.length > 1 && + !rooms.some((room) => room.floor?.footprint) && + isLargestFootprint(nodes, plate) + ) + return 'Shared floor' + const key = rooms.find((room) => room.floor?.footprint)?.floor?.footprint + const creatorId = key && floorFootprintCreatorId(key) + const creator = creatorId ? nodes[creatorId] : undefined + const creatorName = + creator?.type === 'zone' && + creator.spaceRole === 'room' && + creator.parentId === plate.parentId && + creator.floor?.footprint === key && + creator.floor?.support !== 'open' && + !creator.floor?.sourceSlabId && + creator.hasFloor !== false + ? creator.name?.trim() + : undefined + const named = creatorName || rooms.map((room) => room.name?.trim()).find(Boolean) + if (!named) return rooms.some((room) => room.floor?.footprint) ? 'Shared floor' : 'Floor area' + return /\bfloor$/i.test(named) ? named : `${named} floor` +} + +function isLargestFootprint(nodes: Readonly>, plate: SlabNode) { + const largest = Object.values(nodes) + .filter( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && node.parentId === plate.parentId, + ) + .sort( + (a, b) => + polygonArea(b.polygon, b.holes) - polygonArea(a.polygon, a.holes) || + a.id.localeCompare(b.id), + )[0] + return !largest || largest.id === plate.id +} diff --git a/packages/core/src/lib/floor-foundation-datum.ts b/packages/core/src/lib/floor-foundation-datum.ts new file mode 100644 index 0000000000..988a6c31df --- /dev/null +++ b/packages/core/src/lib/floor-foundation-datum.ts @@ -0,0 +1,331 @@ +import type { AnyNode, SlabNode } from '../schema' +import { DEFAULT_SLAB_ELEVATION, MIN_SLAB_THICKNESS } from '../schema/nodes/slab' +import { wallOverlapsSlabFootprint } from '../systems/slab/slab-support' +import { getWallArcData } from '../systems/wall/wall-curve' +import { wallOpeningBand } from './floor-opening-footprints' +import { area, containsPoint, difference, intersection, union } from './polygon-boolean' +import { automaticRoomBaseElevations } from './room-floor-feasibility' +import { isLevelAtSiteDatum } from './terrain-support-query' + +const heights = new WeakMap< + object, + Map +>() + +export function automaticFloorHeight( + nodes: Readonly>, + plate: SlabNode, +): number { + return plate.referenceFloorElevation ?? supportDerivedFloorHeight(nodes, plate) +} + +export function supportDerivedFloorHeight( + nodes: Readonly>, + plate: SlabNode, +): number { + const sources = Object.values(nodes).filter( + (node) => + node.type === 'site' || + node.type === 'building' || + node.type === 'level' || + (node.parentId === plate.parentId && + (node.type === 'wall' || + node.type === 'separator' || + node.type === 'zone' || + (node.type === 'slab' && !node.autoFromWalls && node.boundary !== 'auto'))), + ) + const zoneIds = JSON.stringify(plate.zoneIds) + let memo = heights.get(nodes) + if (!memo) { + memo = new Map() + heights.set(nodes, memo) + } + const hit = memo.get(plate.id) + if ( + hit && + hit.zoneIds === zoneIds && + hit.sources.length === sources.length && + sources.every((node, i) => node === hit.sources[i]) + ) + return hit.height + const placements = automaticRoomBaseElevations(nodes, plate.parentId!) + const values = (plate.zoneIds ?? []).map((id) => placements.get(id) ?? 0.05) + const height = values.length ? Math.max(...values) : 0.05 + memo.set(plate.id, { sources, zoneIds, height }) + return height +} + +export function floorFootprintSupportClass( + nodes: Readonly>, + plate: SlabNode, +): 'supported' | 'ground-bearing' { + const level = nodes[plate.parentId!] + if (level?.type !== 'level') return 'ground-bearing' + const buildingId = (levelId: string, parentId: string | null) => + (parentId && nodes[parentId]?.type === 'building' ? parentId : undefined) ?? + Object.values(nodes).find( + (node) => node.type === 'building' && node.children.includes(levelId as never), + )?.id ?? + null + const owner = buildingId(level.id, level.parentId) + const required = Math.max(1.5, area([{ outer: plate.polygon, holes: plate.holes ?? [] }]) * 0.5) + const overlaps: ReturnType = [] + for (const candidate of Object.values(nodes)) { + if (candidate.type !== 'slab' || candidate.plateRole !== 'base' || candidate.id === plate.id) + continue + const lower = nodes[candidate.parentId!] + if ( + lower?.type === 'level' && + buildingId(lower.id, lower.parentId) === owner && + lower.level < level.level && + candidate.zoneIds?.some((id) => nodes[id]?.type === 'zone' && nodes[id].spaceRole === 'room') + ) { + overlaps.push( + ...intersection( + { outer: candidate.polygon, holes: candidate.holes ?? [] }, + { outer: plate.polygon, holes: plate.holes ?? [] }, + ), + ) + } + } + return overlaps.length && area(union(overlaps)) >= required ? 'supported' : 'ground-bearing' +} + +export function floorPlateAtGroundContact( + nodes: Readonly>, + plate: SlabNode, +): boolean { + return ( + !!plate.parentId && + isLevelAtSiteDatum(nodes as Record, plate.parentId) && + floorFootprintSupportClass(nodes, plate) === 'ground-bearing' + ) +} + +export function floorPlateHoldsUnderside( + nodes: Readonly>, + plate: SlabNode, +): boolean { + return !floorPlateAtGroundContact(nodes, plate) +} + +/** + * A ground-bearing footprint's construction, bottom up: the grade, the + * foundation on it, the slab on the foundation, so the top is always + * grade + foundationHeight + thickness. The foundation height is derived from + * the stored top; a legacy plate whose slab reaches below grade reads 0. + */ +export function groundFloorConstruction( + nodes: Readonly>, + plate: SlabNode, +): { grade: number; top: number; thickness: number; foundationHeight: number } { + const grade = supportDerivedFloorHeight(nodes, plate) - DEFAULT_SLAB_ELEVATION + const top = plate.floorHeight ?? plate.elevation + const foundationHeight = Math.round((top - grade - plate.thickness) * 1e6) / 1e6 + return { grade, top, thickness: plate.thickness, foundationHeight: Math.max(0, foundationHeight) } +} + +export function floorPlateGestureMinimum( + nodes: Readonly>, + plate: SlabNode, +): number { + return upperFloorHeightControl(nodes, plate)?.minimumTop ?? Number.NEGATIVE_INFINITY +} + +export function footprintLift(nodes: Readonly>, plate: SlabNode): number { + return floorPlateHoldsUnderside(nodes, plate) + ? (plate.floorHeight ?? plate.elevation) - automaticFloorHeight(nodes, plate) + : plate.floorHeight !== undefined + ? plate.floorHeight - automaticFloorHeight(nodes, plate) + : 0 +} + +export function upperFloorHeightControl( + nodes: Readonly>, + plate: SlabNode, + targetTop: number = plate.floorHeight ?? plate.elevation, +): { + currentTop: number + minimumTop: number + write: { thickness: number } + advice?: 'thick-floor' +} | null { + if (!floorPlateHoldsUnderside(nodes, plate)) return null + const currentTop = plate.floorHeight ?? plate.elevation + const underside = currentTop - plate.thickness + const thickness = targetTop - underside + const restingUnderside = automaticFloorHeight(nodes, plate) - DEFAULT_SLAB_ELEVATION + return { + currentTop, + minimumTop: underside < restingUnderside - 0.001 ? currentTop : underside + MIN_SLAB_THICKNESS, + write: { thickness }, + ...(thickness > 0.4 ? { advice: 'thick-floor' as const } : {}), + } +} + +export function resolvedFootprintPlane( + nodes: Readonly>, + node: AnyNode, + storedHeight: number, +): number { + const lifts = Object.values(nodes).flatMap((plate) => + plate.type === 'slab' && + plate.plateRole === 'base' && + plate.parentId === node.parentId && + footprintSupportsNode(plate, node, nodes) + ? [footprintLift(nodes, plate)] + : [], + ) + return storedHeight + (lifts.length ? Math.max(...lifts) : 0) +} + +const overlaps = new WeakMap>>() + +export function footprintSupportsNode( + base: SlabNode, + node: AnyNode, + nodes: Readonly>, +): boolean { + let byBase = overlaps.get(nodes) + if (!byBase) { + byBase = new WeakMap() + overlaps.set(nodes, byBase) + } + let byNode = byBase.get(base) + if (!byNode) { + byNode = new WeakMap() + byBase.set(base, byNode) + } + const hit = byNode.get(node) + if (hit !== undefined) return hit + const result = computeFootprintSupport(base, node, nodes) + byNode.set(node, result) + return result +} + +const boundsMemo = new WeakMap() +const ceilingWallBands = new WeakMap>>() + +function ceilingSupportInterior( + base: SlabNode, + node: AnyNode, + nodes: Readonly>, +) { + if (node.type !== 'ceiling') return false + let levels = ceilingWallBands.get(nodes) + if (!levels) { + levels = new Map() + ceilingWallBands.set(nodes, levels) + } + let bands = levels.get(base.parentId!) + if (!bands) { + bands = union( + Object.values(nodes).flatMap((wall) => + wall.type === 'wall' && wall.parentId === base.parentId + ? [wallOpeningBand(wall, 0, 1)] + : [], + ), + ) + levels.set(base.parentId!, bands) + } + // Captured ceilings can cross a party wall by a wall-thickness sliver. + // Only overlap extending into the room carries that ceiling with the floor. + return ( + area( + difference( + intersection( + { outer: base.polygon, holes: base.holes }, + { outer: node.polygon, holes: node.holes }, + ), + bands, + ), + ) > 1e-6 + ) +} +function polygonBounds(polygon: [number, number][]) { + const cached = boundsMemo.get(polygon) + if (cached) return cached + const result = [ + Math.min(...polygon.map(([x]) => x)), + Math.min(...polygon.map(([, z]) => z)), + Math.max(...polygon.map(([x]) => x)), + Math.max(...polygon.map(([, z]) => z)), + ] + boundsMemo.set(polygon, result) + return result +} + +function polygonsOverlap(base: SlabNode, polygon: [number, number][]) { + const a = polygonBounds(base.polygon), + b = polygonBounds(polygon) + return ( + a[0]! < b[2]! && + b[0]! < a[2]! && + a[1]! < b[3]! && + b[1]! < a[3]! && + area(intersection({ outer: base.polygon, holes: base.holes ?? [] }, polygon)) > 1e-6 + ) +} + +function computeFootprintSupport( + base: SlabNode, + node: AnyNode, + nodes: Readonly>, +): boolean { + if (node.type === 'wall') { + const bounds = polygonBounds(base.polygon) + const margin = node.thickness ?? 0.15 + const arc = getWallArcData(node) + const xs = arc + ? [arc.center.x - arc.radius, arc.center.x + arc.radius] + : [node.start[0], node.end[0]] + const zs = arc + ? [arc.center.y - arc.radius, arc.center.y + arc.radius] + : [node.start[1], node.end[1]] + if ( + Math.max(...xs) + margin < bounds[0]! || + Math.min(...xs) - margin > bounds[2]! || + Math.max(...zs) + margin < bounds[1]! || + Math.min(...zs) - margin > bounds[3]! + ) + return false + return wallOverlapsSlabFootprint(node, base.polygon, base.holes) + } + if (node.type === 'ceiling' && node.parentId === base.parentId) + return polygonsOverlap(base, node.polygon) && ceilingSupportInterior(base, node, nodes) + if (node.type === 'slab' || node.type === 'zone' || node.type === 'ceiling') + return polygonsOverlap(base, node.polygon) + if (node.type === 'roof') { + const segments = node.children + .map((id) => nodes[id]) + .filter((segment) => segment?.type === 'roof-segment') + if (!segments.length) + return containsPoint( + [{ outer: base.polygon, holes: base.holes ?? [] }], + [node.position[0], node.position[2]], + ) + return segments.some((segment) => { + if (segment.type !== 'roof-segment') return false + const corners: [number, number][] = [ + [-1, -1], + [1, -1], + [1, 1], + [-1, 1], + ] + const polygon = corners.map(([sx, sz]): [number, number] => { + const x = (sx * segment.width) / 2, + z = (sz * segment.depth) / 2 + const rx = + segment.position[0] + x * Math.cos(segment.rotation) + z * Math.sin(segment.rotation) + const rz = + segment.position[2] - x * Math.sin(segment.rotation) + z * Math.cos(segment.rotation) + return [ + node.position[0] + rx * Math.cos(node.rotation) + rz * Math.sin(node.rotation), + node.position[2] - rx * Math.sin(node.rotation) + rz * Math.cos(node.rotation), + ] + }) + return polygonsOverlap(base, polygon) + }) + } + return false +} diff --git a/packages/core/src/lib/floor-foundation-stack.ts b/packages/core/src/lib/floor-foundation-stack.ts new file mode 100644 index 0000000000..fa1f162eeb --- /dev/null +++ b/packages/core/src/lib/floor-foundation-stack.ts @@ -0,0 +1,269 @@ +import type { AnyNode, AnyNodeId, SlabNode } from '../schema' +import { getAuthoredLevelElevations } from '../services/storey' +import { floorFootprintName } from './floor-footprint-name' +import { + automaticFloorHeight, + floorPlateHoldsUnderside, + footprintLift, + footprintSupportsNode, +} from './floor-foundation-datum' +import { area } from './polygon-boolean' +import { type RoomFloorConflict, roundFloorElevation } from './room-floor-feasibility' + +type Update = { id: AnyNodeId; data: Partial } + +export function isMeaningfulFloorFootprint( + nodes: Readonly>, + plate: SlabNode, +): boolean { + return ( + area([{ outer: plate.polygon, holes: plate.holes }]) >= 1.5 && + !!plate.zoneIds?.some((id) => nodes[id]?.type === 'zone' && nodes[id].spaceRole === 'room') + ) +} + +const supportMemo = new WeakMap }>() + +export function upperStoreyFootprints( + nodes: Readonly>, +): ReadonlyMap { + const values = Object.values(nodes) + const cached = supportMemo.get(nodes) + if ( + cached && + cached.sources.length === values.length && + values.every((node, index) => node === cached.sources[index]) + ) + return cached.result + const elevations = getAuthoredLevelElevations(nodes) + const bases = values.filter( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && isMeaningfulFloorFootprint(nodes, node), + ) + const basesByLevel = new Map() + for (const base of bases) + if (base.parentId) { + const group = basesByLevel.get(base.parentId) ?? [] + group.push(base) + basesByLevel.set(base.parentId, group) + } + const contentsByLevel = new Map() + for (const node of values) + if ( + node.parentId && + (node.type === 'slab' || + node.type === 'zone' || + node.type === 'ceiling' || + node.type === 'wall') + ) { + const group = contentsByLevel.get(node.parentId) ?? [] + group.push(node) + contentsByLevel.set(node.parentId, group) + } + const result = new Map() + for (const [id, upper] of elevations) { + const lowerLevels = [...elevations] + .filter(([, entry]) => entry.buildingId === upper.buildingId && entry.ordinal < upper.ordinal) + .sort((a, b) => b[1].ordinal - a[1].ordinal) + if (!lowerLevels.length) continue + const contents = [...(contentsByLevel.get(id) ?? [])].sort( + (a, b) => Number(a.type === 'wall') - Number(b.type === 'wall'), + ) + const owners = new Map() + for (const node of contents) + for (const [lowerId] of lowerLevels) { + const covering = (basesByLevel.get(lowerId) ?? []).filter((base) => + footprintSupportsNode(base, node, nodes), + ) + if (!covering.length) continue + for (const base of covering) owners.set(base.id, base) + break + } + result.set(id, [...owners.values()]) + } + supportMemo.set(nodes, { sources: values, result }) + return result +} + +export function levelConstructionDisplacements( + nodes: Readonly>, + supports: ReadonlyMap = upperStoreyFootprints(nodes), +): Map { + const elevations = getAuthoredLevelElevations(nodes) + const result = new Map() + for (const [id] of [...elevations].sort((a, b) => a[1].ordinal - b[1].ordinal)) { + const lifts = (supports.get(id) ?? []).map( + (base) => + (result.get(base.parentId!) ?? 0) + + footprintLift(nodes, (nodes[base.id]?.type === 'slab' ? nodes[base.id] : base) as SlabNode), + ) + result.set(id, lifts.length ? Math.max(...lifts) : 0) + } + return result +} + +export function changedLevelConstructionDisplacements( + before: Readonly>, + after: Readonly>, +): Set { + const changed = new Set() + const fields = [ + 'floorHeight', + 'referenceFloorElevation', + 'elevation', + 'polygon', + 'holes', + 'zoneIds', + 'parentId', + 'plateRole', + ] as const + const ids = new Set([...Object.keys(before), ...Object.keys(after)]) + let geometryChanged = false + let anyChanged = false + for (const id of ids) { + const old = before[id], + next = after[id] + if (old === next || (old?.type !== 'slab' && next?.type !== 'slab')) continue + if (old?.type !== 'slab' || next?.type !== 'slab') { + geometryChanged = true + anyChanged = true + continue + } + const different = fields.filter( + (field) => JSON.stringify(old[field]) !== JSON.stringify(next[field]), + ) + if (different.some((field) => field !== 'floorHeight' && field !== 'elevation')) + geometryChanged = true + if (different.length) anyChanged = true + } + if (!anyChanged) return changed + const supports = geometryChanged ? undefined : upperStoreyFootprints(before) + const old = levelConstructionDisplacements(before, supports) + const next = levelConstructionDisplacements(after, supports) + for (const id of new Set([...old.keys(), ...next.keys()])) + if (Math.abs((old.get(id) ?? 0) - (next.get(id) ?? 0)) > 1e-6) changed.add(id) + return changed +} + +export function footprintStackChanges( + nodes: Readonly>, + changes: readonly Update[], +): { updates: Update[]; conflicts: RoomFloorConflict[] } { + const deltas = new Map() + for (const { id, data } of changes) { + const plate = nodes[id] + if ( + plate?.type !== 'slab' || + plate.plateRole !== 'base' || + (!Object.hasOwn(data, 'floorHeight') && !Object.hasOwn(data, 'elevation')) + ) + continue + const delta = roundFloorElevation( + ((data as Partial).elevation ?? + (data as Partial).floorHeight ?? + automaticFloorHeight(nodes, plate)) - (plate.floorHeight ?? plate.elevation), + ) + if (delta) deltas.set(id, delta) + } + if (!deltas.size) return { updates: [], conflicts: [] } + const values = Object.values(nodes) + const bases = values.filter( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && isMeaningfulFloorFootprint(nodes, node), + ) + const supports = upperStoreyFootprints(nodes) + const conflicts: RoomFloorConflict[] = [] + const updates: Update[] = [] + const displacement = new Map() + const elevations = getAuthoredLevelElevations(nodes) + const oldDisplacement = levelConstructionDisplacements(nodes) + for (const [id, owners] of [...elevations.keys()] + .map((levelId): [string, SlabNode[]] => [levelId, supports.get(levelId) ?? []]) + .sort( + (a, b) => + (elevations.get(a[0])?.ordinal ?? Infinity) - (elevations.get(b[0])?.ordinal ?? Infinity), + )) { + if (nodes[id]?.type !== 'level') continue + const shifts = owners.map( + (base) => + (displacement.get(base.parentId!) ?? 0) + + footprintLift(nodes, base) + + (deltas.get(base.id) ?? 0), + ) + displacement.set(id, shifts.length ? Math.max(...shifts) : 0) + const moved = owners.find((base) => deltas.has(base.id)) + const reference = shifts[moved ? owners.indexOf(moved) : 0]! + const other = owners.find((base, index) => Math.abs(shifts[index]! - reference) > 1e-6) + const affected = owners.some( + (base) => + deltas.has(base.id) || + Math.abs( + (displacement.get(base.parentId!) ?? 0) - (oldDisplacement.get(base.parentId!) ?? 0), + ) > 1e-6, + ) + if (other && affected) { + const subject = 'upper floor' + conflicts.push({ + code: 'floor-foundation-shared-storey', + severity: 'error', + nodeIds: [id, ...owners.map((base) => base.id)], + message: `The ${subject} also sits over ${floorFootprintName(nodes, other)}; raise both or neither.`, + }) + continue + } + if (!moved) continue + const delta = deltas.get(moved.id)! + if (nodes[id]?.type !== 'level') continue + const contents = values + .filter((node) => node.parentId === id && node.type !== 'roof') + .sort((a, b) => Number(a.type === 'wall') - Number(b.type === 'wall')) + for (const plate of values) { + if ( + plate.type !== 'slab' || + plate.plateRole !== 'base' || + plate.parentId !== moved.parentId || + isMeaningfulFloorFootprint(nodes, plate) || + changes.some((change) => change.id === plate.id) || + updates.some((change) => change.id === plate.id) + ) + continue + if (contents.some((node) => footprintSupportsNode(plate, node, nodes))) + updates.push({ + id: plate.id, + data: floorPlateHoldsUnderside(nodes, plate) + ? { + floorHeight: undefined, + elevation: roundFloorElevation((plate.floorHeight ?? plate.elevation) + delta), + thickness: roundFloorElevation(plate.thickness + delta), + } + : { floorHeight: roundFloorElevation((plate.floorHeight ?? plate.elevation) + delta) }, + }) + } + } + const affected = (base: SlabNode) => + deltas.has(base.id) || + Math.abs((displacement.get(base.parentId!) ?? 0) - (oldDisplacement.get(base.parentId!) ?? 0)) > + 1e-6 + const shifted = (base: SlabNode) => + (displacement.get(base.parentId!) ?? 0) + + footprintLift(nodes, base) + + (deltas.get(base.id) ?? 0) + for (const node of values) { + if (node.type !== 'roof' && node.type !== 'ceiling') continue + const candidates = bases.filter((base) => base.parentId === node.parentId) + if (!candidates.some((base) => affected(base) && footprintSupportsNode(base, node, nodes))) + continue + const owners = candidates.filter((base) => footprintSupportsNode(base, node, nodes)) + if (owners.length < 2) continue + const reference = shifted(owners.find((base) => deltas.has(base.id)) ?? owners[0]!) + const other = owners.find((base) => Math.abs(shifted(base) - reference) > 1e-6) + if (other) + conflicts.push({ + code: 'floor-foundation-shared-storey', + severity: 'error', + nodeIds: [node.id, ...owners.map((base) => base.id)], + message: `The ${node.type} also sits over ${floorFootprintName(nodes, other)}; raise both or neither.`, + }) + } + return { updates, conflicts } +} diff --git a/packages/core/src/lib/floor-intent-changes.ts b/packages/core/src/lib/floor-intent-changes.ts new file mode 100644 index 0000000000..3801fc35a2 --- /dev/null +++ b/packages/core/src/lib/floor-intent-changes.ts @@ -0,0 +1,531 @@ +import { boundaries, roomFace } from '../commands/structure/shared' +import type { AnyNode, AnyNodeId, CeilingNode, RoofNode, SlabNode, ZoneNode } from '../schema' +import { DEFAULT_SLAB_ELEVATION } from '../schema/nodes/slab' +import { + findLevelBelowId, + getLevelElevations, + getWallCoveringSlabUnderside, + getWallPlaneTop, +} from '../services/storey' +import { resolveWallTop } from '../systems/wall/wall-top' +import { + automaticFloorHeight, + floorPlateAtGroundContact, + floorPlateHoldsUnderside, + footprintSupportsNode, + supportDerivedFloorHeight, +} from './floor-foundation-datum' +import { + changedLevelConstructionDisplacements, + footprintStackChanges, +} from './floor-foundation-stack' +import { floorRoomFaces } from './floor-room-faces' +import { getOpeningFloorTarget, wallSupportForNodes } from './opening-floor-datum' +import { area, intersection } from './polygon-boolean' +import { + checkRoomFloor, + getRoomBaseElevation, + type RoomFloorConflict, + roundFloorElevation, +} from './room-floor-feasibility' + +type Update = { id: AnyNodeId; data: Partial } + +export function expandFloorIntentChanges( + nodes: Readonly>, + updates: readonly Update[], +): Update[] { + const intent = updates.map((update) => { + const plate = nodes[update.id] + const patch = update.data as Partial + if (plate?.type !== 'slab' || plate.plateRole !== 'base') return update + // A reference rebase can need an explicit current top even when that top + // equals the old resting height; normalizing it away would move the floor. + if (Object.hasOwn(patch, 'referenceFloorElevation')) return update + const supported = floorPlateHoldsUnderside(nodes, plate) + if (supported) { + if ( + !Object.hasOwn(patch, 'floorHeight') && + patch.thickness === undefined && + patch.elevation === undefined + ) + return update + const currentTop = plate.floorHeight ?? plate.elevation + const nextTop = + patch.floorHeight !== undefined + ? (patch.floorHeight ?? automaticFloorHeight(nodes, plate)) + : patch.elevation !== undefined + ? patch.elevation + : currentTop + (patch.thickness ?? plate.thickness) - plate.thickness + return { + ...update, + data: { + ...update.data, + floorHeight: undefined, + thickness: roundFloorElevation(plate.thickness + nextTop - currentTop), + elevation: roundFloorElevation(nextTop), + } as Partial, + } + } + if (Object.hasOwn(patch, 'floorHeight')) { + const resting = supportDerivedFloorHeight(nodes, plate) + const atRest = patch.floorHeight == null || Math.abs(patch.floorHeight - resting) <= 0.001 + const keepExplicitRest = + plate.referenceFloorElevation !== undefined && + Math.abs(plate.referenceFloorElevation - resting) > 0.001 + // The store guard can expand a normalized plan again. Its cleared height + // must not erase the foundation already resolved for a raised top. The + // slab sits on the foundation, so only a top above grade + thickness has one. + const foundationHeight = + (patch.floorHeight ?? resting) - + (resting - DEFAULT_SLAB_ELEVATION) - + (patch.thickness ?? plate.thickness) + const foundation = + foundationHeight <= 0.0005 + ? { ...plate.foundation, ...patch.foundation, type: 'none' as const } + : (patch.foundation ?? + (patch.floorHeight == null + ? { ...plate.foundation, type: 'none' as const } + : plate.foundation?.type === 'solid' + ? plate.foundation + : { + type: 'solid' as const, + material: plate.foundation?.material ?? 'library:preset-midgrey', + })) + return { + ...update, + data: { + ...update.data, + floorHeight: atRest && !keepExplicitRest ? undefined : (patch.floorHeight ?? resting), + ...(foundation ? { foundation } : {}), + } as Partial, + } + } + return update + }) + const stack = footprintStackChanges(nodes, intent) + const constructionUpdates = [...intent, ...stack.updates] + const result = [...constructionUpdates] + for (const update of constructionUpdates) { + const plate = nodes[update.id] + if ( + plate?.type !== 'slab' || + plate.plateRole !== 'base' || + (!Object.hasOwn(update.data, 'floorHeight') && !Object.hasOwn(update.data, 'elevation')) + ) + continue + const patch = update.data as Partial + const delta = + (patch.elevation ?? patch.floorHeight ?? automaticFloorHeight(nodes, plate)) - + (plate.floorHeight ?? plate.elevation) + if (!delta) continue + for (const zone of Object.values(nodes)) { + if ( + zone.type !== 'zone' || + !( + plate.zoneIds?.includes(zone.id) || + (zone.parentId === plate.parentId && + zone.floor?.support === 'open' && + area(intersection(plate.polygon, zone.polygon)) > 1e-6) + ) || + zone.floor?.elevation === undefined + ) + continue + const index = result.findIndex((u) => u.id === zone.id) + const data = index >= 0 ? (result[index]!.data as Partial) : {} + if (data.floor && Object.hasOwn(data.floor, 'elevation')) continue + const floor = data.floor ?? zone.floor + if (floor?.elevation === undefined) continue + const translated = { + id: zone.id, + data: { + ...data, + floor: { ...floor, elevation: roundFloorElevation(floor.elevation + delta) }, + }, + } + if (index >= 0) result[index] = translated + else result.push(translated) + } + for (const node of Object.values(nodes)) { + if (node.parentId !== plate.parentId) continue + let data: Partial | undefined + if ( + node.type === 'roof' && + (!node.support || node.support.kind === 'level') && + footprintSupportsNode(plate, node, nodes) + ) + data = { + position: [ + node.position[0], + roundFloorElevation(node.position[1] + delta), + node.position[2], + ], + } + if ( + node.type === 'ceiling' && + node.height !== undefined && + footprintSupportsNode(plate, node, nodes) + ) + data = { height: roundFloorElevation(node.height + delta) } + if (!data) continue + const existing = result.find((entry) => entry.id === node.id) + if (!existing) result.push({ id: node.id, data }) + else if (!Object.keys(data).some((key) => Object.hasOwn(existing.data, key))) + existing.data = { ...existing.data, ...data } as Partial + } + } + return result +} + +export function floorIntentConflicts( + nodes: Readonly>, + updates: readonly Update[], + created: readonly AnyNode[] = [], + deleted: readonly string[] = [], +) { + const stack = footprintStackChanges(nodes, updates) + if (stack.conflicts.length) return stack.conflicts + const groundOnly: RoomFloorConflict[] = updates.flatMap(({ id, data }) => { + const plate = nodes[id] + if (plate?.type !== 'slab' || plate.plateRole !== 'base') return [] + const patch = data as Partial + if (floorPlateAtGroundContact(nodes, plate)) return [] + if (patch.foundation?.type === 'solid') + return [ + { + code: 'floor-foundation-level', + severity: 'error', + nodeIds: [id], + message: 'Only a plate at ground contact can have a solid foundation.', + }, + ] + return [] + }) + if (groundOnly.length) return groundOnly + const draft = { ...nodes } + for (const id of deleted) delete draft[id] + for (const node of created) { + draft[node.id] = node + } + for (const { id, data } of updates) + if (draft[id]) draft[id] = { ...draft[id], ...data } as AnyNode + for (const node of created) { + const parent = node.parentId && draft[node.parentId] + if (parent && 'children' in parent) + draft[parent.id] = { + ...parent, + children: [...new Set([...parent.children, node.id])], + } as AnyNode + } + for (const { id, data } of updates) { + const plate = draft[id] + if ( + plate?.type === 'slab' && + plate.plateRole === 'base' && + Object.hasOwn(data, 'floorHeight') && + !Object.hasOwn(data, 'elevation') + ) + draft[id] = { ...plate, elevation: plate.floorHeight ?? automaticFloorHeight(nodes, plate) } + } + const changedDisplacements = changedLevelConstructionDisplacements(nodes, draft) + const baseHeightChanges = updates.filter( + ({ id, data }) => + nodes[id]?.type === 'slab' && + nodes[id].plateRole === 'base' && + (Object.hasOwn(data, 'floorHeight') || Object.hasOwn(data, 'elevation')), + ) + if ( + !created.length && + !changedDisplacements.size && + baseHeightChanges.length && + baseHeightChanges.every( + ({ id, data }) => + floorPlateAtGroundContact(nodes, nodes[id] as SlabNode) && + Object.keys(data).every( + (key) => + ['floorHeight', 'foundation', 'slots', 'name'].includes(key) || + data[key as keyof typeof data] === nodes[id]![key as keyof AnyNode], + ), + ) + ) { + const translated = new Map( + expandFloorIntentChanges(nodes, baseHeightChanges).map((update) => [update.id, update.data]), + ) + if ( + updates.every(({ id, data }) => + Object.entries(data).every( + ([key, value]) => + ['slots', 'foundation', 'name'].includes(key) || + JSON.stringify(value) === JSON.stringify(translated.get(id)?.[key as keyof AnyNode]), + ), + ) + ) + return [] + } + const verticalBases = updates.flatMap(({ id, data }) => { + const plate = nodes[id] + return plate?.type === 'slab' && + plate.plateRole === 'base' && + ['floorHeight', 'thickness', 'polygon', 'holes'].some((key) => Object.hasOwn(data, key)) + ? [{ plate, data: data as Partial }] + : [] + }) + const baseDeltas = verticalBases.map(({ plate, data }) => + Object.hasOwn(data, 'elevation') + ? roundFloorElevation((data as Partial).elevation! - plate.elevation) + : Object.hasOwn(data, 'floorHeight') + ? roundFloorElevation( + (data.floorHeight ?? automaticFloorHeight(nodes, plate)) - + (plate.floorHeight ?? plate.elevation), + ) + : 0, + ) + const matchesBaseDelta = (delta: number) => + baseDeltas.some((baseDelta) => Math.abs(baseDelta - delta) <= 1e-6) + const baseOnly = + !created.length && + verticalBases.length > 0 && + updates.every(({ id, data }) => { + const node = nodes[id] + if (node?.type === 'slab' && node.plateRole === 'base') + return Object.keys(data).every((key) => + [ + 'floorHeight', + 'elevation', + 'thickness', + 'polygon', + 'holes', + 'foundation', + 'slots', + 'name', + ].includes(key), + ) + if (node?.type === 'zone') { + const floor = (data as Partial).floor + return ( + Object.keys(data).every((key) => key === 'floor') && + floor?.elevation !== undefined && + matchesBaseDelta(floor.elevation - (node.floor?.elevation ?? 0)) + ) + } + if (node?.type === 'ceiling') + return ( + Object.keys(data).every((key) => key === 'height') && + typeof (data as Partial).height === 'number' && + matchesBaseDelta((data as Partial).height! - (node.height ?? 0)) + ) + if (node?.type === 'roof') { + const position = (data as Partial).position + return ( + Object.keys(data).every((key) => key === 'position') && + Array.isArray(position) && + matchesBaseDelta(position[1] - node.position[1]) + ) + } + return false + }) + const loweringPlates = verticalBases.filter(({ plate, data }) => { + if (Object.hasOwn(data, 'polygon') || Object.hasOwn(data, 'holes')) return true + const top = Object.hasOwn(data, 'elevation') + ? data.elevation! + : Object.hasOwn(data, 'floorHeight') + ? (data.floorHeight ?? automaticFloorHeight(nodes, plate)) + : (plate.floorHeight ?? plate.elevation) + return ( + top - (data.thickness ?? plate.thickness) < + (plate.floorHeight ?? plate.elevation) - plate.thickness - 1e-6 + ) + }) + if (baseOnly && !loweringPlates.length) return [] + const levels = new Set() + const relevant = [ + 'floor', + 'floorHeight', + 'thickness', + 'height', + 'verticalAnchor', + 'width', + 'position', + 'start', + 'end', + 'curveOffset', + 'justification', + 'supportSlabId', + 'supportOffset', + 'parentId', + 'children', + 'hasFloor', + 'elevation', + 'baseElevation', + 'polygon', + 'holes', + 'level', + ] + if (!baseOnly) { + for (const { id, data } of [ + ...updates, + ...created.map((node) => ({ id: node.id, data: node })), + ]) { + if (!relevant.some((key) => Object.hasOwn(data, key))) continue + for (const graph of [nodes, draft]) { + let node = graph[id] + const visited = new Set() + while (node && node.type !== 'level' && !visited.has(node.id)) { + visited.add(node.id) + node = node.parentId ? graph[node.parentId] : undefined! + } + if (node?.type === 'level') levels.add(node.id) + } + } + } + if (!baseOnly) for (const id of changedDisplacements) levels.add(id) + if ( + updates.some(({ id, data }) => { + const plate = nodes[id] ?? draft[id] + return ( + plate?.type === 'slab' && + plate.plateRole === 'base' && + ['thickness', 'floorHeight', 'polygon', 'holes'].some((field) => Object.hasOwn(data, field)) + ) + }) + ) { + for (const graph of [nodes, draft]) { + const elevations = getLevelElevations(graph) + for (const { id, data } of updates) { + const plate = graph[id] + if ( + plate?.type !== 'slab' || + plate.plateRole !== 'base' || + !['thickness', 'floorHeight', 'polygon', 'holes'].some((field) => + Object.hasOwn(data, field), + ) + ) + continue + const levelId = plate.parentId + if (!levelId) continue + const below = findLevelBelowId(levelId, elevations) + if (below) levels.add(below) + } + } + } + if (baseOnly && !levels.size) return [] + const edited = new Set([...updates.map((u) => u.id), ...created.map((n) => n.id)]) + const zoneOnly = [...edited].every((id) => draft[id]?.type === 'zone') + const affectedWalls = new Set() + const spans = (graph: Readonly>, zone: ZoneNode) => + roomFace(graph, zone, floorRoomFaces(boundaries(graph, zone.parentId!)))?.spans ?? [] + if (zoneOnly) + for (const id of edited) + for (const graph of [nodes, draft]) { + const zone = graph[id] + if (zone?.type === 'zone') { + if (zone.boundaryWallIds?.length) + for (const id of zone.boundaryWallIds) affectedWalls.add(id) + else for (const span of spans(graph, zone)) affectedWalls.add(span.boundaryId) + } + } + const ids = Object.values(draft).flatMap((node) => + node.type === 'zone' && + levels.has(node.parentId!) && + (!baseOnly || verticalBases.some(({ plate }) => footprintSupportsNode(plate, node, draft))) && + (!zoneOnly || + edited.has(node.id) || + (node.boundaryWallIds?.some((id) => affectedWalls.has(id)) ?? + spans(draft, node).some((span) => affectedWalls.has(span.boundaryId)))) + ? [node.id] + : [], + ) + + const conflicts = [...ids].flatMap((id) => { + const zone = draft[id] as ZoneNode + if (zone.floor?.support === 'open' || zone.spaceRole !== 'room' || zone.hasFloor === false) + return [] + const elevation = zone.floor?.elevation ?? getRoomBaseElevation(draft, zone.id) + const check = checkRoomFloor(draft, id, elevation) + const previous = nodes[id] + const oldElevation = + previous?.type === 'zone' + ? (previous.floor?.elevation ?? getRoomBaseElevation(nodes, id)) + : elevation + const before = previous?.type === 'zone' ? checkRoomFloor(nodes, id, oldElevation) : undefined + return check.conflicts.filter( + (c) => + c.severity === 'error' && + c.code !== 'floor-opening-fit' && + !before?.conflicts.some( + (old) => + old.code === c.code && + JSON.stringify(old.nodeIds) === JSON.stringify(c.nodeIds) && + (c.excess ?? Infinity) <= (old.excess ?? 0) + 1e-6, + ), + ) + }) + for (const node of Object.values(draft)) { + if (node.type !== 'door' && node.type !== 'window') continue + const wall = draft[node.parentId!] + if ( + wall?.type !== 'wall' || + !levels.has(wall.parentId!) || + (baseOnly && !verticalBases.some(({ plate }) => footprintSupportsNode(plate, wall, draft))) || + (zoneOnly && !affectedWalls.has(wall.id)) + ) + continue + const excess = (graph: Readonly>, opening: typeof node) => { + const host = graph[opening.parentId!] + if (host?.type !== 'wall') return -Infinity + return ( + getOpeningFloorTarget(host, opening, graph) + + opening.position[1] + + opening.height / 2 - + resolveWallTop( + host, + getWallPlaneTop(host, host.parentId!, graph), + wallSupportForNodes(host, graph).elevation, + ) + ) + } + const after = excess(draft, node) + const previous = nodes[node.id] + const before = + previous?.type === 'door' || previous?.type === 'window' ? excess(nodes, previous) : -Infinity + if ( + after > 1e-6 && + after > before + 1e-6 && + !conflicts.some((c) => c.code === 'floor-opening-fit' && c.nodeIds.includes(node.id)) + ) + conflicts.push({ + code: 'floor-opening-fit', + severity: 'error', + nodeIds: [node.id], + excess: after, + message: `The ${node.type} does not fit: it exceeds its wall top by ${roundFloorElevation(after)} m.`, + }) + } + for (const node of Object.values(draft)) { + if ( + node.type !== 'wall' || + node.height === undefined || + !levels.has(node.parentId!) || + !loweringPlates.some(({ plate }) => footprintSupportsNode(plate, node, draft)) + ) + continue + const excess = (graph: Readonly>, wall: typeof node) => + resolveWallTop( + wall, + getWallPlaneTop(wall, wall.parentId!, graph), + wallSupportForNodes(wall, graph).elevation, + ) - (getWallCoveringSlabUnderside(wall, wall.parentId!, graph) ?? Infinity) + const after = excess(draft, node) + const previous = nodes[node.id] + const before = previous?.type === 'wall' ? excess(nodes, previous) : -Infinity + if (after > 1e-6 && after > before + 1e-6) + conflicts.push({ + code: 'floor-wall-fit', + severity: 'error', + nodeIds: [node.id], + excess: after, + message: `The wall top exceeds the floor above by ${roundFloorElevation(after)} m.`, + }) + } + return conflicts +} diff --git a/packages/core/src/lib/floor-levels.test.ts b/packages/core/src/lib/floor-levels.test.ts new file mode 100644 index 0000000000..0525bb64be --- /dev/null +++ b/packages/core/src/lib/floor-levels.test.ts @@ -0,0 +1,408 @@ +import { expect, test } from 'bun:test' +import { setZoneIntent } from '../commands/structure/set-zone-intent' +import { + type AnyNode, + BuildingNode, + DoorNode, + LevelNode, + type SlabNode, + type WallNode, + type ZoneNode, +} from '../schema' +import { + assertDerivedNodeWrites, + derivedFieldViolations, + filterDerivedNodeWrites, +} from '../store/derived-node-guard' +import { floorStepFixture } from '../systems/slab/__fixtures__/floor-step' +import { resolveWallTop } from '../systems/wall/wall-top' +import { migrateFloorPlates } from '../utils/floor-plate-migration' +import { reconcileStructureOnLoad } from '../utils/reconcile-structure-on-load' +import { migrateRoomZones } from '../utils/room-zone-migration' +import { reconcileStructureWithStableIds } from '../utils/structure-id' +import { expandFloorIntentChanges } from './floor-intent-changes' +import { getOpeningFloorDatum, getOpeningWallCut, wallSupportForNodes } from './opening-floor-datum' +import { computePlateSurfacePartition, plateLevelContext } from './plate-surface' +import { area, containsPoint, intersection } from './polygon-boolean' +import { + checkRoomFloor, + clampRoomFloorHandle, + getRoomBaseElevation, + getRoomRelativeFloorElevation, + roomFloorElevationFromRelative, +} from './room-floor-feasibility' + +function scene(high = 0.55, low = 0.05, door = true) { + const fixture = floorStepFixture() + const nodes = Object.fromEntries( + Object.entries(fixture.nodes).filter(([, n]) => n.type !== 'slab'), + ) + nodes[fixture.level.id] = { + ...fixture.level, + height: 3, + children: fixture.level.children.filter((id) => nodes[id]), + } + for (const [i, zone] of fixture.zones.entries()) + nodes[zone.id] = { + ...zone, + floor: { elevation: i ? low : high, finish: `library:finish-${i}` }, + } + if (door) { + nodes[fixture.door.id] = fixture.door + nodes[fixture.divider.id] = { ...fixture.divider, children: [fixture.door.id] } + } + return { ...fixture, nodes: { ...reconcileStructureWithStableIds({ nodes }).nodes } } +} +const plates = (nodes: Record) => + Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab') + +test('D1/D2/D3/D5: raising floors retains the base, complete wall bodies and fixed tops', () => { + const s = scene() + const base = plates(s.nodes).find((p) => p.plateRole === 'base')! + const platform = plates(s.nodes).find((p) => p.plateRole === 'platform')! + expect(base.elevation).toBe(0.05) + expect(platform.thickness).toBeCloseTo(0.5) + expect(containsPoint([{ outer: base.polygon, holes: base.holes }], [2, 2])).toBe(true) + const wall = s.nodes[s.divider.id] as WallNode + const support = wallSupportForNodes(wall, s.nodes) + expect(support.elevation).toBe(0.05) + expect(support.faceDatum.a[0]!.elevation).toBe(0.55) + expect(support.faceBottom.a[0]!.elevation).toBe(0.05) + expect(resolveWallTop({ ...wall, height: 2.5 }, 3, support.elevation)).toBe(2.55) + const part = computePlateSurfacePartition( + base, + plateLevelContext(s.nodes[s.level.id]!, (id) => s.nodes[id]), + )! + expect(area(part.masked)).toBeGreaterThan(0) +}) + +test.each([ + [0.55, 0.05], + [0.05, -0.4], + [0.55, -0.4], + [0.55, 0.3], + [0.55, 0.55], +])('D6 door %s/%s stands on one full aperture at the higher floor', (high, low) => { + const s = scene(high, low) + const wall = s.nodes[s.divider.id] as WallNode + const cut = getOpeningWallCut(wall, s.door, s.nodes) + expect(getOpeningFloorDatum(wall, s.door, s.nodes)).toBe(high) + expect(cut.covered).toBe(true) + const carriers = plates(s.nodes).filter( + (p) => + Math.abs(p.elevation - high) < 0.001 && + area(intersection(cut.aperture, { outer: p.polygon, holes: p.holes })) > 0.001, + ) + expect(carriers).toHaveLength(1) + expect( + area(intersection(cut.aperture, { outer: carriers[0]!.polygon, holes: carriers[0]!.holes })), + ).toBeCloseTo(area(cut.aperture), 5) +}) + +test('D6 exterior raised door retains an upstand; wall windows keep their datum', () => { + const s = scene() + const wall = s.walls[0]! + const door = DoorNode.parse({ ...s.door, id: 'door_outside', parentId: wall.id, wallId: wall.id }) + const nodes = reconcileStructureOnLoad({ + ...s.nodes, + [door.id]: door, + [wall.id]: { ...wall, children: [door.id] }, + }).nodes + const cut = getOpeningWallCut(nodes[wall.id] as WallNode, door, nodes) + expect(cut.datum).toBe(0.55) + expect(cut.covered).toBe(false) + expect(cut.bottom).toBe(0.55) + expect(getOpeningFloorDatum(wall, { ...door, position: [2, 1.5, 0], height: 1 }, nodes)).toBe( + 0.05, + ) +}) + +test('D9 room plate ID survives edits and raised/sunken flips; base ID survives retirement', () => { + const s = scene() + const base = plates(s.nodes).find((p) => p.plateRole === 'base')! + const own = plates(s.nodes).find((p) => p.plateRole === 'platform')! + let nodes = s.nodes + for (const elevation of [0.3, 0.8, -0.3, -0.7, 0.55]) { + const zone = nodes[s.zones[0]!.id] as ZoneNode + nodes = reconcileStructureOnLoad({ + ...nodes, + [zone.id]: { ...zone, floor: { ...zone.floor, elevation } }, + }).nodes + expect(nodes[base.id]?.type).toBe('slab') + expect(nodes[own.id]).toMatchObject({ elevation }) + } + const zone = nodes[s.zones[0]!.id] as ZoneNode + nodes = reconcileStructureOnLoad({ + ...nodes, + [zone.id]: { ...zone, floor: { elevation: 0.05 } }, + }).nodes + expect(nodes[own.id]).toBeUndefined() + expect(nodes[base.id]).toBeDefined() +}) + +test('D10 plate writes allow base construction and refuse derived elevation and room slots', () => { + const s = scene() + const base = plates(s.nodes).find((p) => p.plateRole === 'base')! + const own = plates(s.nodes).find((p) => p.plateRole === 'platform')! + expect(derivedFieldViolations(base, { elevation: 1 })).toContain('elevation') + expect( + derivedFieldViolations(base, { + thickness: 0.2, + foundation: { type: 'solid' }, + slots: { edge: 'library:stone' }, + }), + ).toEqual([]) + expect(derivedFieldViolations(base, { slots: { surface: 'library:stone' } })).toContain('slots') + expect( + derivedFieldViolations(own, { slots: { riser: 'library:stone' }, thickness: 0.3 }), + ).toEqual(expect.arrayContaining(['slots', 'thickness'])) +}) + +test('D11 commands refuse worse conflicts while raw store writes never throw', () => { + const s = scene(0.55) + const wall = { ...(s.nodes[s.divider.id] as WallNode), height: 2.5 } + const door = { ...s.door, height: 2.1, position: [2, 1.05, 0] as [number, number, number] } + const nodes = { ...s.nodes, [wall.id]: wall, [door.id]: door } + const checked = checkRoomFloor(nodes, s.zones[0]!.id, 0.8) + expect(checked.maxElevation).toBeCloseTo(0.45) + expect(checked.elevation).toBeCloseTo(0.45) + expect(checked.conflicts[0]!.code).toBe('floor-opening-fit') + expect( + setZoneIntent(nodes, { zoneId: s.zones[0]!.id, patch: { floor: { elevation: 0.8 } } }).changes, + ).toEqual([]) + expect(() => + filterDerivedNodeWrites(nodes, { + update: [{ id: s.zones[0]!.id, data: { floor: { elevation: 0.8 } } }], + }), + ).not.toThrow() + expect(reconcileStructureOnLoad(nodes).nodes[s.zones[0]!.id]).toMatchObject({ + floor: { elevation: 0.55 }, + }) +}) + +test('D12 valid upper depression keeps the soffit and deeper authoring is refused', () => { + const s = scene(0.03, 0.05, false) + const ground = LevelNode.parse({ id: 'level_ground', level: 0 }) + const building = BuildingNode.parse({ children: [ground.id, s.level.id] }) + const level = { ...(s.nodes[s.level.id] as LevelNode), parentId: building.id, level: 1 } + const lowerWalls = Object.values(s.nodes) + .filter((node): node is WallNode => node.type === 'wall' && node.parentId === level.id) + .map((wall) => ({ ...wall, id: `${wall.id}_lower` as WallNode['id'], parentId: ground.id })) + const input = { + ...s.nodes, + ...Object.fromEntries(lowerWalls.map((wall) => [wall.id, wall])), + [ground.id]: { ...ground, parentId: building.id, children: lowerWalls.map((wall) => wall.id) }, + [building.id]: building, + [level.id]: level, + } + const nodes = reconcileStructureOnLoad( + migrateFloorPlates(migrateRoomZones(input).nodes).nodes, + ).nodes + const sunken = plates(nodes).find((p) => p.plateRole === 'sunken')! + expect(sunken.thickness).toBeCloseTo(0.03) + expect(sunken.elevation - sunken.thickness).toBeCloseTo(0) + expect(checkRoomFloor(nodes, s.zones[0]!.id, -0.1).minElevation).toBeCloseTo(0.02) +}) + +test('D13 numeric millimetre steps remain authored without handle snapping', () => { + const s = scene(0.052, 0.05, false) + expect(plates(s.nodes).find((p) => p.plateRole === 'platform')?.thickness).toBeCloseTo(0.002) +}) + +test('§14 footprint floor intent translates explicit room floors in one batch and clearing resumes derivation', () => { + const s = scene() + const updates = expandFloorIntentChanges(s.nodes, [ + { id: plates(s.nodes).find((p) => p.plateRole === 'base')!.id, data: { floorHeight: 0.25 } }, + ]) + expect(updates.length).toBeGreaterThanOrEqual(3) + const nodes = { ...s.nodes } + for (const { id, data } of updates) nodes[id] = { ...nodes[id], ...data } as AnyNode + expect((nodes[s.zones[0]!.id] as ZoneNode).floor?.elevation).toBeCloseTo(0.75) + expect(getRoomBaseElevation(nodes, s.zones[0]!.id)).toBe(0.25) + const reset = expandFloorIntentChanges(nodes, [ + { + id: plates(s.nodes).find((p) => p.plateRole === 'base')!.id, + data: { floorHeight: undefined }, + }, + ]) + expect( + (reset.find((u) => u.id === s.zones[0]!.id)!.data as Partial).floor?.elevation, + ).toBeCloseTo(0.55) +}) + +test('D2/D7 courtyard wall bands persist without adding an interior floor', () => { + const s = scene() + const zone = s.nodes[s.zones[1]!.id] as ZoneNode + const nodes = reconcileStructureOnLoad({ + ...s.nodes, + [zone.id]: { ...zone, hasFloor: false }, + }).nodes + const base = plates(nodes).find((p) => p.plateRole === 'base')! + const shape = [{ outer: base.polygon, holes: base.holes }] + expect(containsPoint(shape, [6, 2])).toBe(false) + expect(containsPoint(shape, [6, 0])).toBe(false) + const support = wallSupportForNodes(nodes[s.divider.id] as WallNode, nodes) + expect(support.faceDatum.b[0]!.elevation).toBe(0.05) +}) + +test('D8 a sunken doorway step belongs to the base-height room and uses its step role', () => { + const s = scene(0.05, -0.4) + const base = plates(s.nodes).find((p) => p.plateRole === 'base')! + const part = computePlateSurfacePartition( + base, + plateLevelContext(s.nodes[s.level.id]!, (id) => s.nodes[id]), + )! + expect( + part.sides.some( + (side) => side.role === 'riser' && side.zoneId === s.zones[0]!.id && side.dropTo === -0.4, + ), + ).toBe(true) + expect(part.sides.filter((side) => side.role === 'edge').every((side) => !side.zoneId)).toBe(true) +}) + +test('D14 raising every room keeps wall support at the level floor', () => { + const s = scene(0.6, 0.6) + expect(plates(s.nodes).filter((p) => p.plateRole === 'platform')).toHaveLength(2) + expect(getRoomBaseElevation(s.nodes, s.zones[0]!.id)).toBe(0.05) + expect(wallSupportForNodes(s.nodes[s.divider.id] as WallNode, s.nodes).elevation).toBe(0.05) +}) + +test('support offsets move W while plate-carried face datums stay on their own floor', () => { + const s = scene(0.55, 0.05, false) + const wall = { ...(s.nodes[s.divider.id] as WallNode), supportOffset: 0.2 } + const support = wallSupportForNodes(wall, { ...s.nodes, [wall.id]: wall }) + expect(support.elevation).toBeCloseTo(0.25) + expect(support.faceDatum.a[0]!.elevation).toBe(0.55) + expect(support.faceDatum.b[0]!.elevation).toBe(0.05) + expect(support.faceBottom.a[0]!.elevation).toBeCloseTo(0.25) + expect(support.faceBottom.b[0]!.elevation).toBe(0.05) +}) + +test.each([ + 0.049, 0.051, +])('D13 exact millimetre floor %s has its own nonempty plate', (elevation) => { + const s = scene(elevation, 0.05, false) + const own = plates(s.nodes).find((plate) => plate.plateRole !== 'base')! + expect(own).toBeDefined() + expect(area([{ outer: own.polygon, holes: own.holes }])).toBeGreaterThan(1) +}) + +test('D11 door resizing and wall lowering use the same floor feasibility check', () => { + const s = scene(0.3) + expect(() => + assertDerivedNodeWrites(s.nodes, { + update: [{ id: s.door.id, data: { height: 3, position: [2, 1.5, 0] } }], + }), + ).toThrow('fit') + expect(() => + assertDerivedNodeWrites(s.nodes, { update: [{ id: s.divider.id, data: { height: 2 } }] }), + ).toThrow('fit') +}) + +test('D14 moving the structural floor also moves the explicit wall top in the feasibility draft', () => { + const s = scene(0.3) + const nodes = { + ...s.nodes, + [s.divider.id]: { ...(s.nodes[s.divider.id] as WallNode), height: 2.5 }, + } + expect(() => + filterDerivedNodeWrites(nodes, { + update: [ + { + id: plates(s.nodes).find((p) => p.plateRole === 'base')!.id, + data: { floorHeight: 0.25 }, + }, + ], + }), + ).not.toThrow() +}) + +test('D1 authoring hints stay advisory and do not change a feasible floor', () => { + const s = scene(0.3) + const nodes = { ...s.nodes, [s.door.id]: { ...s.door, swingDirection: 'outward' as const } } + const check = checkRoomFloor(nodes, s.zones[0]!.id, 0.3) + expect(check.conflicts.filter((c) => c.severity === 'error')).toEqual([]) + expect(check.conflicts.map((c) => c.code)).toEqual( + expect.arrayContaining(['floor-door-step', 'floor-door-swing']), + ) + expect(check.elevation).toBe(0.3) + const noDoor = scene(0.6, 0.05, false) + noDoor.nodes[noDoor.level.id] = { ...noDoor.level, height: 2.5 } + expect(checkRoomFloor(noDoor.nodes, noDoor.zones[0]!.id, 0.6).conflicts).toContainEqual( + expect.objectContaining({ code: 'floor-low-headroom', severity: 'warning' }), + ) +}) + +test('D8/D10 mezzanine underside remains plate construction while fascia belongs to the zone', () => { + const s = scene() + const plate = { + ...plates(s.nodes)[0]!, + support: 'open' as const, + plateRole: undefined, + slots: { underside: 'library:old' }, + } + expect(derivedFieldViolations(plate, { slots: { underside: 'library:new' } })).toEqual([]) + expect( + derivedFieldViolations(plate, { slots: { underside: 'library:old', edge: 'library:new' } }), + ).toContain('slots') +}) + +test('D13 a one-millimetre raised exterior threshold still retains its upstand', () => { + const s = scene(0.051, 0.05) + const wall = s.walls[0]! + const door = { ...s.door, parentId: wall.id, wallId: wall.id } + const nodes = reconcileStructureOnLoad({ + ...s.nodes, + [wall.id]: { ...wall, children: [door.id] }, + [door.id]: door, + }).nodes + const cut = getOpeningWallCut(wall, door, nodes) + expect(cut.covered).toBe(false) + expect(cut.bottom).toBeCloseTo(0.051) +}) + +test('H2 every command edit may retain or improve an existing opening overload', () => { + const s = scene(0.55) + const wall = { ...(s.nodes[s.divider.id] as WallNode), height: 2.5 } + const nodes = { ...s.nodes, [wall.id]: wall } + for (const data of [{ position: [2.1, 1.05, 0] }, { height: 2, position: [2, 1, 0] }]) + expect(() => + assertDerivedNodeWrites(nodes, { + update: [{ id: s.door.id, data: data as Partial }], + }), + ).not.toThrow() + expect( + setZoneIntent(nodes, { zoneId: s.zones[0]!.id, patch: { floor: { elevation: 0.5 } } }) + .conflicts ?? [], + ).toEqual([]) + expect(() => + assertDerivedNodeWrites(nodes, { update: [{ id: wall.id, data: { height: 2.6 } }] }), + ).not.toThrow() + expect(() => + assertDerivedNodeWrites(nodes, { update: [{ id: wall.id, data: { height: 2.4 } }] }), + ).toThrow() +}) + +test('H2 newly created doors must fit, including a wall with no room', () => { + const s = scene(0.3) + const door = DoorNode.parse({ + ...s.door, + id: 'door_review_new', + height: 3, + position: [2, 1.5, 0], + }) + expect(() => assertDerivedNodeWrites(s.nodes, { create: [{ node: door }] })).toThrow() + const wallsOnly = Object.fromEntries(Object.entries(s.nodes).filter(([, n]) => n.type !== 'zone')) + expect(() => assertDerivedNodeWrites(wallsOnly, { create: [{ node: door }] })).toThrow() + expect(() => filterDerivedNodeWrites(s.nodes, { create: [{ node: door }] })).not.toThrow() +}) + +test('room-relative heights round to micrometres and handle clamps stay on the 5 cm grid', () => { + const s = scene(0.3) + const wall = { ...s.nodes[s.divider.id], height: 2.479 } as WallNode + const nodes = { ...s.nodes, [wall.id]: wall } + expect(getRoomRelativeFloorElevation(nodes, s.zones[0]!.id)).toBe(0.25) + expect(roomFloorElevationFromRelative(nodes, s.zones[0]!.id, 0.35)).toBe(0.4) + expect(checkRoomFloor(nodes, s.zones[0]!.id, 0.8).maxElevation).toBeCloseTo(0.529) + expect(clampRoomFloorHandle(nodes, s.zones[0]!.id, 0.8)).toBe(0.5) +}) diff --git a/packages/core/src/lib/floor-opening-footprints.ts b/packages/core/src/lib/floor-opening-footprints.ts new file mode 100644 index 0000000000..1c84e5519e --- /dev/null +++ b/packages/core/src/lib/floor-opening-footprints.ts @@ -0,0 +1,187 @@ +import type { AnyNode, DoorNode, WallNode, WindowNode } from '../schema' +import { getWallCurveFrameAt, getWallCurveLength, isCurvedWall } from '../systems/wall/wall-curve' +import type { PlateRoom } from './floor-plates' +import { openingFitsAtDatum } from './opening-floor-datum' +import { difference, intersection, type MultiPolygon, type Ring, union } from './polygon-boolean' + +export function isFloorAnchoredOpening( + opening: Pick & + Partial>, +) { + if (opening.verticalAnchor) return opening.verticalAnchor === 'floor' + return opening.position[1] - opening.height / 2 <= 0.01 +} + +/** + * The wall's `from`–`to` span as a plan band reaching well past both faces + * (and any justification offset). A wall cutter must overshoot the body it + * removes: a cutter whose sides coincide with the wall faces leaves the CSG + * subtraction coplanar, which silently drops the cut. + */ +export function wallOpeningBand(wall: WallNode, from: number, to: number): Ring { + if (to <= from) return [] + const count = isCurvedWall(wall) ? Math.max(2, Math.ceil((to - from) * 96)) : 1 + const width = Math.max(wall.thickness ?? 0.15, 0.15) * 2 + const sides = [1, -1].map((sign) => + Array.from({ length: count + 1 }, (_, i): [number, number] => { + const frame = getWallCurveFrameAt(wall, from + ((to - from) * i) / count) + return [ + frame.point.x + frame.normal.x * width * sign, + frame.point.y + frame.normal.y * width * sign, + ] + }), + ) + return [...sides[0]!, ...sides[1]!.reverse()] +} + +export function wallOpeningFootprint( + wall: WallNode, + footprint: Ring, + from: number, + to: number, +): MultiPolygon { + if (to <= from || !footprint.length) return [] + return intersection(footprint, wallOpeningBand(wall, from, to)) +} + +export function openingAperture( + wall: WallNode, + opening: Pick, + footprints: ReadonlyMap, +): MultiPolygon { + const length = getWallCurveLength(wall) + if (length < 1e-9) return [] + const from = Math.max(0, (opening.position[0] - opening.width / 2) / length) + const to = Math.min(1, (opening.position[0] + opening.width / 2) / length) + const aperture = wallOpeningFootprint(wall, footprints.get(wall.id) ?? [], from, to) + const points = aperture.flatMap((part) => part.outer) + const xs = points.map((p) => p[0]), + zs = points.map((p) => p[1]) + const minX = Math.min(...xs) - 0.0001, + maxX = Math.max(...xs) + 0.0001 + const minZ = Math.min(...zs) - 0.0001, + maxZ = Math.max(...zs) + 0.0001 + const neighbours = [...footprints] + .filter( + ([id, ring]) => + id !== wall.id && + Math.max(...ring.map((p) => p[0])) >= minX && + Math.min(...ring.map((p) => p[0])) <= maxX && + Math.max(...ring.map((p) => p[1])) >= minZ && + Math.min(...ring.map((p) => p[1])) <= maxZ, + ) + .map(([, ring]) => ring) + return difference(aperture, neighbours.length ? union(neighbours) : []) +} + +export type OpeningLanding = { + openingId: string + wallId: string + zoneId: string + elevation: number + polygons: MultiPolygon + exterior: boolean +} + +export function openingLandings( + rooms: PlateRoom[], + elevationOf: (room: PlateRoom) => number, + nodes: Readonly>, + apertures?: ReadonlyMap, +): OpeningLanding[] { + const result: OpeningLanding[] = [] + const context = rooms[0]?.context + if (!context) return result + for (const wall of context.walls.values()) { + const length = getWallCurveLength(wall) + if (length < 1e-9) continue + const spans = rooms.flatMap((room) => + room.spans.filter((span) => span.boundaryId === wall.id).map((span) => ({ room, span })), + ) + for (const id of wall.children ?? []) { + const opening = nodes[id] + if ( + (opening?.type !== 'door' && opening?.type !== 'window') || + !isFloorAnchoredOpening(opening) + ) + continue + const chord = (station: number) => { + const { point } = getWallCurveFrameAt(wall, station / length) + const dx = wall.end[0] - wall.start[0], + dz = wall.end[1] - wall.start[1] + return ( + ((point.x - wall.start[0]) * dx + (point.y - wall.start[1]) * dz) / (dx * dx + dz * dz) + ) + } + const from = Math.max(0, chord(opening.position[0] - opening.width / 2)) + const to = Math.min(1, chord(opening.position[0] + opening.width / 2)) + const cuts = [ + ...new Set([ + from, + to, + ...spans.flatMap(({ span }) => [span.t0, span.t1]).filter((t) => t > from && t < to), + ]), + ].sort((a, b) => a - b) + const facing = spans.filter( + ({ span }) => Math.min(to, span.t1) - Math.max(from, span.t0) > 1e-7, + ) + const carried = cuts + .slice(1) + .every((end, i) => + ['a', 'b'].every((face) => + facing.some( + ({ span }) => + span.face === face && + span.t0 <= (end + cuts[i]!) / 2 && + span.t1 >= (end + cuts[i]!) / 2, + ), + ), + ) + const exterior = + facing.length > 0 && + facing.every( + ({ room, span }) => + room.zone.id === facing[0]!.room.zone.id && span.face === facing[0]!.span.face, + ) && + cuts + .slice(1) + .every((end, i) => + facing.some( + ({ span }) => span.t0 <= (end + cuts[i]!) / 2 && span.t1 >= (end + cuts[i]!) / 2, + ), + ) + if (!carried && !exterior) continue + const owner = facing + .map(({ room }) => room) + .sort((a, b) => { + const delta = elevationOf(b) - elevationOf(a) + return Math.abs(delta) > 0.001 ? delta : a.zone.id.localeCompare(b.zone.id) + })[0] + if (!owner) continue + if (!openingFitsAtDatum(wall, opening, elevationOf(owner), nodes)) continue + result.push({ + openingId: id, + wallId: wall.id, + zoneId: owner.zone.id, + elevation: elevationOf(owner), + exterior, + polygons: apertures?.get(id) ?? openingAperture(wall, opening, context.wallFootprints), + }) + } + } + return result +} + +export function floorOpeningFootprints( + rooms: PlateRoom[], + elevationOf: (room: PlateRoom) => number, + nodes: Readonly>, +): Map { + const result = new Map() + for (const landing of openingLandings(rooms, elevationOf, nodes)) { + // Exterior ownership changes paint, not the existing step footprint. + if (landing.exterior) continue + result.set(landing.zoneId, union([result.get(landing.zoneId) ?? [], landing.polygons])) + } + return result +} diff --git a/packages/core/src/lib/floor-opening-intent.test.ts b/packages/core/src/lib/floor-opening-intent.test.ts new file mode 100644 index 0000000000..f0ae8b5276 --- /dev/null +++ b/packages/core/src/lib/floor-opening-intent.test.ts @@ -0,0 +1,497 @@ +import { expect, test } from 'bun:test' +import { duplicateZone } from '../commands/structure/duplicate-zone' +import { cutFloorOpening, removeFloorOpening } from '../commands/structure/floor-opening' +import { applyToScratch, structureChangeBatch } from '../commands/structure/shared' +import { + type AnyNode, + BuildingNode, + LevelNode, + SeparatorNode, + SlabNode, + StairNode, + WallNode, + ZoneNode, +} from '../schema' +import { cloneLevelSubtree } from '../utils/clone-scene-graph' +import { migrateFloorOpeningNodes } from '../utils/floor-opening-migration' +import { reconcileStructureOnLoad } from '../utils/reconcile-structure-on-load' +import { area, union } from './polygon-boolean' +import { reconcileSceneStructure } from './structure-reconcile' + +const outline: [number, number][] = [ + [0, 0], + [6, 0], + [6, 5], + [0, 5], +] +const aperture: [number, number][] = [ + [2, 2], + [3, 2], + [3, 3], + [2, 3], +] +const mintId = (() => { + let n = 0 + return (kind: string) => `${kind}_test_${n++}` +})() + +function house() { + const building = BuildingNode.parse({ id: 'building_openings' }) + const levels = [0, 1].map((number) => { + const id = `level_openings_${number}` + const walls = outline.map((start, index) => + WallNode.parse({ + id: `wall_openings_${number}_${index}`, + parentId: id, + start, + end: outline[(index + 1) % 4], + }), + ) + const level = LevelNode.parse({ + id, + parentId: building.id, + level: number, + children: walls.map((wall) => wall.id), + }) + return [level, ...walls] + }) + const nodes = Object.fromEntries([building, ...levels.flat()].map((node) => [node.id, node])) + return reconcileSceneStructure({ nodes, mintId }).nodes +} + +function surface(nodes: Record, levelId: string, kind: 'slab' | 'ceiling') { + return Object.values(nodes).find((node) => node.type === kind && node.parentId === levelId) as + | Extract + | undefined +} + +test('one floor opening cuts the upper plate and the lower ceiling, then restores both', () => { + const before = house() + const plan = cutFloorOpening(before, { levelId: 'level_openings_1', polygon: aperture, mintId }) + const next = reconcileSceneStructure({ + nodes: applyToScratch(before, structureChangeBatch(plan.changes)), + mintId, + }).nodes + const upper = surface(next, 'level_openings_1', 'slab')! + const lower = surface(next, 'level_openings_0', 'ceiling')! + const ownCeiling = surface(next, 'level_openings_1', 'ceiling')! + expect(upper.holeMetadata.some((entry) => entry.openingId === plan.openingIds[0])).toBe(true) + expect(lower.holeMetadata.some((entry) => entry.openingId === plan.openingIds[0])).toBe(true) + expect(ownCeiling.holeMetadata.some((entry) => entry.openingId === plan.openingIds[0])).toBe( + false, + ) + expect(reconcileSceneStructure({ nodes: next, mintId }).patches).toEqual([]) + const removed = removeFloorOpening(next, plan.openingIds[0]!) + const restored = reconcileSceneStructure({ + nodes: applyToScratch(next, structureChangeBatch(removed.changes)), + mintId, + }).nodes + expect( + surface(restored, 'level_openings_1', 'slab')?.holeMetadata.some( + (entry) => entry.source === 'floor-opening', + ), + ).toBe(false) + expect( + surface(restored, 'level_openings_0', 'ceiling')?.holeMetadata.some( + (entry) => entry.source === 'floor-opening', + ), + ).toBe(false) + expect(reconcileSceneStructure({ nodes: restored, mintId }).patches).toEqual([]) +}) + +test('ceiling-only top storey leaves the floor unchanged', () => { + const before = house() + const plan = cutFloorOpening(before, { + levelId: 'level_openings_1', + polygon: aperture, + drawnOn: 'ceiling', + mintId, + }) + const next = reconcileSceneStructure({ + nodes: applyToScratch(before, structureChangeBatch(plan.changes)), + mintId, + }).nodes + expect(plan.openingIds).toHaveLength(1) + expect( + surface(next, 'level_openings_1', 'ceiling')?.holeMetadata.some( + (entry) => entry.source === 'floor-opening', + ), + ).toBe(true) + expect( + surface(next, 'level_openings_1', 'slab')?.holeMetadata.some( + (entry) => entry.source === 'floor-opening', + ), + ).toBe(false) +}) + +test('ceiling-drawn opening cuts that ceiling and the floor above', () => { + const before = house() + const plan = cutFloorOpening(before, { + levelId: 'level_openings_0', + polygon: aperture, + drawnOn: 'ceiling', + mintId, + }) + const next = reconcileSceneStructure({ + nodes: applyToScratch(before, structureChangeBatch(plan.changes)), + mintId, + }).nodes + const id = plan.openingIds[0] + expect( + surface(next, 'level_openings_0', 'ceiling')?.holeMetadata.some( + (entry) => entry.openingId === id, + ), + ).toBe(true) + expect( + surface(next, 'level_openings_1', 'slab')?.holeMetadata.some((entry) => entry.openingId === id), + ).toBe(true) + expect( + surface(next, 'level_openings_0', 'slab')?.holeMetadata.some((entry) => entry.openingId === id), + ).toBe(false) +}) + +test('manual ceiling below is left whole and reported as a hint', () => { + const before = house() + const ceiling = surface(before, 'level_openings_0', 'ceiling')! + const manual = { ...ceiling, boundary: undefined, autoFromWalls: false } + const nodes = { ...before, [ceiling.id]: manual } as Record + const plan = cutFloorOpening(nodes, { levelId: 'level_openings_1', polygon: aperture, mintId }) + expect(plan.hints).toEqual([ + expect.objectContaining({ code: 'manual-ceiling', surfaceIds: [ceiling.id] }), + ]) + const next = reconcileSceneStructure({ + nodes: applyToScratch(nodes, structureChangeBatch(plan.changes)), + mintId, + }).nodes + expect((next[ceiling.id] as Extract).holes).toEqual(ceiling.holes) + expect( + surface(next, 'level_openings_1', 'slab')?.holeMetadata.some( + (entry) => entry.source === 'floor-opening', + ), + ).toBe(true) +}) + +test('mezzanine hatch cuts only its hosted plate', () => { + const before = house() + const host = Object.values(before).find( + (node) => node.type === 'zone' && node.parentId === 'level_openings_0', + )! + if (host.type !== 'zone') throw Error('missing host') + const mezz = ZoneNode.parse({ + id: 'zone_openings_mezzanine', + parentId: host.parentId, + hostZoneId: host.id, + name: 'Mezzanine', + spaceRole: 'room', + polygon: [ + [1, 1], + [4, 1], + [4, 4], + [1, 4], + ], + floor: { support: 'open', elevation: 1.4, thickness: 0.2 }, + }) + const level = before[host.parentId!] as Extract + const withMezz = reconcileSceneStructure({ + nodes: { + ...before, + [mezz.id]: mezz, + [level.id]: { ...level, children: [...level.children, mezz.id] }, + }, + mintId, + }).nodes + const unhosted = cutFloorOpening(withMezz, { + levelId: level.id, + polygon: aperture, + mintId, + }) + const throughBase = reconcileSceneStructure({ + nodes: applyToScratch(withMezz, structureChangeBatch(unhosted.changes)), + mintId, + }).nodes + expect( + Object.values(throughBase) + .filter((node) => node.type === 'slab' && node.support === 'open') + .some((node) => + node.holeMetadata.some((entry) => entry.openingId === unhosted.openingIds[0]), + ), + ).toBe(false) + const plan = cutFloorOpening(withMezz, { zoneId: mezz.id, polygon: aperture, mintId }) + const next = reconcileSceneStructure({ + nodes: applyToScratch(withMezz, structureChangeBatch(plan.changes)), + mintId, + }).nodes + expect( + (next[plan.openingIds[0]!] as Extract).hostZoneId, + ).toBe(mezz.id) + expect( + Object.values(next) + .filter((node) => node.type === 'slab' && node.support === 'open') + .some((node) => node.holeMetadata.some((entry) => entry.openingId === plan.openingIds[0])), + ).toBe(true) + expect( + Object.values(next) + .filter((node) => node.type === 'slab' && node.plateRole === 'base') + .some((node) => node.holeMetadata.some((entry) => entry.openingId === plan.openingIds[0])), + ).toBe(false) + expect( + surface(next, 'level_openings_0', 'ceiling')?.holeMetadata.some( + (entry) => entry.openingId === plan.openingIds[0], + ), + ).toBe(false) + const cloned = cloneLevelSubtree(next as Record, level.id) + const copy = cloned.clonedNodes.find((node) => node.type === 'floor-opening') + expect(copy).toMatchObject({ hostZoneId: cloned.idMap.get(mezz.id) }) + expect( + cloned.clonedNodes + .filter((node) => node.type === 'slab') + .some((node) => node.holeMetadata.some((entry) => entry.openingId === copy?.id)), + ).toBe(true) +}) + +test('room divide preserves an opening identity and its cut', () => { + const before = house() + const plan = cutFloorOpening(before, { levelId: 'level_openings_1', polygon: aperture, mintId }) + const opened = reconcileSceneStructure({ + nodes: applyToScratch(before, structureChangeBatch(plan.changes)), + mintId, + }).nodes + const separator = SeparatorNode.parse({ + id: 'separator_openings_divide', + parentId: 'level_openings_1', + start: [4, 0], + end: [4, 5], + }) + const level = opened['level_openings_1'] as Extract + const divided = reconcileSceneStructure({ + nodes: { + ...opened, + [separator.id]: separator, + [level.id]: { ...level, children: [...level.children, separator.id] }, + }, + mintId, + }).nodes + expect(divided[plan.openingIds[0]!] as AnyNode).toEqual(opened[plan.openingIds[0]!]) + expect( + Object.values(divided) + .filter((node) => node.type === 'slab' && node.parentId === level.id) + .some((node) => node.holeMetadata.some((entry) => entry.openingId === plan.openingIds[0])), + ).toBe(true) +}) + +test('legacy manual plate holes adopt deterministic nodes and load idempotently', () => { + const before = house() + const plate = surface(before, 'level_openings_1', 'slab') as SlabNode + const source = { + ...before, + [plate.id]: { + ...plate, + holes: [...plate.holes, aperture], + holeMetadata: [...plate.holeMetadata, { source: 'manual' as const }], + }, + } + const lowerCeiling = surface(source, 'level_openings_0', 'ceiling')! + const first = migrateFloorOpeningNodes(source) + expect(first.created).toBe(1) + expect(migrateFloorOpeningNodes(first.nodes).changed).toBe(false) + const loaded = reconcileStructureOnLoad(source).nodes + const adopted = Object.values(loaded).filter((node) => node.type === 'floor-opening') + expect(adopted).toHaveLength(1) + expect(adopted[0]).toMatchObject({ + cutsAdjacent: false, + legacyPlateCuts: { [plate.id]: [aperture] }, + }) + expect(surface(loaded, 'level_openings_0', 'ceiling')).toEqual(lowerCeiling) + expect(area(union(surface(loaded, 'level_openings_1', 'slab')!.holes))).toBeCloseTo(1) + const removed = removeFloorOpening(loaded, adopted[0]!.id) + const restored = reconcileSceneStructure({ + nodes: applyToScratch(loaded, structureChangeBatch(removed.changes)), + mintId, + }).nodes + expect(area(union(surface(restored, 'level_openings_1', 'slab')!.holes))).toBe(0) + expect(reconcileStructureOnLoad(loaded).nodes).toEqual(loaded) + expect(reconcileSceneStructure({ nodes: loaded, mintId }).patches).toEqual([]) + expect(area([{ outer: aperture, holes: [] }])).toBe(1) +}) + +test('legacy cuts retain their original plate layer and ignore tiny fragments', () => { + const before = house() + const base = surface(before, 'level_openings_1', 'slab') as SlabNode + const platform = SlabNode.parse({ + ...base, + id: 'slab_legacy_platform_only', + plateRole: 'platform', + elevation: 0.45, + holes: [ + aperture, + [ + [0, 0], + [0.001, 0], + [0, 0.001], + ], + ], + holeMetadata: [{ source: 'manual' }, { source: 'manual' }], + }) + const migrated = migrateFloorOpeningNodes({ ...before, [platform.id]: platform }) + const adopted = Object.values(migrated.nodes).filter( + (node): node is Extract => + (node as AnyNode).type === 'floor-opening', + ) + expect(adopted).toHaveLength(1) + expect(adopted[0]!.legacyPlateCuts).toEqual({ [platform.id]: [aperture] }) + expect(adopted[0]!.legacyPlateCuts?.[base.id]).toBeUndefined() +}) + +test('legacy floor and matching lower ceiling hole adopt one linked void', () => { + const before = house() + const plate = surface(before, 'level_openings_1', 'slab') as SlabNode + const ceiling = surface(before, 'level_openings_0', 'ceiling')! + const source = { + ...before, + [plate.id]: { + ...plate, + holes: [...plate.holes, aperture], + holeMetadata: [...plate.holeMetadata, { source: 'manual' as const }], + }, + [ceiling.id]: { + ...ceiling, + holes: [...ceiling.holes, aperture], + holeMetadata: [...ceiling.holeMetadata, { source: 'manual' as const }], + }, + } + const loaded = reconcileStructureOnLoad(source).nodes + const opening = Object.values(loaded).find((node) => node.type === 'floor-opening')! + expect(opening.type).toBe('floor-opening') + if (opening.type !== 'floor-opening') return + expect(opening.cutsAdjacent).toBe(true) + const lower = surface(loaded, 'level_openings_0', 'ceiling')! + expect(lower.holes).toHaveLength(1) + expect(lower.holeMetadata).toContainEqual( + expect.objectContaining({ source: 'floor-opening', openingId: opening.id }), + ) + expect(reconcileSceneStructure({ nodes: loaded, mintId }).patches).toEqual([]) +}) + +test('a strip produces separate valid ceiling components and an edge notch keeps its opening link', () => { + const before = house() + const strip = cutFloorOpening(before, { + levelId: 'level_openings_1', + polygon: [ + [2.5, -1], + [3.5, -1], + [3.5, 6], + [2.5, 6], + ], + mintId, + }) + const split = reconcileSceneStructure({ + nodes: applyToScratch(before, structureChangeBatch(strip.changes)), + mintId, + }).nodes + const ceilings = Object.values(split).filter( + (node) => node.type === 'ceiling' && node.parentId === 'level_openings_0', + ) + expect(ceilings).toHaveLength(2) + expect(ceilings.every((ceiling) => ceiling.holes.length === 0)).toBe(true) + expect(ceilings.every((ceiling) => ceiling.openingIds?.includes(strip.openingIds[0]!))).toBe(true) + expect(reconcileSceneStructure({ nodes: split, mintId }).patches).toEqual([]) + + const notch = cutFloorOpening(before, { + levelId: 'level_openings_1', + polygon: [ + [0, 2], + [1.5, 2], + [1.5, 3], + [0, 3], + ], + mintId, + }) + const notched = reconcileSceneStructure({ + nodes: applyToScratch(before, structureChangeBatch(notch.changes)), + mintId, + }).nodes + expect(surface(notched, 'level_openings_0', 'ceiling')?.openingIds).toContain(notch.openingIds[0]) +}) + +test('deleting a stair retires its owned opening and restores the surfaces', () => { + const before = house() + const stair = StairNode.parse({ + id: 'stair_owned_opening', + parentId: 'level_openings_0', + fromLevelId: 'level_openings_0', + toLevelId: 'level_openings_1', + }) + const first = { ...before, [stair.id]: stair } + const plan = cutFloorOpening(first, { + levelId: 'level_openings_1', + polygon: aperture, + source: 'stair', + ownerId: stair.id, + mintId, + }) + const withStair = reconcileSceneStructure({ + nodes: applyToScratch(first, structureChangeBatch(plan.changes)), + mintId, + }).nodes + expect(withStair[plan.openingIds[0]!]?.type).toBe('floor-opening') + const withoutStair = { ...withStair } + delete withoutStair[stair.id] + const restored = reconcileSceneStructure({ nodes: withoutStair, mintId }).nodes + expect(restored[plan.openingIds[0]!]).toBeUndefined() + expect(surface(restored, 'level_openings_1', 'slab')?.holeMetadata).not.toContainEqual( + expect.objectContaining({ openingId: plan.openingIds[0] }), + ) + expect(reconcileSceneStructure({ nodes: restored, mintId }).patches).toEqual([]) +}) + +test('duplicating a room clears an uncopied pool owner reference', () => { + const before = house() + const plan = cutFloorOpening(before, { + levelId: 'level_openings_1', + polygon: aperture, + source: 'plugin:pool', + ownerId: 'pool_original', + mintId, + }) + const opened = reconcileSceneStructure({ + nodes: applyToScratch(before, structureChangeBatch(plan.changes)), + mintId, + }).nodes + const zone = Object.values(opened).find( + (node) => node.type === 'zone' && node.parentId === 'level_openings_1', + )! + const copied = duplicateZone(opened, { zoneId: zone.id, translate: [10, 0], mintId }) + const cloned = copied.changes.find( + (change) => change.op === 'create' && change.node.type === 'floor-opening', + ) + expect(cloned?.op).toBe('create') + if (cloned?.op === 'create' && cloned.node.type === 'floor-opening') { + expect(cloned.node.source).toBe('manual') + expect(cloned.node.ownerId).toBeUndefined() + } +}) + +test('legacy pool ownership migrates onto its opening node', () => { + const before = house() + const plate = surface(before, 'level_openings_0', 'slab') as SlabNode + const source = { + ...before, + [plate.id]: { + ...plate, + holes: [...plate.holes, aperture], + holeMetadata: [...plate.holeMetadata, { source: 'manual' as const }], + metadata: { + ...plate.metadata, + poolManagedOpenings: [ + { poolId: 'pool_legacy', polygon: aperture, holeIndex: plate.holes.length }, + ], + }, + }, + } + const migrated = migrateFloorOpeningNodes(source) + const opening = Object.values(migrated.nodes).find( + (node) => (node as AnyNode).type === 'floor-opening', + ) as Extract + expect(opening).toMatchObject({ source: 'plugin:pool', ownerId: 'pool_legacy' }) + expect(migrateFloorOpeningNodes(migrated.nodes).changed).toBe(false) +}) diff --git a/packages/core/src/lib/floor-opening-intent.ts b/packages/core/src/lib/floor-opening-intent.ts new file mode 100644 index 0000000000..48a19abc2c --- /dev/null +++ b/packages/core/src/lib/floor-opening-intent.ts @@ -0,0 +1,112 @@ +import type { AnyNode, FloorOpeningNode } from '../schema' + +export type FloorOpeningSurface = 'floor' | 'ceiling' +type Target = { levelId: string; surface: FloorOpeningSurface } +export type FloorOpeningIndex = { + targets: Map + surfaces: Map +} + +function levelOrder(nodes: Readonly>) { + const buildings = new Map>>() + for (const node of Object.values(nodes)) { + if (node.type !== 'level') continue + const levels = buildings.get(node.parentId) ?? [] + levels.push(node) + buildings.set(node.parentId, levels) + } + const neighbors = new Map() + for (const levels of buildings.values()) { + levels.sort((a, b) => a.level - b.level || a.id.localeCompare(b.id)) + for (const [index, level] of levels.entries()) + neighbors.set(level.id, { below: levels[index - 1]?.id, above: levels[index + 1]?.id }) + } + return neighbors +} + +function targetsFor( + nodes: Readonly>, + opening: FloorOpeningNode, + neighbors: Map, +): Target[] { + const levelId = opening.parentId + if (!levelId || nodes[levelId]?.type !== 'level') return [] + if (opening.hostZoneId) { + const host = nodes[opening.hostZoneId] + return host?.type === 'zone' && host.parentId === levelId && host.floor?.support === 'open' + ? [{ levelId, surface: 'floor' }] + : [] + } + const primary = opening.drawnOn + const adjacent = neighbors.get(levelId)?.[primary === 'floor' ? 'below' : 'above'] + const targets: Target[] = [ + ...(opening.cutsPrimary ? [{ levelId, surface: primary }] : []), + ...(opening.cutsAdjacent && adjacent + ? [{ levelId: adjacent, surface: primary === 'floor' ? 'ceiling' : 'floor' } as Target] + : []), + ] + for (const [surface, cuts] of [ + ['floor', opening.legacyPlateCuts], + ['ceiling', opening.legacyCeilingCuts], + ] as const) + for (const surfaceId of Object.keys(cuts ?? {})) { + const host = nodes[surfaceId] + if (!host?.parentId || nodes[host.parentId]?.type !== 'level') continue + if (!targets.some((target) => target.levelId === host.parentId && target.surface === surface)) + targets.push({ levelId: host.parentId, surface }) + } + return targets +} + +export function createFloorOpeningIndex( + nodes: Readonly>, +): FloorOpeningIndex { + const neighbors = levelOrder(nodes) + const targets = new Map() + const surfaces = new Map() + for (const node of Object.values(nodes)) { + if (node.type !== 'floor-opening') continue + if ( + (node.source === 'stair' || node.source === 'elevator') && + node.ownerId && + nodes[node.ownerId]?.type !== node.source + ) + continue + const resolved = targetsFor(nodes, node, neighbors) + targets.set(node.id, resolved) + for (const target of resolved) { + const key = `${target.levelId}:${target.surface}` + const openings = surfaces.get(key) ?? [] + openings.push(node) + surfaces.set(key, openings) + } + } + for (const openings of surfaces.values()) openings.sort((a, b) => a.id.localeCompare(b.id)) + return { targets, surfaces } +} + +export function adjacentLevelId( + nodes: Readonly>, + levelId: string, + direction: -1 | 1, +): string | undefined { + const neighbor = levelOrder(nodes).get(levelId) + return direction < 0 ? neighbor?.below : neighbor?.above +} + +export function floorOpeningTargets( + nodes: Readonly>, + opening: FloorOpeningNode, + index?: FloorOpeningIndex, +): Target[] { + return index?.targets.get(opening.id) ?? targetsFor(nodes, opening, levelOrder(nodes)) +} + +export function openingsForSurface( + nodes: Readonly>, + levelId: string, + surface: FloorOpeningSurface, + index?: FloorOpeningIndex, +): FloorOpeningNode[] { + return (index ?? createFloorOpeningIndex(nodes)).surfaces.get(`${levelId}:${surface}`) ?? [] +} diff --git a/packages/core/src/lib/floor-plate-id.ts b/packages/core/src/lib/floor-plate-id.ts new file mode 100644 index 0000000000..575d2086b9 --- /dev/null +++ b/packages/core/src/lib/floor-plate-id.ts @@ -0,0 +1,31 @@ +import { area, type Polygon } from './polygon-boolean' + +export function floorPlateId( + levelId: string, + role: string, + zoneIds: readonly string[], + component = 0, +): `slab_${string}` { + let hash = 0xcbf29ce484222325n + const identity = role === 'platform' || role === 'sunken' ? 'room' : role + for (const byte of new TextEncoder().encode( + JSON.stringify([levelId, identity, [...zoneIds].sort(), component]), + )) { + hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100000001b3n) + } + return `slab_${hash.toString(36).padStart(16, '0')}` +} + +export function comparePlateComponents(a: Polygon, b: Polygon): number { + const byArea = area([b]) - area([a]) + if (byArea) return byArea + const lowest = (polygon: Polygon) => + [...polygon.outer].sort((a, b) => a[0] - b[0] || a[1] - b[1])[0] ?? [0, 0] + const left = lowest(a), + right = lowest(b) + return left[0]! - right[0]! || left[1]! - right[1]! +} + +export function keyedFloorPlateId(levelId: string, key: string, component = 0) { + return floorPlateId(levelId, 'keyed-base', [key], component + 1) +} diff --git a/packages/core/src/lib/floor-plate-paint.ts b/packages/core/src/lib/floor-plate-paint.ts new file mode 100644 index 0000000000..60ec39a4d5 --- /dev/null +++ b/packages/core/src/lib/floor-plate-paint.ts @@ -0,0 +1,25 @@ +import type { AnyNode } from '../schema' + +export type FloorPlatePaintRefusal = { + status: 'refused' + code: 'floor-surface-without-room' + message: string +} + +export function floorPlatePaintRefusal( + nodes: Readonly>, + node: AnyNode, + role: string, +): FloorPlatePaintRefusal | undefined { + if ( + node.type === 'slab' && + node.plateRole === 'base' && + role === 'surface' && + !node.zoneIds?.some((id) => nodes[id]?.type === 'zone' && nodes[id].hasFloor !== false) + ) + return { + status: 'refused', + code: 'floor-surface-without-room', + message: 'This structural floor band has no room finish to paint. Paint its edge instead.', + } +} diff --git a/packages/core/src/lib/floor-plate-support.test.ts b/packages/core/src/lib/floor-plate-support.test.ts new file mode 100644 index 0000000000..96184bf720 --- /dev/null +++ b/packages/core/src/lib/floor-plate-support.test.ts @@ -0,0 +1,111 @@ +import { expect, test } from 'bun:test' +import { LevelNode, SlabNode, WallNode, ZoneNode } from '../schema' +import { computeWallSlabSupport } from '../systems/slab/slab-support' +import { migrateFloorPlates } from '../utils/floor-plate-migration' +import { getRenderableSlabPolygon } from './slab-polygon' + +const ring = (x0: number, z0: number, x1: number, z1: number): [number, number][] => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], +] +function fixture(highThickness = 0.45) { + const polygon = ring(0, 0, 8, 4) + const walls = polygon.map((start, i) => + WallNode.parse({ + id: `wall_${i}`, + parentId: 'level_support', + start, + end: polygon[(i + 1) % 4], + thickness: 0.2, + }), + ) + walls.push( + WallNode.parse({ + id: 'wall_divider', + parentId: 'level_support', + start: [4, 0], + end: [4, 4], + thickness: 0.2, + }), + ) + const zones = [ + ZoneNode.parse({ + id: 'zone_low', + parentId: 'level_support', + polygon: ring(0, 0, 4, 4), + name: 'Room', + spaceRole: 'room', + enclosureStatus: 'enclosed', + }), + ZoneNode.parse({ + id: 'zone_high', + parentId: 'level_support', + polygon: ring(4, 0, 8, 4), + name: 'Room', + spaceRole: 'room', + enclosureStatus: 'enclosed', + }), + ] + const slabs = zones.map((zone, i) => + SlabNode.parse({ + id: `slab_${i}`, + parentId: 'level_support', + polygon: zone.polygon, + autoFromWalls: true, + elevation: i ? 0.45 : 0.05, + thickness: i ? highThickness : 0.05, + }), + ) + const level = LevelNode.parse({ + id: 'level_support', + children: [...walls, ...zones, ...slabs].map((node) => node.id), + }) + const nodes = Object.fromEntries( + [level, ...walls, ...zones, ...slabs].map((node) => [node.id, node]), + ) + const migrated = migrateFloorPlates(nodes).nodes as typeof nodes + const plates = Object.values(migrated).filter((node): node is SlabNode => node.type === 'slab') + return { walls, slabs, plates, nodes: migrated } +} + +test.each([ + 0.05, 0.45, +])('base plate carries every wall regardless of legacy thickness %s', (thickness) => { + const { walls, plates, nodes } = fixture(thickness) + const baseHeight = plates.find((plate) => plate.plateRole === 'base')!.elevation + expect(baseHeight).toBe(0.05) + expect(plates.every((plate) => plate.floorHeight === undefined)).toBe(true) + for (const wall of walls) { + const actual = computeWallSlabSupport(wall, plates, walls, undefined, undefined, 0, nodes) + expect(actual.elevation).toBe(baseHeight) + expect(actual.baseSegments).toEqual([{ start: 0, end: 1, elevation: baseHeight }]) + } + const divider = computeWallSlabSupport(walls[4]!, plates, walls, undefined, undefined, 0, nodes) + expect(divider.faceDatum.a[0]!.elevation).toBe(0.05) + expect(divider.faceDatum.b[0]!.elevation).toBe(0.45) + for (const plate of plates) + expect(getRenderableSlabPolygon(plate, { walls, siblingSlabs: plates })).toBe(plate.polygon) +}) + +test('a zero-height exterior deck cannot pull a wall off the continuous base', () => { + const { walls, plates, nodes } = fixture(0.05) + const deck = SlabNode.parse({ + parentId: 'level_support', + polygon: ring(4, -4, 8, 0), + elevation: 0, + }) + const wall = WallNode.parse({ start: [4.2, 0], end: [7.8, 0], thickness: 0.2 }) + const actual = computeWallSlabSupport( + wall, + [...plates, deck], + walls, + undefined, + undefined, + 0, + nodes, + ) + expect(actual.elevation).toBe(0.05) + expect(actual.baseElevation).toBe(0.05) +}) diff --git a/packages/core/src/lib/floor-plates.ts b/packages/core/src/lib/floor-plates.ts new file mode 100644 index 0000000000..0e26bb864d --- /dev/null +++ b/packages/core/src/lib/floor-plates.ts @@ -0,0 +1,919 @@ +import type { AnyNode } from '../schema' +import { DEFAULT_SLAB_ELEVATION, SlabNode } from '../schema/nodes/slab' +import type { SurfaceHoleMetadata } from '../schema/nodes/surface-hole-metadata' +import type { ZoneNode } from '../schema/nodes/zone' +import { stairArrivalOpening } from '../systems/stair/stair-footprint' +import { omitUndefined } from '../utils/omit-undefined' +import { + automaticFloorHeight, + floorPlateHoldsUnderside, + footprintLift, +} from './floor-foundation-datum' +import { floorOpeningFootprints } from './floor-opening-footprints' +import { type FloorOpeningIndex, openingsForSurface } from './floor-opening-intent' +import { comparePlateComponents, keyedFloorPlateId } from './floor-plate-id' +import { + exposedIntervals, + plateFootprint, + roomClearPolygon, + roomWallFootprints, +} from './level-footprints' +import { area, difference, intersection, type Polygon, union } from './polygon-boolean' +import type { TopologyRoom } from './room-topology-index' +import { autoRoomVerticalPlacements } from './room-vertical-placement' +import { getRenderableSlabPolygon } from './slab-polygon' + +export type PlateRoom = TopologyRoom & { zone: ZoneNode } + +// Migration validates construction without interpreting historical material payloads. +export function parseSlabConstruction(source: SlabNode): SlabNode { + const { material, slots, ...construction } = source + return omitUndefined({ + ...SlabNode.parse(construction), + ...(material === undefined ? {} : { material }), + ...(slots === undefined ? {} : { slots }), + }) +} + +export function slabFootprint( + node: Pick & { holes?: SlabNode['holes'] }, +): Polygon { + return { outer: node.polygon, holes: node.holes ?? [] } +} + +type PreparedFootprint = { + signature: string + polygon: Polygon + bounds: readonly [number, number, number, number] + normalized?: Polygon[] + area?: number +} + +const footprintCache = new Map>() +const footprintObjects = new WeakMap>() +const overlapCache = new WeakMap>() + +function prepareFootprint(polygon: Polygon, levelId = ''): PreparedFootprint { + const objectCache = footprintObjects.get(polygon.outer) + const byObject = objectCache?.get(polygon.holes) + if (byObject) return byObject + const signature = JSON.stringify([polygon.outer, polygon.holes]) + let level = footprintCache.get(levelId) + if (!level) { + if (footprintCache.size >= 32) footprintCache.delete(footprintCache.keys().next().value!) + level = new Map() + footprintCache.set(levelId, level) + } + const cached = level.get(signature) + if (cached) { + const cache = objectCache ?? new WeakMap() + cache.set(polygon.holes, cached) + if (!objectCache) footprintObjects.set(polygon.outer, cache) + return cached + } + let minX = Infinity, + minZ = Infinity, + maxX = -Infinity, + maxZ = -Infinity + for (const [x, z] of polygon.outer) { + minX = Math.min(minX, x) + minZ = Math.min(minZ, z) + maxX = Math.max(maxX, x) + maxZ = Math.max(maxZ, z) + } + const prepared = { signature, polygon, bounds: [minX, minZ, maxX, maxZ] } as PreparedFootprint + if (level.size >= 512) level.delete(level.keys().next().value!) + level.set(signature, prepared) + const cache = objectCache ?? new WeakMap() + cache.set(polygon.holes, prepared) + if (!objectCache) footprintObjects.set(polygon.outer, cache) + return prepared +} + +function boundsOverlap(a: PreparedFootprint, b: PreparedFootprint) { + const left = a.bounds, + right = b.bounds + return left[2] > right[0] && right[2] > left[0] && left[3] > right[1] && right[3] > left[1] +} + +function normalizedFootprint(footprint: PreparedFootprint) { + if (!footprint.normalized) { + footprint.normalized = union([footprint.polygon]) + footprint.area = area(footprint.normalized) + } + return footprint.normalized +} + +function preparedIoU(a: PreparedFootprint, b: PreparedFootprint) { + if (!boundsOverlap(a, b)) return 0 + if (a.signature === b.signature) return area([a.polygon]) > 0 ? 1 : 0 + const cached = overlapCache.get(a)?.get(b) + if (cached !== undefined) return cached + const left = normalizedFootprint(a), + right = normalizedFootprint(b) + const overlap = area(intersection(left, right)) + const combined = a.area! + b.area! - overlap + const iou = combined > 0 ? overlap / combined : 0 + let neighbors = overlapCache.get(a) + if (!neighbors) { + neighbors = new WeakMap() + overlapCache.set(a, neighbors) + } + neighbors.set(b, iou) + return iou +} + +export function footprintIoU(a: Polygon, b: Polygon) { + const bounds = (polygon: Polygon) => { + const xs = polygon.outer.map((p) => p[0]), + zs = polygon.outer.map((p) => p[1]) + return [Math.min(...xs), Math.min(...zs), Math.max(...xs), Math.max(...zs)] as const + } + const ab = bounds(a), + bb = bounds(b) + if (ab[2] <= bb[0] || bb[2] <= ab[0] || ab[3] <= bb[1] || bb[3] <= ab[1]) return 0 + const left = union([a]), + right = union([b]) + const overlap = area(intersection(left, right)) + const combined = area(left) + area(right) - overlap + return combined > 0 ? overlap / combined : 0 +} + +function construction(slab?: SlabNode) { + return { + thickness: slab?.thickness ?? 0.05, + recessed: slab?.recessed ?? false, + fillToTerrain: slab?.fillToTerrain ?? false, + } +} + +export function buildFloorPlates({ + rooms, + slabs, + levelId, + mintId, + retiredZones = new Map(), + nodes, + additionalHoles = [], + openingIndex, + renderedManualCuts = true, +}: { + rooms: PlateRoom[] + slabs: SlabNode[] + levelId: string + mintId: (zoneIds: string[], component?: number, role?: string) => string + retiredZones?: ReadonlyMap + nodes?: Readonly> + additionalHoles?: SlabNode[] + openingIndex?: FloorOpeningIndex + renderedManualCuts?: boolean +}) { + const existing = slabs + .filter((slab) => slab.boundary === 'auto' || slab.autoFromWalls) + .sort((a, b) => a.id.localeCompare(b.id)) + const footprints = new Map( + existing.map((slab) => [slab.id, prepareFootprint(slabFootprint(slab), levelId)]), + ) + const footprintOf = (slab: SlabNode) => + footprints.get(slab.id) ?? prepareFootprint(slabFootprint(slab), levelId) + const matchingFootprints = new Map( + existing.map((slab) => [ + slab.id, + prepareFootprint( + { + outer: slab.polygon, + holes: slab.holes.filter((_, i) => slab.holeMetadata[i]?.source === 'room'), + }, + levelId, + ), + ]), + ) + const zoneIdCache = new WeakMap() + const sourceIds = (slab: SlabNode) => { + let ids = zoneIdCache.get(slab) + if (!ids) { + ids = (slab.zoneIds ?? []).map((id) => retiredZones.get(id) ?? id) + zoneIdCache.set(slab, ids) + } + return ids + } + const eligible = rooms + .filter( + (room) => + room.zone.spaceRole === 'room' && + room.zone.enclosureStatus !== 'open' && + room.zone.hasFloor !== false && + (room.zone.floor?.support === 'open' || + !slabs.some( + (slab) => + slab.id === room.zone.floor?.sourceSlabId && + area(intersection(slabFootprint(room), slabFootprint(slab))) > 1e-4, + )), + ) + .sort((a, b) => a.zone.id.localeCompare(b.zone.id)) + const sources = new Map( + eligible.map((room) => { + const face = slabFootprint(room) + const roomFootprint = prepareFootprint(face, levelId) + const candidates = existing + .filter( + (slab) => + slab.support === room.zone.floor?.support && + (slab.plateRole !== 'base' || + !existing.some( + (other) => + other.plateRole && + other.plateRole !== 'base' && + sourceIds(other).includes(room.zone.id), + )) && + (slab.support !== 'open' || sourceIds(slab).includes(room.zone.id)), + ) + .map((slab) => ({ + slab, + linked: sourceIds(slab).includes(room.zone.id), + iou: preparedIoU(footprintOf(slab), roomFootprint), + })) + .filter(({ linked, iou }) => linked || iou > 0) + .sort( + (a, b) => + Number(b.linked) - Number(a.linked) || + b.iou - a.iou || + a.slab.id.localeCompare(b.slab.id), + ) + return [room.zone.id, candidates[0]?.slab] + }), + ) + const derived = nodes ? autoRoomVerticalPlacements(eligible, nodes) : new Map() + const intent = new Map(eligible.map((room) => [room.zone.id, room.zone.floor?.elevation])) + const grounded = eligible.filter((room) => room.zone.floor?.support !== 'open') + const ownRooms = grounded.filter((room) => !!room.zone.floor?.footprint) + const sharedRooms = grounded.filter((room) => !room.zone.floor?.footprint) + const keyedSources = new Map() + const keyedPlateIds = new Set() + for (const key of new Set(ownRooms.map((room) => room.zone.floor!.footprint!))) { + const ids = new Set( + Array.from({ length: existing.length + 1 }, (_, i) => keyedFloorPlateId(levelId, key, i)), + ) + const sources = existing.filter((plate) => plate.plateRole === 'base' && ids.has(plate.id)) + keyedSources.set(key, sources) + for (const source of sources) keyedPlateIds.add(source.id) + } + const ownSource = (room: PlateRoom) => keyedSources.get(room.zone.floor!.footprint!)?.[0] + const inheritedSource = (room: PlateRoom) => + existing + .filter((slab) => slab.plateRole === 'base') + .map((slab) => ({ + slab, + overlap: area(intersection(slabFootprint(slab), slabFootprint(room))), + })) + .filter((entry) => entry.overlap > 0) + .sort((a, b) => b.overlap - a.overlap || a.slab.id.localeCompare(b.slab.id))[0]?.slab + const ownHeight = (room: PlateRoom) => { + const source = ownSource(room) + return ( + source?.floorHeight ?? + (source && nodes && !floorPlateHoldsUnderside(nodes, source) + ? automaticFloorHeight(nodes, source) + : source?.elevation) ?? + room.zone.floor?.elevation ?? + inheritedSource(room)?.elevation ?? + derived.get(room.zone.id) ?? + DEFAULT_SLAB_ELEVATION + ) + } + const wallOwners = new Map() + for (const room of [ + ...sharedRooms, + ...ownRooms + .slice() + .sort( + (a, b) => + ownHeight(b) - ownHeight(a) || + a.zone.floor!.footprint!.localeCompare(b.zone.floor!.footprint!), + ), + ]) + for (const span of room.spans) + if (span.kind === 'wall' && !wallOwners.has(span.boundaryId)) + wallOwners.set(span.boundaryId, room.zone.floor?.footprint) + const partitions = ownRooms.length + ? [ + sharedRooms, + ...[...new Set(ownRooms.map((room) => room.zone.floor!.footprint!))] + .sort() + .map((key) => ownRooms.filter((room) => room.zone.floor!.footprint === key)), + ].filter((group) => group.length) + : [grounded] + const components = partitions + .flatMap((group) => { + const own = group[0]?.zone.floor?.footprint ? group[0] : undefined + const excludedWalls = ownRooms.length + ? [...wallOwners].flatMap(([id, owner]) => { + const polygon = group[0]?.context.wallFootprints.get(id) + return owner !== own?.zone.floor?.footprint && polygon ? [polygon] : [] + }) + : [] + const outline = ownRooms.length + ? union([ + plateFootprint(group), + ...[...wallOwners].flatMap(([id, owner]) => { + const polygon = group[0]?.context.wallFootprints.get(id) + return owner === own?.zone.floor?.footprint && polygon ? [polygon] : [] + }), + ]) + : plateFootprint(group) + return (excludedWalls.length ? difference(outline, union(excludedWalls)) : union([outline])) + .sort(comparePlateComponents) + .map((footprint) => ({ footprint, group, own })) + }) + .flatMap( + ({ + footprint, + group, + own, + }): Array<{ footprint: Polygon; group: PlateRoom[]; own: PlateRoom | undefined }> => { + if (own) return [{ footprint, group, own }] + const owners = existing.filter( + (slab) => + slab.plateRole === 'base' && + !keyedPlateIds.has(slab.id) && + (!ownRooms.length || + sourceIds(slab).some((id) => sharedRooms.some((room) => room.zone.id === id))) && + slab.support !== 'open' && + boundsOverlap(footprintOf(slab), prepareFootprint(footprint, levelId)) && + area(intersection(slabFootprint(slab), footprint)) > 1e-6, + ) + if (new Set(owners.map((slab) => String(slab.referenceFloorElevation))).size <= 1) + return [{ footprint, group, own }] + let remaining: Polygon[] = [footprint] + const domains: Polygon[] = [] + for (const owner of owners.sort((a, b) => a.id.localeCompare(b.id))) { + const claimed = intersection(remaining, slabFootprint(owner)) + domains.push(...claimed) + remaining = difference(remaining, slabFootprint(owner)) + } + return [...domains, ...remaining] + .sort(comparePlateComponents) + .map((footprint) => ({ footprint, group, own })) + }, + ) + .filter( + ({ footprint, group, own }) => + !own || group.some((room) => area(intersection(slabFootprint(room), footprint)) > 1e-6), + ) + .map(({ footprint, group, own }) => { + const members = group.filter((room) => area(intersection(slabFootprint(room), footprint)) > 0) + let source = + (own ? ownSource(own) : undefined) ?? + existing + .filter( + (slab) => + slab.support !== 'open' && + (!slab.plateRole || slab.plateRole === 'base') && + (own || + (!keyedPlateIds.has(slab.id) && + (!ownRooms.length || + sourceIds(slab).some((id) => + sharedRooms.some((room) => room.zone.id === id), + )))), + ) + .map((slab) => ({ + slab, + overlap: boundsOverlap(footprintOf(slab), prepareFootprint(footprint, levelId)) + ? area(intersection(slabFootprint(slab), footprint)) + : 0, + })) + .filter((entry) => entry.overlap > 0) + .sort((a, b) => b.overlap - a.overlap || a.slab.id.localeCompare(b.slab.id))[0]?.slab + if (own && !ownSource(own)) { + const elevation = ownHeight(own) + source = source + ? { + ...source, + ...(!ownSource(own) ? { name: 'Floor plate' } : {}), + floorHeight: elevation, + thickness: + nodes && + floorPlateHoldsUnderside(nodes, { + ...source, + polygon: footprint.outer, + holes: footprint.holes, + }) + ? source.thickness + elevation - source.elevation + : source.thickness, + referenceFloorElevation: elevation - (nodes ? footprintLift(nodes, source) : 0), + } + : undefined + } + const elevation = + (own ? ownHeight(own) : undefined) ?? + source?.floorHeight ?? + (source?.plateRole === 'base' && nodes && floorPlateHoldsUnderside(nodes, source) + ? source.elevation + : undefined) ?? + source?.referenceFloorElevation ?? + (members.length + ? Math.max(...members.map((room) => derived.get(room.zone.id) ?? DEFAULT_SLAB_ELEVATION)) + : DEFAULT_SLAB_ELEVATION) + const holdsUnderside = + !!nodes && + floorPlateHoldsUnderside(nodes, { + ...source, + parentId: levelId, + polygon: footprint.outer, + holes: footprint.holes, + } as SlabNode) + return { footprint, members, source, elevation, own, holdsUnderside } + }) + const componentOf = (room: PlateRoom) => + components.find((component) => component.members.includes(room)) + const baseOf = (room: PlateRoom) => componentOf(room)?.elevation ?? DEFAULT_SLAB_ELEVATION + const elevationOf = (room: PlateRoom) => intent.get(room.zone.id) ?? baseOf(room) + const thresholds = floorOpeningFootprints(grounded, elevationOf, nodes ?? {}) + const interiors = new Map( + grounded.map((room) => [ + room.zone.id, + union([ + Math.abs(elevationOf(room) - baseOf(room)) >= 0.001 - 1e-9 ? roomClearPolygon(room) : [], + ...(thresholds.get(room.zone.id) ?? []), + ]), + ]), + ) + const baseSource = + existing + .filter((slab) => slab.plateRole === 'base') + .sort( + (a, b) => area([slabFootprint(b)]) - area([slabFootprint(a)]) || a.id.localeCompare(b.id), + )[0] ?? + existing.find( + (slab) => + slab.support !== 'open' && Math.abs(slab.elevation - DEFAULT_SLAB_ELEVATION) < 0.001, + ) ?? + (grounded[0] ? sources.get(grounded[0].zone.id) : undefined) + const baseConstruction = construction( + baseSource?.plateRole === 'platform' ? undefined : baseSource, + ) + const supported = (room: PlateRoom) => { + const component = componentOf(room) + return ( + !!nodes && + !!component && + floorPlateHoldsUnderside( + nodes, + (component.source ?? { + id: `slab_support_probe_${levelId}`, + parentId: levelId, + polygon: component.footprint.outer, + }) as SlabNode, + ) + ) + } + const definitions = [ + ...components.map((component) => ({ + members: component.members, + template: component.source, + footprints: difference( + component.own + ? union([ + component.footprint, + ...component.members.flatMap((room) => thresholds.get(room.zone.id) ?? []), + ]) + : component.footprint, + union([ + ...(ownRooms.length + ? grounded + .filter( + (room) => + !component.members.includes(room) && + elevationOf(room) >= component.elevation - 1e-9, + ) + .flatMap((room) => thresholds.get(room.zone.id) ?? []) + : []), + ...component.members + .filter((room) => elevationOf(room) <= component.elevation - 0.001 + 1e-9) + .flatMap((room) => interiors.get(room.zone.id)!), + ]), + ), + elevation: component.elevation, + floorHeight: component.own + ? component.holdsUnderside + ? undefined + : component.elevation + : component.source?.floorHeight, + referenceFloorElevation: component.source?.referenceFloorElevation, + foundation: + component.own && + (component.holdsUnderside || + component.elevation <= + Math.max( + ...component.members.map( + (room) => derived.get(room.zone.id) ?? DEFAULT_SLAB_ELEVATION, + ), + ) - + DEFAULT_SLAB_ELEVATION + + 0.001) + ? { + ...(component.holdsUnderside ? {} : component.source?.foundation), + type: 'none' as const, + } + : (component.source?.foundation ?? { + type: component.source?.fillToTerrain ? ('solid' as const) : ('none' as const), + ...(component.source?.fillToTerrain + ? { + material: + component.source.slots?.edge ?? component.source.slots?.side ?? '#cccccc', + } + : {}), + }), + construction: { + ...construction(component.source), + fillToTerrain: undefined, + }, + plateRole: 'base' as const, + support: undefined, + })), + ...eligible.flatMap((room) => { + const open = room.zone.floor?.support === 'open' + const baseElevation = baseOf(room) + const elevation = open + ? (intent.get(room.zone.id) ?? derived.get(room.zone.id) ?? DEFAULT_SLAB_ELEVATION) + : elevationOf(room) + if (!open && Math.abs(elevation - baseElevation) < 0.001 - 1e-9) return [] + const baseThickness = construction(componentOf(room)?.source).thickness + return [ + { + members: [room], + template: undefined, + floorHeight: undefined, + referenceFloorElevation: undefined, + foundation: undefined, + footprints: open ? [slabFootprint(room)] : interiors.get(room.zone.id)!, + elevation, + construction: open + ? { + thickness: room.zone.floor?.thickness ?? 0.2, + recessed: false, + fillToTerrain: false, + } + : { + thickness: + elevation > baseElevation + ? elevation - baseElevation + : supported(room) && baseElevation - elevation <= baseThickness - 0.02 + 1e-9 + ? baseThickness - (baseElevation - elevation) + : baseThickness, + recessed: false, + fillToTerrain: false, + }, + plateRole: open + ? undefined + : elevation > baseElevation + ? ('platform' as const) + : ('sunken' as const), + support: open ? ('open' as const) : undefined, + }, + ] + }), + ] + const openings = nodes ? openingsForSurface(nodes, levelId, 'floor', openingIndex) : [] + const dynamicOpenings = openings.filter((opening) => !opening.legacyPlateCuts) + const openingFootprints = new Map( + dynamicOpenings.map((opening) => [ + opening.id, + prepareFootprint({ outer: opening.polygon, holes: [] }, levelId), + ]), + ) + const wallFootprints = dynamicOpenings.length + ? [...new Set(eligible.flatMap((room) => [...room.context.wallFootprints.values()]))].map( + (outer) => prepareFootprint({ outer, holes: [] }, levelId), + ) + : [] + const openingCuts = new Map( + dynamicOpenings.map((opening) => { + const footprint = openingFootprints.get(opening.id)! + const walls = wallFootprints + .filter((wall) => boundsOverlap(footprint, wall)) + .map((wall) => wall.polygon) + return [ + opening.id, + walls.length + ? difference(opening.polygon, union(walls)) + : [{ outer: opening.polygon, holes: [] }], + ] as const + }), + ) + const cutsFor = (members: PlateRoom[], support: 'open' | undefined) => + dynamicOpenings.filter((opening) => + opening.hostZoneId + ? support === 'open' && members.some((room) => room.zone.id === opening.hostZoneId) + : support !== 'open', + ) + const authoredVolumes: Array<{ top: number; bottom: number; footprint: Polygon }> = [] + for (const slab of slabs) { + if ( + slab.boundary === 'auto' || + slab.autoFromWalls || + slab.support === 'open' || + !( + slab.associatedZoneIds !== undefined || + rooms.some((room) => room.zone.floor?.sourceSlabId === slab.id) + ) + ) + continue + authoredVolumes.push({ + top: slab.elevation, + bottom: slab.elevation - slab.thickness, + footprint: { + outer: renderedManualCuts + ? getRenderableSlabPolygon(slab, { + walls: [...(rooms[0]?.context.walls.values() ?? [])], + siblingSlabs: slabs.filter((other) => other.id !== slab.id), + }) + : slab.polygon, + holes: slab.holes, + }, + }) + } + let baseComponent = 0 + const ownComponents = new Map() + const nextBaseComponent = (members: PlateRoom[]) => { + const own = members.find((room) => !!room.zone.floor?.footprint) + if (!own) return baseComponent++ + const index = ownComponents.get(own.zone.floor!.footprint!) ?? 0 + ownComponents.set(own.zone.floor!.footprint!, index + 1) + return index + } + const planned = definitions.flatMap(({ footprints, ...definition }) => + footprints + .flatMap((footprint) => { + const prepared = prepareFootprint(footprint, levelId) + const cuts = cutsFor(definition.members, definition.support).flatMap((opening) => + boundsOverlap(prepared, openingFootprints.get(opening.id)!) + ? (openingCuts.get(opening.id) ?? []).filter((cut) => + boundsOverlap(prepared, prepareFootprint(cut, levelId)), + ) + : [], + ) + const occupied = authoredVolumes + .filter( + (volume) => + volume.top >= definition.elevation - 1e-6 && + volume.bottom < definition.elevation - 1e-6, + ) + .map((volume) => volume.footprint) + return cuts.length || occupied.length + ? difference(footprint, union([...cuts, ...occupied])) + : [footprint] + }) + .sort(comparePlateComponents) + .map((footprint, component) => ({ + component: + definition.plateRole === 'base' ? nextBaseComponent(definition.members) : component, + ...definition, + footprint, + zoneIds: definition.members + .filter( + (room) => + definition.plateRole === 'base' || + area(intersection(slabFootprint(room), footprint)) > 0 || + area(intersection(roomWallFootprints([room]), footprint)) > 0, + ) + .map((room) => room.zone.id), + })), + ) + const compatible = (slab: SlabNode, group: (typeof planned)[number]) => + slab.support === group.support && + (group.plateRole !== 'base' || + group.members[0]?.zone.floor?.footprint || + !keyedPlateIds.has(slab.id)) && + (group.plateRole !== 'base' || + !group.members.some((room) => !!room.zone.floor?.footprint) || + slab.id === + keyedFloorPlateId(levelId, group.members[0]!.zone.floor!.footprint!, group.component)) && + (!slab.plateRole || (slab.plateRole === 'base') === (group.plateRole === 'base')) && + (group.support !== 'open' || + sourceIds(slab).some((id) => group.zoneIds.includes(id as ZoneNode['id']))) + const groupFootprints = planned.map((group) => prepareFootprint(group.footprint, levelId)) + const groupZones = planned.map((group) => new Set(group.zoneIds)) + const score = (slab: SlabNode, group: (typeof planned)[number], index: number) => { + const zones = sourceIds(slab) + const overlap = zones.filter((id) => groupZones[index]!.has(id)).length + const slabFoot = matchingFootprints.get(slab.id) ?? footprintOf(slab), + groupFoot = groupFootprints[index]! + return { + overlap, + iou: + overlap === zones.length && + zones.length === groupZones[index]!.size && + slabFoot.signature === groupFoot.signature + ? 1 + : preparedIoU(slabFoot, groupFoot), + } + } + const pairs = planned + .flatMap((group, index) => + existing + .filter((slab) => compatible(slab, group)) + .map((slab) => ({ + slab, + index, + ...score(slab, group, index), + adoptionArea: !slab.plateRole + ? boundsOverlap(footprintOf(slab), groupFootprints[index]!) + ? area( + intersection( + slabFootprint(slab), + union( + group.members + .filter( + (room) => + group.plateRole !== 'base' || + Math.abs(elevationOf(room) - baseOf(room)) < 0.005, + ) + .map(slabFootprint), + ), + ), + ) + : 0 + : 0, + })) + .filter( + ({ slab, overlap, iou }) => + overlap > 0 || + iou > 0 || + (group.plateRole === 'base' && + !!group.members[0]?.zone.floor?.footprint && + slab.id === + keyedFloorPlateId(levelId, group.members[0].zone.floor.footprint, group.component)), + ), + ) + .sort( + (a, b) => + b.adoptionArea - a.adoptionArea || + b.overlap - a.overlap || + b.iou - a.iou || + a.slab.id.localeCompare(b.slab.id) || + a.index - b.index, + ) + const matches = new Map() + const used = new Set() + for (const { index, slab } of pairs) { + if (matches.has(index) || used.has(slab.id)) continue + matches.set(index, slab) + used.add(slab.id) + } + const plates = planned.map((group, index) => { + const matched = matches.get(index) + if (!group.zoneIds.length) group.zoneIds = group.members.map((room) => room.zone.id) + const template = + matched ?? (group.plateRole === 'base' ? group.template : sources.get(group.zoneIds[0]!)) + const plate = parseSlabConstruction({ + ...template, + ...group.construction, + ...(group.plateRole === 'base' && + matched?.plateRole === 'base' && + !group.members.some((room) => !!room.zone.floor?.footprint && !ownSource(room)) + ? construction(matched) + : {}), + id: + group.plateRole === 'base' && group.members[0]?.zone.floor?.footprint + ? keyedFloorPlateId(levelId, group.members[0].zone.floor.footprint, group.component) + : (matched?.id ?? mintId(group.zoneIds, group.component, group.plateRole ?? 'open')), + parentId: levelId, + name: template?.name ?? 'Floor plate', + boundary: 'auto', + autoFromWalls: true, + zoneIds: group.zoneIds, + support: group.support, + plateRole: group.plateRole, + railing: undefined, + floorHeight: group.floorHeight, + referenceFloorElevation: group.referenceFloorElevation, + foundation: group.foundation, + ...(group.plateRole === 'base' ? { fillToTerrain: undefined } : {}), + slots: group.plateRole && group.plateRole !== 'base' ? undefined : template?.slots, + elevation: group.elevation, + polygon: group.footprint.outer, + holes: group.footprint.holes, + holeMetadata: group.footprint.holes.map((hole) => { + const holeFootprint = prepareFootprint({ outer: hole, holes: [] }, levelId) + const opening = cutsFor(group.members, group.support).find( + (candidate) => + boundsOverlap(holeFootprint, openingFootprints.get(candidate.id)!) && + (openingCuts.get(candidate.id) ?? []).some( + (cut) => + boundsOverlap(holeFootprint, prepareFootprint(cut, levelId)) && + area(intersection(hole, cut)) > 1e-6, + ), + ) + return opening + ? { source: 'floor-opening' as const, openingId: opening.id } + : { source: 'room' as const } + }), + } as SlabNode) + const unchangedMatchedFootprint = + !!matched?.plateRole && + matchingFootprints.get(matched.id)?.signature === groupFootprints[index]?.signature + if (unchangedMatchedFootprint) + for (const [i, hole] of matched.holes.entries()) { + const metadata = matched.holeMetadata[i] ?? { source: 'manual' as const } + if (metadata.source === 'room' || metadata.source === 'floor-opening') continue + plate.holes.push(hole) + plate.holeMetadata.push(metadata) + } + const authoredHoles = new Map() + for (const source of [...existing, ...additionalHoles]) { + const matchedSibling = !!matched?.plateRole && source.id !== matched.id && used.has(source.id) + if (source.support !== group.support) continue + const { overlap, iou } = score(source, group, index) + if (!(overlap || iou)) continue + if (unchangedMatchedFootprint && source.id === matched?.id) continue + for (const [i, hole] of source.holes.entries()) { + const metadata = source.holeMetadata[i] ?? { source: 'manual' as const } + if (metadata.source === 'room' || metadata.source === 'floor-opening') continue + if (matchedSibling && metadata.source === 'manual') continue + const key = JSON.stringify(Object.entries(metadata).sort(([a], [b]) => a.localeCompare(b))) + const entry = authoredHoles.get(key) ?? { metadata, polygons: [] } + // A retained cut-out is authored data; clipping it again changes ensured + // stair/elevator holes and can duplicate them on every load. + if (source.id === matched?.id) entry.polygons.push({ outer: hole, holes: [] }) + else if ( + !( + matched?.plateRole && + metadata.source !== 'manual' && + matched.holeMetadata.some( + (own) => + JSON.stringify(Object.entries(own).sort(([a], [b]) => a.localeCompare(b))) === key, + ) + ) + ) + entry.polygons.push(...intersection(hole, group.footprint)) + authoredHoles.set(key, entry) + } + } + const holeKey = (hole: SlabNode['holes'][number], metadata: SurfaceHoleMetadata) => + JSON.stringify([hole, Object.entries(metadata).sort(([a], [b]) => a.localeCompare(b))]) + const retainedHoleKeys = new Set( + plate.holes.map((hole, i) => holeKey(hole, plate.holeMetadata[i]!)), + ) + for (const { metadata, polygons } of authoredHoles.values()) { + for (const part of union(polygons)) { + const key = holeKey(part.outer, metadata) + if (retainedHoleKeys.has(key)) continue + retainedHoleKeys.add(key) + plate.holes.push(part.outer) + plate.holeMetadata.push(metadata) + } + } + if (matched) + for (const opening of openings) { + const legacyCuts = opening.legacyPlateCuts?.[matched.id] + if (!legacyCuts) continue + const metadata = { source: 'floor-opening' as const, openingId: opening.id } + for (const hole of legacyCuts) { + const key = holeKey(hole, metadata) + if (retainedHoleKeys.has(key)) continue + plate.holes.push(hole) + plate.holeMetadata.push(metadata) + retainedHoleKeys.add(key) + } + } + if (group.support === 'open') { + const context = group.members[0]!.context + const arrivals = Object.values(nodes ?? {}) + .flatMap((node) => + node.type === 'stair' && node.deckSlabId === plate.id && node.visible !== false + ? [stairArrivalOpening(node, nodes!)] + : [], + ) + .filter((ring) => ring.length >= 3) + const cover = union([...context.wallFootprints.values(), ...arrivals]) + const surface = difference(plate.polygon, union(plate.holes)) + plate.railing = exposedIntervals(surface, context, cover).map(({ start, end }) => ({ + start, + end, + })) + } + if (plate.plateRole === 'base') delete (plate as Partial).fillToTerrain + return omitUndefined(plate) + }) + const plateIds = new Set(plates.map((plate) => plate.id)) + const retired = existing.filter((slab) => !used.has(slab.id) && !plateIds.has(slab.id)) + const remap = new Map() + for (const slab of retired) { + const best = planned + .flatMap((group, index) => + slab.support === group.support ? [{ index, ...score(slab, group, index) }] : [], + ) + .filter(({ overlap, iou }) => overlap > 0 || iou > 0) + .sort((a, b) => b.overlap - a.overlap || b.iou - a.iou || a.index - b.index)[0] + remap.set(slab.id, best ? plates[best.index]!.id : undefined) + } + return { plates, retired, remap } +} + +const warnedLevels = new Set() +export function warnPlateFailure(levelId: string, ids: string[], error: unknown) { + if (warnedLevels.has(levelId)) return + warnedLevels.add(levelId) + console.warn('[floor plates] Keeping existing level construction', { levelId, ids, error }) +} diff --git a/packages/core/src/lib/floor-room-faces.ts b/packages/core/src/lib/floor-room-faces.ts new file mode 100644 index 0000000000..a63e23c0f9 --- /dev/null +++ b/packages/core/src/lib/floor-room-faces.ts @@ -0,0 +1,37 @@ +import { type ExtractedRoom, extractRooms } from './room-graph' +import type { BoundaryNode } from './room-topology-index' + +const facesByGeometry = new Map() + +export function floorRoomFaces(boundaries: BoundaryNode[]): ExtractedRoom[] { + const ordered = [...boundaries].sort((a, b) => a.id.localeCompare(b.id)) + const signature = JSON.stringify( + ordered.map((boundary) => [ + boundary.id, + boundary.type, + boundary.start, + boundary.end, + boundary.type === 'wall' + ? [boundary.curveOffset, boundary.thickness, boundary.justification] + : null, + ]), + ) + const cached = facesByGeometry.get(signature) + if (cached) return cached + const faces = extractRooms(ordered) + facesByGeometry.set(signature, faces) + if (facesByGeometry.size > 64) facesByGeometry.delete(facesByGeometry.keys().next().value!) + return faces +} + +export function roomPolygonKey( + polygon: readonly (readonly number[])[], + holes: readonly (readonly (readonly number[])[])[] = [], +): string { + const ring = (points: readonly (readonly number[])[]) => + points + .map(([x, z]) => `${Math.round(x! * 1e6)},${Math.round(z! * 1e6)}`) + .sort() + .join(';') + return [ring(polygon), ...holes.map(ring).sort()].join('|') +} diff --git a/packages/core/src/lib/floor-step-finish.test.ts b/packages/core/src/lib/floor-step-finish.test.ts new file mode 100644 index 0000000000..60545fa735 --- /dev/null +++ b/packages/core/src/lib/floor-step-finish.test.ts @@ -0,0 +1,288 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { setZoneIntent } from '../commands/structure/set-zone-intent' +import { type AnyNode, type AnyNodeId, BuildingNode, SeparatorNode, type ZoneNode } from '../schema' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { doorwayStepsFixture } from '../systems/slab/__fixtures__/doorway-steps' +import { reconcileStructureWithStableIds } from '../utils/structure-id' +import { + floorStepRole, + floorStepRoleCovers, + parseFloorStepRole, + remapFloorStepOverrideKeys, + resolveFloorStepFinish, + withFloorStepOverride, + withoutFloorStepOverrideKeys, +} from './floor-step-finish' +import { computePlateSurfacePartition, floorStepKeysOf, plateLevelContext } from './plate-surface' + +globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} + +const RED = 'library:preset-red' +const BLUE = 'library:preset-blue' +const zonesOf = (nodes: Record) => + Object.values(nodes).filter((node): node is ZoneNode => node.type === 'zone') +const zone = (nodes: Record, id: string) => nodes[id] as ZoneNode +const finishOf = (nodes: Record, owner: string, key: string) => + resolveFloorStepFinish(zone(nodes, owner), key, null, zonesOf(nodes)) +const withZone = (nodes: Record, id: string, data: Partial) => ({ + ...nodes, + [id]: { ...nodes[id], ...data } as AnyNode, +}) +/** Re-derive the floors after a floor edit, keeping the room's paint. */ +const relevel = (nodes: Record, id: string, elevation: number) => + reconcileStructureWithStableIds({ + nodes: withZone(nodes, id, { floor: { ...zone(nodes, id).floor, elevation } }), + }).nodes as Record + +describe('step roles', () => { + test('round-trip and coverage', () => { + expect(floorStepRole('zone_b')).toBe('step:zone_b') + expect(floorStepRole('zone_b', 'door_ab')).toBe('step:zone_b/door_ab') + expect(parseFloorStepRole('step:zone_b/door_ab#2')).toEqual({ + zoneId: 'zone_b', + key: 'door_ab', + step: 2, + }) + expect(parseFloorStepRole('edge:zone_b')).toBeNull() + expect(floorStepRoleCovers('step:zone_b', 'step:zone_b/door_ab')).toBe(true) + expect(floorStepRoleCovers('step:zone_b/door_ab', 'step:zone_b/door_ab#1')).toBe(true) + expect(floorStepRoleCovers('step:zone_b/door_ab', 'step:zone_b/door_bc')).toBe(false) + expect(floorStepRoleCovers('step:zone_b', 'step:zone_a/door_ab')).toBe(false) + }) +}) + +describe('override bookkeeping', () => { + const owner = { + id: 'zone_b', + parentId: 'level_row', + floorStepOverrides: [ + { key: 'door_ab', finish: RED }, + { key: 'zone_old', finish: BLUE }, + { key: 'zone_new', step: 0, finish: RED }, + ], + } + test('a deleted key goes, the rest stay', () => { + expect(withoutFloorStepOverrideKeys(owner, new Set(['door_ab']))?.floorStepOverrides).toEqual( + owner.floorStepOverrides.slice(1), + ) + expect(withoutFloorStepOverrideKeys(owner, new Set(['door_zz']))).toBeNull() + }) + test('a retired room key is renamed to its survivor; the room never keys itself', () => { + expect( + remapFloorStepOverrideKeys(owner, new Map([['zone_old', 'zone_new']]))?.floorStepOverrides, + ).toEqual([ + { key: 'door_ab', finish: RED }, + { key: 'zone_new', finish: BLUE }, + { key: 'zone_new', step: 0, finish: RED }, + ]) + expect( + remapFloorStepOverrideKeys(owner, new Map([['zone_old', 'zone_b']]))?.floorStepOverrides, + ).toEqual([owner.floorStepOverrides[0], owner.floorStepOverrides[2]]) + }) +}) + +describe('step keys', () => { + test('a raised room owns one keyed step per door, every riser piece included', () => { + const nodes = doorwayStepsFixture() + expect(floorStepKeysOf(nodes, 'level_row', 'zone_b')).toEqual(['door_ab', 'door_bc']) + expect(floorStepKeysOf(nodes, 'level_row', 'zone_a')).toEqual([]) + const context = plateLevelContext(nodes.level_row!, (id) => nodes[id]) + for (const plate of context.slabs) { + const sides = computePlateSurfacePartition(plate, context)?.sides ?? [] + for (const side of sides.filter((side) => side.role === 'riser' && side.zoneId)) + expect(['door_ab', 'door_bc']).toContain(side.stepKey!) + } + }) + + test('a step with no door is keyed by the lower room it looks at', () => { + const nodes = doorwayStepsFixture(undefined, true) + expect(floorStepKeysOf(nodes, 'level_row', 'zone_b')).toEqual(['door_ab', 'zone_c']) + }) +}) + +describe('what a step draws', () => { + test('its doorway override, else the room steps, else the room floor', () => { + let nodes = doorwayStepsFixture() + nodes = withZone(nodes, 'zone_b', { + floor: { ...zone(nodes, 'zone_b').floor, finish: 'library:oak' }, + }) + expect(finishOf(nodes, 'zone_b', 'door_ab')).toBe('library:oak') + nodes = withZone(nodes, 'zone_b', { floorStepFinish: BLUE }) + nodes = withZone(nodes, 'zone_b', { floorStepOverrides: [{ key: 'door_bc', finish: RED }] }) + expect(finishOf(nodes, 'zone_b', 'door_bc')).toBe(RED) + expect(finishOf(nodes, 'zone_b', 'door_ab')).toBe(BLUE) + // An exact step index beats the whole doorway. + nodes = withZone(nodes, 'zone_b', { + floorStepOverrides: [ + { key: 'door_bc', finish: RED }, + { key: 'door_bc', step: 1, finish: BLUE }, + ], + }) + expect(resolveFloorStepFinish(zone(nodes, 'zone_b'), 'door_bc', 1, zonesOf(nodes))).toBe(BLUE) + expect(resolveFloorStepFinish(zone(nodes, 'zone_b'), 'door_bc', 0, zonesOf(nodes))).toBe(RED) + }) + + test('a painted door step keeps its colour when the room across rises above', () => { + let nodes = doorwayStepsFixture() + nodes = withZone(nodes, 'zone_b', { floorStepOverrides: [{ key: 'door_bc', finish: RED }] }) + nodes = relevel(nodes, 'zone_c', 0.5) + // C now owns the step at door_bc; the paint is read through from B. + expect(floorStepKeysOf(nodes, 'level_row', 'zone_c')).toEqual(['door_bc']) + expect(finishOf(nodes, 'zone_c', 'door_bc')).toBe(RED) + // The step at door_ab is still B's and unpainted. + expect(finishOf(nodes, 'zone_b', 'door_ab')).toBeUndefined() + }) + + test('a painted open step keeps its colour when the room across rises above', () => { + let nodes = doorwayStepsFixture(undefined, true) + nodes = withZone(nodes, 'zone_b', { floorStepOverrides: [{ key: 'zone_c', finish: RED }] }) + nodes = relevel(nodes, 'zone_c', 0.5) + expect(floorStepKeysOf(nodes, 'level_row', 'zone_c')).toEqual(['zone_b']) + expect(finishOf(nodes, 'zone_c', 'zone_b')).toBe(RED) + }) + + test('painting or erasing a swapped step moves or clears the one doorway colour', () => { + let nodes = doorwayStepsFixture() + nodes = withZone(nodes, 'zone_b', { + floorStepOverrides: [ + { key: 'door_bc', finish: RED }, + { key: 'door_ab', finish: RED }, + ], + }) + const zones = zonesOf(nodes) + const painted = withFloorStepOverride(zone(nodes, 'zone_c'), 'door_bc', null, BLUE, zones) + expect(Object.fromEntries(painted.map((z) => [z.id, z.floorStepOverrides]))).toEqual({ + zone_b: [{ key: 'door_ab', finish: RED }], + zone_c: [{ key: 'door_bc', finish: BLUE }], + }) + const erased = withFloorStepOverride(zone(nodes, 'zone_c'), 'door_bc', null, undefined, zones) + expect(erased.map((z) => [z.id, z.floorStepOverrides])).toEqual([ + ['zone_b', [{ key: 'door_ab', finish: RED }]], + ]) + }) +}) + +describe('edits never repaint another doorway', () => { + function load(nodes: Record) { + const building = BuildingNode.parse({ id: 'building_row', children: ['level_row'] }) + useScene.setState({ + nodes: { + ...nodes, + building_row: building, + level_row: { ...nodes.level_row!, parentId: building.id } as AnyNode, + } as Record, + rootNodeIds: [building.id as AnyNodeId], + collections: {}, + materials: {}, + dirtyNodes: new Set(), + readOnly: false, + }) + useScene.temporal.getState().resume() + clearSceneHistory() + } + const now = () => useScene.getState().nodes as Record + afterEach(() => { + useScene.setState({ nodes: {}, rootNodeIds: [], dirtyNodes: new Set() }) + clearSceneHistory() + }) + + test('deleting a door drops only its own step paint, and undo brings it back', () => { + const painted = [ + { key: 'door_ab', finish: RED }, + { key: 'door_bc', finish: BLUE }, + ] + load(withZone(doorwayStepsFixture(), 'zone_b', { floorStepOverrides: painted })) + useScene.getState().deleteNode('door_ab' as AnyNodeId) + expect(zone(now(), 'zone_b').floorStepOverrides).toEqual([{ key: 'door_bc', finish: BLUE }]) + expect(finishOf(now(), 'zone_b', 'door_bc')).toBe(BLUE) + useScene.temporal.getState().undo() + expect(now().door_ab).toBeDefined() + expect(zone(now(), 'zone_b').floorStepOverrides).toEqual(painted) + useScene.temporal.getState().redo() + expect(zone(now(), 'zone_b').floorStepOverrides).toEqual([{ key: 'door_bc', finish: BLUE }]) + }) + + test('moving a door keeps its step paint', () => { + load( + withZone(doorwayStepsFixture(), 'zone_b', { + floorStepOverrides: [{ key: 'door_bc', finish: RED }], + }), + ) + useScene.getState().updateNode('door_bc' as AnyNodeId, { position: [2.6, 1, 0] }) + expect(zone(now(), 'zone_b').floorStepOverrides).toEqual([{ key: 'door_bc', finish: RED }]) + const moved = reconcileStructureWithStableIds({ nodes: now() }).nodes as Record + expect(floorStepKeysOf(moved, 'level_row', 'zone_b')).toContain('door_bc') + expect(finishOf(moved, 'zone_b', 'door_bc')).toBe(RED) + }) + + test('merging two rooms carries the retired room’s doorway paint and keys', () => { + let nodes = doorwayStepsFixture([0.3, 0.3, 0.05], true) + nodes = withZone(nodes, 'zone_b', { floorStepOverrides: [{ key: 'zone_c', finish: RED }] }) + nodes = withZone(nodes, 'zone_c', { floorStepOverrides: [{ key: 'zone_b', finish: RED }] }) + // Take the wall between A and B away: the rooms become one. + const { wall_row_ab: _wall, door_ab: _door, ...rest } = nodes + const level = rest.level_row as AnyNode & { children: string[] } + nodes = reconcileStructureWithStableIds({ + nodes: { + ...rest, + level_row: { + ...level, + children: level.children.filter((id) => id !== 'wall_row_ab'), + } as AnyNode, + }, + }).nodes as Record + const rooms = zonesOf(nodes).filter((z) => z.id !== 'zone_c') + expect(rooms).toHaveLength(1) + const survivor = rooms[0]! + // The survivor owns the open step toward C and keeps the colour painted there. + expect(floorStepKeysOf(nodes, 'level_row', survivor.id)).toEqual(['zone_c']) + expect(finishOf(nodes, survivor.id, 'zone_c')).toBe(RED) + // C's dormant paint for the retired room now names the survivor. + expect(zone(nodes, 'zone_c').floorStepOverrides).toEqual([{ key: survivor.id, finish: RED }]) + }) + + test('dividing a room gives both halves its doorway paint', () => { + let nodes = doorwayStepsFixture() + nodes = withZone(nodes, 'zone_b', { floorStepOverrides: [{ key: 'door_bc', finish: RED }] }) + const separator = SeparatorNode.parse({ + id: 'separator_split', + parentId: 'level_row', + start: [4, 1], + end: [8, 1], + }) + const level = nodes.level_row as AnyNode & { children: string[] } + nodes = reconcileStructureWithStableIds({ + nodes: { + ...nodes, + [separator.id]: separator, + level_row: { ...level, children: [...level.children, separator.id] } as AnyNode, + }, + }).nodes as Record + const halves = zonesOf(nodes).filter((z) => z.id !== 'zone_a' && z.id !== 'zone_c') + expect(halves).toHaveLength(2) + for (const half of halves) + expect(half.floorStepOverrides).toEqual([{ key: 'door_bc', finish: RED }]) + const owner = halves.find((half) => + floorStepKeysOf(nodes, 'level_row', half.id).includes('door_bc'), + )! + expect(finishOf(nodes, owner.id, 'door_bc')).toBe(RED) + }) +}) + +test('room intent sets and clears the doorway step paint', () => { + const nodes = doorwayStepsFixture() + const painted = [{ key: 'door_bc', finish: RED }] + expect( + setZoneIntent(nodes, { zoneId: 'zone_b', patch: { floorStepOverrides: painted } }).changes, + ).toEqual([{ op: 'update', id: 'zone_b', data: { floorStepOverrides: painted } }]) + expect( + setZoneIntent(withZone(nodes, 'zone_b', { floorStepOverrides: painted }), { + zoneId: 'zone_b', + patch: { floorStepOverrides: null }, + }).changes, + ).toEqual([{ op: 'update', id: 'zone_b', data: { floorStepOverrides: undefined } }]) +}) diff --git a/packages/core/src/lib/floor-step-finish.ts b/packages/core/src/lib/floor-step-finish.ts new file mode 100644 index 0000000000..d0d9a13318 --- /dev/null +++ b/packages/core/src/lib/floor-step-finish.ts @@ -0,0 +1,191 @@ +import type { ZoneNode } from '../schema' + +/** + * A room's steps — the riser faces where its floor drops to a lower one — are + * painted per doorway. Each riser is keyed by what it steps through: the door + * (or floor-anchored window) it sits under, else the lower room it looks at. + * A riser draws as `step:/`; `step:` alone is + * the room scope, every step of the room. + * + * What a step shows, highest first: + * 1. an override for its doorway (`zone.floorStepOverrides`, exact step + * index before the whole doorway) + * 2. the owning room's `floorStepFinish` + * 3. the owning room's floor finish + * + * An override belongs to its doorway, not to whichever room is higher. When a + * floor edit hands the step to the room on the other side, the override stays + * where it was painted and is read through from there, so the step keeps its + * colour; the next paint or erase of that step moves or clears it. + */ +export type FloorStepOverride = NonNullable[number] +type StepZone = Pick + +export function floorStepRole(zoneId: string, key?: string, step?: number): string { + if (!key) return `step:${zoneId}` + return step === undefined ? `step:${zoneId}/${key}` : `step:${zoneId}/${key}#${step}` +} + +export function parseFloorStepRole( + role: string, +): { zoneId: string; key: string | null; step: number | null } | null { + const match = /^step:([^/#]+)(?:\/([^/#]+)(?:#(\d+))?)?$/.exec(role) + if (!match) return null + return { + zoneId: match[1]!, + key: match[2] ?? null, + step: match[3] === undefined ? null : Number(match[3]), + } +} + +/** + * Whether painting `target` paints the step mesh drawn as `role`: the room scope + * covers every step of the room, a doorway every step index of that doorway. + */ +export function floorStepRoleCovers(target: string, role: string): boolean { + if (target === role) return true + const wide = parseFloorStepRole(target) + const mesh = parseFloorStepRole(role) + if (!(wide && mesh) || wide.zoneId !== mesh.zoneId) return false + if (!wide.key) return true + return wide.key === mesh.key && wide.step === null +} + +/** + * Every (room, key) pair that stores paint for the doorway `key` of `zone`'s + * steps: the owner itself, and whoever stored it before the owner changed — for + * a door, any other room keyed by the same door; for a step keyed by the lower + * room, that room keyed back by the owner. + */ +function doorwayHolders( + zone: Z, + key: string, + zones: readonly Z[], +): Array<{ zone: Z; key: string }> { + const siblings = zones + .filter((other) => other.id !== zone.id && other.parentId === zone.parentId) + .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + const lower = siblings.find((other) => other.id === key) + if (lower) + return [ + { zone, key }, + { zone: lower, key: zone.id }, + ] + if (zones.some((other) => other.id === key)) return [{ zone, key }] + return [{ zone, key }, ...siblings.map((other) => ({ zone: other, key }))] +} + +function pick( + overrides: readonly FloorStepOverride[] | undefined, + key: string, + step: number | null, +): FloorStepOverride | undefined { + if (!overrides?.length) return undefined + return ( + (step === null + ? undefined + : overrides.find((entry) => entry.key === key && entry.step === step)) ?? + overrides.find((entry) => entry.key === key && entry.step === undefined) + ) +} + +/** The override painting step `key` (`#step`) of `zone`, wherever it is stored. */ +export function floorStepOverrideFor( + zone: Z, + key: string, + step: number | null, + zones: readonly Z[], +): FloorStepOverride | undefined { + for (const holder of doorwayHolders(zone, key, zones)) { + const found = pick(holder.zone.floorStepOverrides, holder.key, step) + if (found) return found + } + return undefined +} + +/** What a step of `zone` keyed `key` draws; `undefined` = the plate's own top. */ +export function resolveFloorStepFinish( + zone: Pick, + key: string | null, + step: number | null, + zones: readonly StepZone[], +): string | Record | undefined { + return ( + (key ? floorStepOverrideFor(zone, key, step, zones)?.finish : undefined) ?? + zone.floorStepFinish ?? + zone.floor?.finish + ) +} + +/** + * The rooms that change when step `key` of `owner` is painted (`finish`) or + * erased (`undefined`): the doorway's paint is dropped from every holder and, + * painting, written on the owner — one colour per doorway. No step index paints + * the whole doorway, so its per-step entries go too. + */ +export function withFloorStepOverride( + owner: Z, + key: string, + step: number | null, + finish: string | undefined, + zones: readonly Z[], +): Z[] { + const changed = new Map() + for (const holder of doorwayHolders(owner, key, zones)) { + const current = holder.zone.floorStepOverrides ?? [] + const kept = current.filter( + (entry) => entry.key !== holder.key || (step !== null && entry.step !== step), + ) + if (kept.length !== current.length) + changed.set(holder.zone.id, withOverrides(holder.zone, kept)) + } + if (finish !== undefined) { + const base = changed.get(owner.id) ?? owner + changed.set( + owner.id, + withOverrides(base, [ + ...(base.floorStepOverrides ?? []), + { key, ...(step === null ? {} : { step }), finish }, + ]), + ) + } + return [...changed.values()] +} + +function withOverrides(zone: Z, overrides: FloorStepOverride[]): Z { + const next = { ...zone } + if (overrides.length) next.floorStepOverrides = overrides + else delete next.floorStepOverrides + return next +} + +/** `zone` without the overrides keyed by `keys` (deleted doors), or null when none go. */ +export function withoutFloorStepOverrideKeys( + zone: Z, + keys: ReadonlySet, +): Z | null { + const current = zone.floorStepOverrides + if (!current?.some((entry) => keys.has(entry.key))) return null + return withOverrides( + zone, + current.filter((entry) => !keys.has(entry.key)), + ) +} + +/** `zone` with override keys naming a retired room renamed to its survivor, or null. */ +export function remapFloorStepOverrideKeys( + zone: Z, + remap: ReadonlyMap, +): Z | null { + const current = zone.floorStepOverrides + if (!current?.some((entry) => remap.has(entry.key))) return null + const byKey = new Map() + for (const entry of current) { + const key = remap.get(entry.key) ?? entry.key + if (key === zone.id) continue + const id = `${key}#${entry.step ?? ''}` + // An entry already under the survivor's key was painted on that step itself. + if (!byKey.has(id) || !remap.has(entry.key)) byKey.set(id, { ...entry, key }) + } + return withOverrides(zone, [...byKey.values()]) +} diff --git a/packages/core/src/lib/level-footprints.test.ts b/packages/core/src/lib/level-footprints.test.ts new file mode 100644 index 0000000000..23404eccbd --- /dev/null +++ b/packages/core/src/lib/level-footprints.test.ts @@ -0,0 +1,620 @@ +import { describe, expect, spyOn, test } from 'bun:test' +import clipping from 'polygon-clipping' +import { LevelNode, SeparatorNode, SlabNode, WallNode } from '../schema' +import { computeWallSlabSupport } from '../systems/slab/slab-support' +import { getWallCurveFrameAt } from '../systems/wall/wall-curve' +import { exposedIntervals, plateFootprint, roomClearPolygon } from './level-footprints' +import { area, containsPoint, difference, intersection, type Ring, union } from './polygon-boolean' +import type { BoundaryNode, LevelTopology } from './room-topology-index' +import { createRoomTopologyIndex, detectSpacesForLevel } from './space-detection' + +const levelId = 'level_topology' as const +function wall( + id: string, + start: [number, number], + end: [number, number], + extra: Partial = {}, +) { + return WallNode.parse({ + id: `wall_${id}`, + parentId: levelId, + start, + end, + thickness: 0.2, + ...extra, + }) +} +function enclosure(polygon: Ring): WallNode[] { + return polygon.map((p, i) => wall(`${i}`, p, polygon[(i + 1) % polygon.length]!)) +} +function rectangle() { + return enclosure([ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ]) +} +function scene(boundaries: BoundaryNode[]) { + const level = LevelNode.parse({ id: levelId, children: boundaries.map((node) => node.id) }) + return Object.fromEntries([level, ...boundaries].map((node) => [node.id, node])) +} +function topology(boundaries: BoundaryNode[]) { + const index = createRoomTopologyIndex() + index.rebuild(scene(boundaries)) + return { index, level: index.getLevelTopology(levelId)! } +} +function assertTiling(level: LevelTopology, boundaries: BoundaryNode[]) { + const all = [...level.rooms.flatMap((room) => room.spans), ...level.exteriorSpans] + for (const boundary of boundaries) { + for (const face of ['a', 'b'] as const) { + const spans = all + .filter((span) => span.boundaryId === boundary.id && span.face === face) + .sort((a, b) => a.t0 - b.t0) + expect(spans[0]!.t0).toBe(0) + expect(spans.at(-1)!.t1).toBe(1) + spans.forEach((span, i) => { + expect(span.t1).toBeGreaterThan(span.t0) + if (i) expect(span.t0).toBeCloseTo(spans[i - 1]!.t1, 12) + }) + } + } + for (const room of level.rooms) { + const perimeter = [room.polygon, ...room.holes].reduce( + (total, ring) => + total + + ring.reduce((sum, p, i) => { + const q = ring[(i + 1) % ring.length]! + return sum + Math.hypot(q[0] - p[0], q[1] - p[1]) + }, 0), + 0, + ) + const spanLength = room.spans.reduce((sum, span) => { + const boundary = boundaries.find((node) => node.id === span.boundaryId)! + return ( + sum + + (span.t1 - span.t0) * + Math.hypot(boundary.end[0] - boundary.start[0], boundary.end[1] - boundary.start[1]) + ) + }, 0) + expect(spanLength).toBeCloseTo(perimeter, 6) + } +} + +const cases: Array<{ name: string; boundaries: () => BoundaryNode[]; rooms: number }> = [ + { name: '4×3 room with centred 0.2 m walls', boundaries: rectangle, rooms: 1 }, + { + name: '4×3 room with two b-justified walls', + boundaries: () => + rectangle().map((node, i) => (i < 2 ? { ...node, justification: 'b' as const } : node)), + rooms: 1, + }, + { + name: 'two rooms sharing a wall', + boundaries: () => [...rectangle(), wall('shared', [2, 0], [2, 3])], + rooms: 2, + }, + { + name: 'L-shaped room with a dangling T-stem', + boundaries: () => [ + ...enclosure([ + [0, 0], + [4, 0], + [4, 2], + [2, 2], + [2, 3], + [0, 3], + ]), + wall('stem', [1, 0], [1, -2]), + wall('free', [6, 0], [6, 2]), + ], + rooms: 1, + }, + { + name: 'room split by a separator', + boundaries: () => [ + ...rectangle(), + SeparatorNode.parse({ id: 'separator_split', parentId: levelId, start: [2, 0], end: [2, 3] }), + ], + rooms: 2, + }, +] + +describe('level footprint agreement', () => { + test.each(cases)('$name', ({ boundaries: build, rooms: count }) => { + const boundaries = build() + const { index, level } = topology(boundaries) + expect(level.rooms).toHaveLength(count) + const plate = plateFootprint(level.rooms) + expect(plate).toHaveLength(1) + expect(plateFootprint([...level.rooms].reverse())).toBe(plate) + const slab = SlabNode.parse({ + polygon: plate[0]!.outer, + holes: plate[0]!.holes, + elevation: 0.2, + }) + const walls = boundaries.filter((node): node is WallNode => node.type === 'wall') + const boundaryIds = new Set( + level.rooms.flatMap((room) => + room.spans.filter((span) => span.kind === 'wall').map((span) => span.boundaryId), + ), + ) + for (const id of boundaryIds) { + const footprint = level.rooms[0]!.context.wallFootprints.get(id)! + expect(area(difference(footprint, plate))).toBeLessThan(1e-6) + const support = computeWallSlabSupport(walls.find((node) => node.id === id)!, [slab], walls) + expect(support.electedSlabId).toBe(slab.id) + const coverage = support.baseSegments + .filter((segment) => segment.elevation === slab.elevation) + .reduce((sum, segment) => sum + segment.end - segment.start, 0) + expect(coverage).toBeCloseTo(1, 6) + } + for (const room of level.rooms) { + const footprints = union( + room.spans + .filter((span) => span.kind === 'wall') + .map((span) => room.context.wallFootprints.get(span.boundaryId)!), + ) + const face = { outer: room.polygon, holes: room.holes } + const expected = area(union([face])) - area(intersection(face, footprints)) + expect(Math.abs(area(roomClearPolygon(room)) - expected)).toBeLessThan(1e-6) + expect(roomClearPolygon(room)).toBe(roomClearPolygon(room)) + for (const span of room.spans) { + expect( + index.roomForWallHit(levelId, span.boundaryId, span.face, (span.t0 + span.t1) / 2)?.id, + ).toBe(room.id) + } + } + assertTiling(level, boundaries) + if (boundaryIds.has('wall_shared')) { + expect(index.roomForWallHit(levelId, 'wall_shared', 'a', 0.5)).toBe( + index.roomAtPoint(levelId, [1, 1]), + ) + expect(index.roomForWallHit(levelId, 'wall_shared', 'b', 0.5)).toBe( + index.roomAtPoint(levelId, [3, 1]), + ) + expect(index.spansForWall(levelId, 'wall_0').map(({ t0, t1 }) => [t0, t1])).toEqual([ + [0, 0.5], + [0.5, 1], + ]) + } + expect(boundaryIds.has('wall_stem')).toBe(false) + expect(boundaryIds.has('wall_free')).toBe(false) + if (boundaries.some((node) => node.id === 'wall_stem')) { + expect( + area( + intersection(plate, [ + [0.9, -1], + [1.1, -1], + [1.1, -0.5], + [0.9, -0.5], + ]), + ), + ).toBe(0) + } + expect(index.roomAtPoint(levelId, [20, 20])).toBeNull() + expect(index.roomForWallHit(levelId, 'wall_0', 'b', 0.5)).toBeNull() + }) + + test('exposed intervals split outer edges at covered portions, including collinear rims', () => { + const plate = union([ + [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ], + ]) + const walls = [wall('cover', [1, 0.1], [3, 0.1])] + const bottom = exposedIntervals(plate, walls).filter((interval) => interval.edgeIndex === 0) + expect(bottom).toHaveLength(2) + expect(bottom[0]!.t0).toBe(0) + expect(bottom[0]!.t1).toBeCloseTo(0.25, 12) + expect(bottom[1]!.t0).toBeCloseTo(0.75, 12) + expect(bottom[1]!.t1).toBe(1) + expect(exposedIntervals(plate, [])).toHaveLength(4) + expect(exposedIntervals([], walls)).toEqual([]) + const closed = topology(rectangle()).level + expect(exposedIntervals(plateFootprint(closed.rooms), rectangle())).toEqual([]) + }) + + test('separator delta splits and merges the graph without wall classification or miter participation', () => { + const walls = rectangle() + const separator = SeparatorNode.parse({ parentId: levelId, start: [2, 0], end: [2, 3] }) + const before = scene(walls), + after = scene([...walls, separator]) + const { index, level: previous } = topology(walls) + const delta = index.applyWallDelta(levelId, new Set([separator.id]), before, after) + expect(delta.strategy).toBe('indexed') + expect(delta.beforeRooms).toHaveLength(1) + expect(delta.currentRooms).toHaveLength(2) + const next = index.getLevelTopology(levelId)! + expect(next.revision).toBeGreaterThan(previous.revision) + expect(plateFootprint(next.rooms)).toEqual(plateFootprint(previous.rooms)) + expect(next.rooms[0]!.context.wallFootprints).toEqual(previous.rooms[0]!.context.wallFootprints) + expect( + detectSpacesForLevel(levelId, [...walls, separator]).wallUpdates.map( + (update) => update.wallId, + ), + ).not.toContain(separator.id) + index.applyWallDelta(levelId, new Set([separator.id]), after, before) + expect(index.getLevelTopology(levelId)!.rooms).toHaveLength(1) + }) + + test('thickness changes invalidate footprints and keep earlier revision snapshots intact', () => { + const walls = rectangle() + const { index, level: previous } = topology(walls) + const oldPlate = plateFootprint(previous.rooms) + const changed = walls.map((node) => + node.id === walls[0]!.id ? { ...node, thickness: 0.6 } : node, + ) + index.applyWallDelta(levelId, new Set([walls[0]!.id]), scene(walls), scene(changed)) + const next = index.getLevelTopology(levelId)! + expect(area(plateFootprint(next.rooms))).toBeGreaterThan(area(oldPlate)) + expect(plateFootprint(previous.rooms)).toBe(oldPlate) + expect(() => plateFootprint([previous.rooms[0]!, next.rooms[0]!])).toThrow() + }) + + test('one wall face can be exterior on only part of its stored reference line', () => { + const boundaries = [ + wall('long', [0, 0], [8, 0]), + wall('right', [4, 0], [4, 3]), + wall('top', [4, 3], [0, 3]), + wall('left', [0, 3], [0, 0]), + ] + const { index, level } = topology(boundaries) + expect(index.spansForWall(levelId, 'wall_long')).toMatchObject([{ face: 'a', t0: 0, t1: 0.5 }]) + expect(level.exteriorSpans.filter((span) => span.boundaryId === 'wall_long')).toEqual([ + { roomId: null, boundaryId: 'wall_long', kind: 'wall', face: 'a', t0: 0.5, t1: 1 }, + { roomId: null, boundaryId: 'wall_long', kind: 'wall', face: 'b', t0: 0, t1: 0.5 }, + { roomId: null, boundaryId: 'wall_long', kind: 'wall', face: 'b', t0: 0.5, t1: 1 }, + ]) + expect(index.roomForWallHit(levelId, 'wall_long', 'a', 0.25)).toBe(level.rooms[0]!) + expect(index.roomForWallHit(levelId, 'wall_long', 'a', 0.5)).toBeNull() + expect(index.roomForWallHit(levelId, 'wall_long', 'a', -1)).toBeNull() + assertTiling(level, boundaries) + }) + + test('separator movement uses the indexed component and agrees with a full rebuild', () => { + const separator = SeparatorNode.parse({ parentId: levelId, start: [2, 0], end: [2, 3] }) + const remote = rectangle().map((node) => ({ + ...node, + id: `${node.id}_remote` as WallNode['id'], + start: [node.start[0] + 20, node.start[1]] as [number, number], + end: [node.end[0] + 20, node.end[1]] as [number, number], + })) + const before = [...rectangle(), ...remote, separator] + const after = before.map((node) => + node.id === separator.id + ? { ...separator, start: [1, 0] as [number, number], end: [1, 3] as [number, number] } + : node, + ) + const { index } = topology(before) + const delta = index.applyWallDelta( + levelId, + new Set([separator.id]), + scene(before), + scene(after), + ) + expect(delta.examinedWallIds).not.toContain(remote[0]!.id) + expect(delta.currentRooms).toHaveLength(2) + expect( + index + .getLevelTopology(levelId)! + .rooms.map(({ id, polygon, spans }) => ({ id, polygon, spans })), + ).toEqual(topology(after).level.rooms.map(({ id, polygon, spans }) => ({ id, polygon, spans }))) + expect(index.roomForWallHit(levelId, 'wall_0', 'a', 0.25)).toBe( + index.roomAtPoint(levelId, [3, 1]), + ) + expect(index.roomForWallHit(levelId, 'wall_0', 'a', 1)).toBe(index.roomAtPoint(levelId, [3, 1])) + }) + + test('separator-only enclosures contribute faces and no physical footprints', () => { + const boundaries = rectangle().map(({ start, end }) => + SeparatorNode.parse({ parentId: levelId, start, end }), + ) + const { level } = topology(boundaries) + expect(level.rooms).toHaveLength(1) + expect(level.rooms[0]!.context.wallFootprints.size).toBe(0) + expect(area(plateFootprint(level.rooms))).toBe(12) + expect(area(roomClearPolygon(level.rooms[0]!))).toBe(12) + assertTiling(level, boundaries) + }) + + test('curved wall spans use stored chord parameters and stored direction', () => { + const walls = rectangle() + walls[0] = { ...walls[0]!, curveOffset: 0.5 } + const { index, level } = topology(walls) + const span = index.spansForWall(levelId, walls[0]!.id)[0]! + expect(span).toMatchObject({ face: 'a', t0: 0, t1: 1 }) + const point = getWallCurveFrameAt(walls[0]!, 0.25).point + const chordT = point.x / 4 + expect(index.roomForWallHit(levelId, walls[0]!.id, 'a', chordT)?.id).toBe(level.rooms[0]!.id) + const reverse = walls.map((node, i) => + i === 0 + ? { ...node, start: node.end, end: node.start, curveOffset: -node.curveOffset! } + : node, + ) + expect(topology(reverse).index.spansForWall(levelId, walls[0]!.id)[0]).toMatchObject({ + face: 'b', + t0: 0, + t1: 1, + }) + }) +}) + +function nestedWalls() { + const outer = enclosure([ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + ]) + const inner = enclosure([ + [3, 3], + [7, 3], + [7, 7], + [3, 7], + ]).map((node) => ({ ...node, id: `${node.id}_inner` as WallNode['id'] })) + return { outer, inner, walls: [...outer, ...inner] } +} + +describe('nested reference faces', () => { + test('10×10 outer and 4×4 inner have disjoint faces, holes, clear polygons and two-sided spans', () => { + const { walls, inner: innerWalls } = nestedWalls() + const { index, level } = topology(walls) + const outer = index.roomAtPoint(levelId, [1, 1])! + const inner = index.roomAtPoint(levelId, [5, 5])! + expect(level.rooms).toHaveLength(2) + expect(inner.id).not.toBe(outer.id) + expect(outer.holes).toHaveLength(1) + expect(inner.holes).toHaveLength(0) + const outerFace = { outer: outer.polygon, holes: outer.holes } + const innerFace = { outer: inner.polygon, holes: inner.holes } + expect(area([outerFace])).toBe(84) + expect(area([innerFace])).toBe(16) + expect(intersection(outerFace, innerFace)).toEqual([]) + expect(area(roomClearPolygon(outer))).toBeCloseTo(78.4, 6) + expect(area(roomClearPolygon(inner))).toBeCloseTo(14.44, 6) + const outerPlate = plateFootprint([outer]) + expect(outerPlate[0]!.holes).toHaveLength(1) + expect(containsPoint(outerPlate, [5, 5])).toBe(false) + expect(area(outerPlate)).toBeCloseTo(89.6, 6) + const filled = plateFootprint([outer, inner]) + expect(filled[0]!.holes).toHaveLength(0) + expect(containsPoint(filled, [5, 5])).toBe(true) + expect(area(filled)).toBeCloseTo(104.04, 6) + for (const boundary of innerWalls) { + expect(index.spansForWall(levelId, boundary.id)).toHaveLength(2) + expect(index.roomForWallHit(levelId, boundary.id, 'a', 0.5)).toBe(inner) + expect(index.roomForWallHit(levelId, boundary.id, 'b', 0.5)).toBe(outer) + expect(level.exteriorSpans.some((span) => span.boundaryId === boundary.id)).toBe(false) + expect(difference(outer.context.wallFootprints.get(boundary.id)!, outerPlate)).toEqual([]) + } + assertTiling(level, walls) + const legacy = detectSpacesForLevel(levelId, walls) + expect( + legacy.spaces.map((space) => area([{ outer: space.polygon, holes: space.holes ?? [] }])), + ).toEqual([84, 16]) + expect(legacy.spaces.map((space) => space.wallIds.length)).toEqual([8, 4]) + }) + + test('a partitioned inner enclosure has one surrounding hole and no outer spans on its divider', () => { + const { walls } = nestedWalls() + const divider = wall('inner_divider', [5, 3], [5, 7]) + const { index, level } = topology([...walls, divider]) + const outer = index.roomAtPoint(levelId, [1, 1])! + expect(level.rooms).toHaveLength(3) + expect(outer.holes).toHaveLength(1) + expect(area([{ outer: outer.polygon, holes: outer.holes }])).toBe(84) + expect(outer.spans.some((span) => span.boundaryId === divider.id)).toBe(false) + expect(index.spansForWall(levelId, divider.id)).toHaveLength(2) + expect(plateFootprint(level.rooms)[0]!.holes).toHaveLength(0) + assertTiling(level, [...walls, divider]) + }) + + test('each nested boundary belongs to its smallest containing face', () => { + const { walls } = nestedWalls() + const centre = enclosure([ + [4, 4], + [6, 4], + [6, 6], + [4, 6], + ]).map((node) => ({ ...node, id: `${node.id}_centre` as WallNode['id'] })) + const { index, level } = topology([...walls, ...centre]) + expect(level.rooms).toHaveLength(3) + for (const [point, expected] of [ + [[1, 1], 84], + [[3.5, 3.5], 12], + [[5, 5], 4], + ] as Array<[[number, number], number]>) { + const room = index.roomAtPoint(levelId, point)! + expect(area([{ outer: room.polygon, holes: room.holes }])).toBe(expected) + } + assertTiling(level, [...walls, ...centre]) + }) + + test('nested creation, opening, restoration and movement agree with a full rebuild', () => { + const { outer, inner, walls } = nestedWalls() + const { index, level: original } = topology(outer) + let before: BoundaryNode[] = outer + const opened = walls.filter((node) => node.id !== inner[0]!.id) + const moved = [ + ...outer, + ...inner.map((node) => ({ + ...node, + start: [node.start[0] + 15, node.start[1]] as [number, number], + end: [node.end[0] + 15, node.end[1]] as [number, number], + })), + ] + for (const after of [walls, opened, walls, moved, walls, inner]) { + const ids = new Set( + [...before, ...after] + .map((node) => node.id) + .filter( + (id) => before.find((node) => node.id === id) !== after.find((node) => node.id === id), + ), + ) + index.applyWallDelta(levelId, ids, scene(before), scene(after)) + const snapshot = (value: LevelTopology) => + value.rooms.map(({ id, polygon, holes, spans }) => ({ id, polygon, holes, spans })) + expect(snapshot(index.getLevelTopology(levelId)!)).toEqual(snapshot(topology(after).level)) + before = after + } + expect(original.rooms[0]!.holes).toEqual([]) + }) +}) + +describe('curved boundary junctions and exposure caching', () => { + test.each([ + 'separator', + 'wall', + ] as const)('%s endpoint splits a curved wall at mid-span', (kind) => { + for (const arcT of [0.5, 0.37]) { + const walls = rectangle() + walls[0] = { ...walls[0]!, curveOffset: 0.5 } + const point = getWallCurveFrameAt(walls[0]!, arcT).point + const start: [number, number] = [point.x, point.y] + const end: [number, number] = [point.x, 3] + const divider = + kind === 'separator' + ? SeparatorNode.parse({ parentId: levelId, start, end }) + : wall('curve_divider', start, end) + const { index, level } = topology([...walls, divider]) + expect(level.rooms).toHaveLength(2) + const spans = index.spansForWall(levelId, walls[0]!.id) + const chordT = point.x / 4 + expect(spans).toHaveLength(2) + expect(spans[0]).toMatchObject({ face: 'a', t0: 0 }) + expect(spans[0]!.t1).toBeCloseTo(chordT, 12) + expect(spans[1]!.t0).toBeCloseTo(chordT, 12) + expect(spans[1]).toMatchObject({ face: 'a', t1: 1 }) + const dividerSpans = index.spansForWall(levelId, divider.id) + expect(dividerSpans).toHaveLength(2) + expect(new Set(dividerSpans.map((span) => span.roomId)).size).toBe(2) + expect(index.roomForWallHit(levelId, divider.id, 'a', 0.5)).toBe( + index.roomAtPoint(levelId, [1, 2]), + ) + expect(index.roomForWallHit(levelId, divider.id, 'b', 0.5)).toBe( + index.roomAtPoint(levelId, [3, 2]), + ) + const before = topology(walls).index + before.applyWallDelta( + levelId, + new Set([divider.id]), + scene(walls), + scene([...walls, divider]), + ) + expect( + before.getLevelTopology(levelId)!.rooms.map(({ holes, spans }) => ({ holes, spans })), + ).toEqual(level.rooms.map(({ holes, spans }) => ({ holes, spans }))) + } + }) + + test('exposure preparation is reused across plates and invalidated by topology revision', () => { + const walls = rectangle() + const { index, level } = topology(walls) + const plate = plateFootprint(level.rooms) + const otherPlate = union([ + [ + [0, 0], + [5, 0], + [5, 4], + [0, 4], + ], + ]) + const changed = walls.map((node, i) => (i === 0 ? { ...node, thickness: 0.6 } : node)) + index.applyWallDelta(levelId, new Set([walls[0]!.id]), scene(walls), scene(changed)) + const next = index.getLevelTopology(levelId)! + const nextPlate = plateFootprint(next.rooms) + const clip = spyOn(clipping, 'union') + try { + expect(exposedIntervals(plate, walls)).toEqual([]) + const calls = clip.mock.calls.length + expect(calls).toBeGreaterThan(0) + expect(exposedIntervals(plate, [...walls])).toEqual([]) + expect(exposedIntervals(otherPlate, level.rooms[0]!.context).length).toBeGreaterThan(0) + expect(clip.mock.calls.length).toBe(calls) + expect(exposedIntervals(nextPlate, next.rooms[0]!.context)).toEqual([]) + expect(clip.mock.calls.length).toBeGreaterThan(calls) + } finally { + clip.mockRestore() + } + }) + + test('wall-array exposure cache follows geometry changes', () => { + const plate = union([ + [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ], + ]) + const walls = [wall('cover_cache', [1, 0.1], [3, 0.1])] + const first = exposedIntervals(plate, walls) + expect(exposedIntervals(plate, walls)).toEqual(first) + walls[0] = { ...walls[0]!, start: [0, 0.1], end: [4, 0.1] } + expect(exposedIntervals(plate, walls).some((span) => span.edgeIndex === 0)).toBe(false) + }) +}) + +test('plate boundary wall coverage stops at the group spans while retaining corner miters', () => { + const boundaries = [ + ...enclosure([ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ]), + wall('divider_span', [4, 0], [4, 4]), + ] + const { level } = topology(boundaries) + const left = level.rooms.find((room) => + containsPoint([{ outer: room.polygon, holes: room.holes }], [2, 2]), + )! + const plate = plateFootprint([left]) + expect(containsPoint(plate, [-0.09, -0.09])).toBe(true) + expect(containsPoint(plate, [4.09, 2])).toBe(true) + expect(containsPoint(plate, [6, 0])).toBe(false) + expect(containsPoint(plate, [6, 4])).toBe(false) + expect(Math.max(...plate.flatMap((part) => part.outer.map(([x]) => x)))).toBeCloseTo(4.1) +}) + +test('near-terminal spans retain the stored miter instead of a perpendicular cut', () => { + const boundaries = enclosure([ + [0, 0], + [4, 0], + [3, 3], + [0, 3], + ]) + const { level } = topology(boundaries) + const original = level.rooms[0]! + const room = { + ...original, + id: `${original.id}-snapped`, + spans: original.spans.map((span) => ({ + ...span, + t0: span.t0 === 0 ? 0.001 : span.t0, + t1: span.t1 === 1 ? 0.999 : span.t1, + })), + } + const plate = plateFootprint([room]) + for (const footprint of original.context.wallFootprints.values()) + expect(area(difference(footprint, plate))).toBeLessThan(1e-6) +}) + +test('a T-stem snapped into its host keeps support to the host near face', () => { + const boundaries = [ + wall('host_near', [-2, 0], [4, 0], { thickness: 0.4 }), + wall('right_near', [4, 0], [4, 3]), + wall('top_near', [4, 3], [0, 3]), + wall('stem_near', [0, 3], [0, 0.05]), + ] + const { level } = topology(boundaries) + expect(level.rooms).toHaveLength(1) + const plate = plateFootprint(level.rooms) + expect(containsPoint(plate, [0.09, 0.2])).toBe(true) + expect(containsPoint(plate, [-0.09, 0.2])).toBe(true) + expect(containsPoint(plate, [-1, 0])).toBe(false) +}) diff --git a/packages/core/src/lib/level-footprints.ts b/packages/core/src/lib/level-footprints.ts new file mode 100644 index 0000000000..d5dfaa665c --- /dev/null +++ b/packages/core/src/lib/level-footprints.ts @@ -0,0 +1,474 @@ +import type { WallNode } from '../schema' +import { getWallSurfacePolygon, isCurvedWall } from '../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { getWallFaceLine } from '../systems/wall/wall-frame' +import { getWallMiterBoundaryPoints, type WallMiterData } from '../systems/wall/wall-mitering' +import { + area, + containsPoint, + difference, + type MultiPolygon, + type Ring, + union, +} from './polygon-boolean' +import { WALL_JUNCTION_TOLERANCE } from './room-graph' +import type { LevelFootprintContext, TopologyRoom } from './room-topology-index' + +const sharedPlateCache = new Map() +const clearCache = new WeakMap() +const plateCache = new WeakMap>() +const plateContexts = new WeakMap() +const miterCache = new WeakMap() + +type WallFootprint = { id: string; polygon: Ring; t0: number; t1: number } + +function clipWallSpan(polygon: Ring, wall: WallNode, t0: number, t1: number): Ring { + let result = polygon + const dx = wall.end[0] - wall.start[0], + dz = wall.end[1] - wall.start[1] + const length = Math.hypot(dx, dz) + const tangent = { x: dx / length, y: dz / length } + for (const [t, sign] of [ + [t0, 1], + [t1, -1], + ]) { + // Spans use chord parameters, and topology can snap a junction up to 8 cm + // from an endpoint. Keep the real miter at those terminal spans. + if ( + (sign === 1 && t! * length <= WALL_JUNCTION_TOLERANCE) || + (sign === -1 && (1 - t!) * length <= WALL_JUNCTION_TOLERANCE) + ) + continue + const point = { x: wall.start[0] + dx * t!, y: wall.start[1] + dz * t! } + const distance = ([x, z]: [number, number]) => + sign! * ((x - point.x) * tangent.x + (z - point.y) * tangent.y) + const clipped: Ring = [] + for (const [i, end] of result.entries()) { + const start = result[(i + result.length - 1) % result.length]! + const a = distance(start), + b = distance(end) + if (a >= 0 !== b >= 0) { + const u = a / (a - b) + clipped.push([start[0] + u * (end[0] - start[0]), start[1] + u * (end[1] - start[1])]) + } + if (b >= 0) clipped.push(end) + } + result = clipped + } + return result +} + +function boundaryFootprints(rooms: readonly TopologyRoom[]): WallFootprint[] { + const context = rooms[0]?.context + if (!context) return [] + let miters = miterCache.get(context) + if (!miters) { + miters = calculateLevelMiters([...context.walls.values()]) + miterCache.set(context, miters) + } + const intervals = new Map>() + for (const room of rooms) + for (const span of room.spans) { + if (span.kind !== 'wall') continue + const list = intervals.get(span.boundaryId) ?? [] + list.push(span) + intervals.set(span.boundaryId, list) + } + return [...intervals].flatMap(([id, spans]) => { + const wall = context?.walls.get(id), + polygon = context?.wallFootprints.get(id) + if (!(wall && polygon)) return [] + const merged: Array<{ t0: number; t1: number }> = [] + for (const span of spans.sort((a, b) => a.t0 - b.t0)) { + const last = merged.at(-1) + if (last && span.t0 <= last.t1 + 1e-8) last.t1 = Math.max(last.t1, span.t1) + else merged.push({ t0: span.t0, t1: span.t1 }) + } + const boundary = getWallMiterBoundaryPoints(wall, miters) + const dx = wall.end[0] - wall.start[0], + dz = wall.end[1] - wall.start[1] + const lengthSq = dx * dx + dz * dz + const segments = isCurvedWall(wall) ? 24 : 1 + const surface = boundary ? getWallSurfacePolygon(wall, segments, boundary) : [] + const lines = [surface.slice(0, segments + 1), surface.slice(segments + 1).reverse()] + const faceParameters = (t: number) => + boundary + ? lines.map((line) => { + const index = Math.min(Math.floor(t * segments), segments - 1) + const fraction = t * segments - index + const start = line[index]!, + end = line[index + 1]! + return ( + ((start.x + (end.x - start.x) * fraction - wall.start[0]) * dx + + (start.y + (end.y - start.y) * fraction - wall.start[1]) * dz) / + lengthSq + ) + }) + : [t] + return merged.map(({ t0, t1 }) => { + // Mitered face endpoints can lie beyond the reference segment. Retain the + // owned face interval as well as its perpendicular reference-line cut. + const stations = [ + t0, + t1, + ...Array.from({ length: segments + 1 }, (_, i) => i / segments).filter( + (t) => t > t0 && t < t1, + ), + ] + const parameters = stations.flatMap(faceParameters) + const from = Math.min(t0, ...parameters) + const to = Math.max(t1, ...parameters) + return { id, t0: from, t1: to, polygon: clipWallSpan(polygon, wall, from, to) } + }) + }) +} + +const coverageCache = new WeakMap>() +function coversFootprint(plate: MultiPolygon, footprint: Ring) { + const cache = coverageCache.get(plate) ?? new WeakMap() + const cached = cache.get(footprint) + if (cached !== undefined) return cached + try { + const covered = area(difference(footprint, plate, { throwOnError: true })) < 1e-6 + cache.set(footprint, covered) + coverageCache.set(plate, cache) + return covered + } catch { + return false + } +} + +function rawWallRectangle(wall: WallNode): Ring { + const a = getWallFaceLine(wall, 'a') + const b = getWallFaceLine(wall, 'b') + const dx = wall.end[0] - wall.start[0] + const dz = wall.end[1] - wall.start[1] + const length = Math.hypot(dx, dz) + const tx = dx / length + const tz = dz / length + // Two clipping-grid steps keep re-quantized intersections inside the fallback. + const padding = 0.0002 + return [ + [a.start.x + padding * (-tx - tz), a.start.y + padding * (-tz + tx)], + [b.start.x + padding * (-tx + tz), b.start.y + padding * (-tz - tx)], + [b.end.x + padding * (tx + tz), b.end.y + padding * (tz - tx)], + [a.end.x + padding * (tx - tz), a.end.y + padding * (tz + tx)], + ] +} + +function recoverWallFootprint( + plate: MultiPolygon, + footprint: WallFootprint, + context: LevelFootprintContext, +): MultiPolygon { + const wall = context.walls.get(footprint.id) + const diagnostic = { levelId: wall?.parentId, wallId: footprint.id } + const cleaned = union([footprint.polygon]) + if (cleaned.length) { + const combined = union([plate, cleaned]) + if (combined.length && coversFootprint(combined, footprint.polygon)) return combined + } + if (wall) { + const combined = union([ + plate, + clipWallSpan(rawWallRectangle(wall), wall, footprint.t0, footprint.t1), + ]) + if (combined.length && coversFootprint(combined, footprint.polygon)) return combined + if (combined.length && cleaned.length) { + const joined = union([combined, cleaned]) + if (joined.length && coversFootprint(joined, footprint.polygon)) return joined + } + } + const padded = union( + [-0.0002, 0, 0.0002].flatMap((dx) => + [-0.0002, 0, 0.0002].map((dz) => + footprint.polygon.map(([x, z]): [number, number] => [x + dx, z + dz]), + ), + ), + ) + const combined = union([plate, padded]) + if (combined.length && coversFootprint(combined, footprint.polygon)) return combined + throw new Error(`Cannot cover boundary wall ${diagnostic.wallId} on level ${diagnostic.levelId}`) +} + +export function roomWallFootprints(rooms: readonly TopologyRoom[]): MultiPolygon { + return union(boundaryFootprints(rooms).map(({ polygon }) => polygon)) +} + +export function roomClearPolygon(room: TopologyRoom): MultiPolygon { + const cached = clearCache.get(room) + if (cached) return cached + const result = difference( + { outer: room.polygon, holes: room.holes }, + union(boundaryFootprints([room]).map(({ polygon }) => polygon)), + ) + clearCache.set(room, result) + return result +} + +/** Rooms must belong to the same immutable level topology revision. */ +export function plateFootprint(rooms: readonly TopologyRoom[]): MultiPolygon { + const context = rooms[0]?.context + if (!context) return [] + if (rooms.some((room) => room.context !== context)) + throw new Error('Plate rooms must share a level topology revision') + const key = JSON.stringify([...new Set(rooms.map((room) => room.id))].sort()) + const cache = plateCache.get(context) ?? new Map() + const cached = cache.get(key) + if (cached) return cached + const signature = JSON.stringify([ + rooms + .map(({ id, polygon, holes, spans }) => [id, polygon, holes, spans]) + .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), + [...context.wallFootprints], + [...context.walls.values()].map(({ id, start, end, thickness, justification, curveOffset }) => [ + id, + start, + end, + thickness, + justification, + curveOffset, + ]), + ]) + const shared = sharedPlateCache.get(signature) + if (shared) { + cache.set(key, shared) + plateCache.set(context, cache) + plateContexts.set(shared, context) + return shared + } + // Only half-edges in closed faces contribute: dangling T-stems are not room boundaries. + const faces = rooms.map((room) => ({ outer: room.polygon, holes: room.holes })) + const footprints = boundaryFootprints(rooms) + let result = union([...faces, ...footprints.map(({ polygon }) => polygon)]) + if (!result.length) { + // A combined sweep can fail even when both sets union separately. Preserve + // the room surface while isolating additions that the clipper cannot handle. + result = union(faces) + if (!result.length) { + result = faces.flatMap((face) => { + const cleaned = union([face]) + return cleaned.length ? cleaned : [face] + }) + } + for (const footprint of footprints) { + const combined = union([result, footprint.polygon]) + result = combined.length ? combined : recoverWallFootprint(result, footprint, context) + } + } + for (const footprint of footprints) { + if (!coversFootprint(result, footprint.polygon)) + result = recoverWallFootprint(result, footprint, context) + } + if (result.length > 1) { + const rectangles = footprints.flatMap(({ id, t0, t1 }) => { + const wall = context.walls.get(id) + return wall && !wall.curveOffset ? [clipWallSpan(rawWallRectangle(wall), wall, t0, t1)] : [] + }) + const joined = union([result, ...rectangles]) + if (joined.length) result = joined + } + // Quantization in a later union can reopen a sliver at an earlier wall. + for (let pass = 0; pass < 3; pass++) { + const missing = footprints.filter((footprint) => !coversFootprint(result, footprint.polygon)) + if (!missing.length) break + for (const footprint of missing) result = recoverWallFootprint(result, footprint, context) + } + if (footprints.some((footprint) => !coversFootprint(result, footprint.polygon))) { + // Recover all seams together: repairing one wall at a time can repeatedly + // reopen the preceding wall's intersection on the clipping grid. + const padded = footprints.flatMap(({ polygon }) => + [-0.0002, 0, 0.0002].flatMap((dx) => + [-0.0002, 0, 0.0002].map((dz) => + polygon.map(([x, z]): [number, number] => [x + dx, z + dz]), + ), + ), + ) + const covered = union([result, ...padded]) + if (covered.length) result = covered + } + // Later unions re-quantize earlier intersections; never cache a plate that + // lost coverage during a subsequent recovery. + for (const footprint of footprints) { + if (!coversFootprint(result, footprint.polygon)) { + const levelId = context.walls.get(footprint.id)?.parentId + throw new Error(`Cannot cover boundary wall ${footprint.id} on level ${levelId}`) + } + } + sharedPlateCache.set(signature, result) + if (sharedPlateCache.size > 64) sharedPlateCache.delete(sharedPlateCache.keys().next().value!) + plateContexts.set(result, context) + cache.set(key, result) + plateCache.set(context, cache) + return result +} + +export type ExposedInterval = { + covered?: boolean + polygonIndex: number + edgeIndex: number + t0: number + t1: number + start: [number, number] + end: [number, number] +} + +type Edge = { start: [number, number]; end: [number, number]; dx: number; dz: number } +type PreparedFootprints = { polygons: MultiPolygon; edges: Edge[] } +const exposureCache = new WeakMap() +const wallExposureCache = new WeakMap< + readonly WallNode[], + { signature: string; prepared: PreparedFootprints } +>() +const plateEdgeCache = new WeakMap< + MultiPolygon, + Array +>() + +function edges(ring: Ring): Edge[] { + return ring.map((start, i) => { + const end = ring[(i + 1) % ring.length]! + return { start, end, dx: end[0] - start[0], dz: end[1] - start[1] } + }) +} + +function prepareFootprints(rings: Ring[]): PreparedFootprints { + const polygons = union(rings) + return { + polygons, + edges: polygons.flatMap(({ outer, holes }) => [outer, ...holes].flatMap(edges)), + } +} + +function exposureFootprints( + plate: MultiPolygon, + source: readonly WallNode[] | LevelFootprintContext, +) { + let context: LevelFootprintContext | undefined + if ('wallFootprints' in source) context = source + else { + const candidate = plateContexts.get(plate) + if ( + candidate && + candidate.walls.size === source.length && + source.every((wall) => candidate.walls.get(wall.id) === wall) + ) + context = candidate + } + if (context) { + let prepared = exposureCache.get(context) + if (!prepared) { + prepared = prepareFootprints([...context.wallFootprints.values()]) + exposureCache.set(context, prepared) + } + return prepared + } + const walls = source as readonly WallNode[] + const signature = JSON.stringify( + walls.map(({ id, start, end, thickness, justification, curveOffset }) => [ + id, + start, + end, + thickness, + justification, + curveOffset, + ]), + ) + const cached = wallExposureCache.get(walls) + if (cached?.signature === signature) return cached.prepared + const miters = calculateLevelMiters([...walls]) + const prepared = prepareFootprints( + walls.map((wall) => + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ), + ) + wallExposureCache.set(walls, { signature, prepared }) + return prepared +} + +/** Passing a topology context reuses its joined footprints across every plate in that revision. */ +export function exposedIntervals( + plate: MultiPolygon, + walls: readonly WallNode[] | LevelFootprintContext, + cover?: MultiPolygon, + options?: { includeCovered?: boolean; splitAt?: MultiPolygon }, +): ExposedInterval[] { + if (!plate.length) return [] + const footprints = cover + ? { + polygons: cover, + edges: cover.flatMap(({ outer, holes }) => [outer, ...holes].flatMap(edges)), + } + : exposureFootprints(plate, walls) + const cuttingEdges = [ + ...footprints.edges, + ...(options?.splitAt ?? []).flatMap(({ outer, holes }) => [outer, ...holes].flatMap(edges)), + ] + let plateEdges = plateEdgeCache.get(plate) + if (!plateEdges) { + plateEdges = plate.flatMap(({ outer, holes }, polygonIndex) => + [outer, ...holes] + .flatMap(edges) + .map((edge, edgeIndex) => ({ ...edge, polygonIndex, edgeIndex })), + ) + plateEdgeCache.set(plate, plateEdges) + } + const result: ExposedInterval[] = [] + for (const { start, dx, dz, polygonIndex, edgeIndex } of plateEdges) { + const lengthSq = dx * dx + dz * dz + if (!lengthSq) continue + const at = (t: number): [number, number] => [start[0] + t * dx, start[1] + t * dz] + const cuts = [0, 1] + for (const { start: a, end: b, dx: ex, dz: ez } of cuttingEdges) { + const ax = a[0] - start[0], + az = a[1] - start[1] + const cross = dx * ez - dz * ex + if (Math.abs(cross) < 1e-12) { + if (Math.abs(ax * dz - az * dx) < 1e-12) { + for (const p of [a, b]) + cuts.push( + Math.max( + 0, + Math.min(1, ((p[0] - start[0]) * dx + (p[1] - start[1]) * dz) / lengthSq), + ), + ) + } + continue + } + const t = (ax * ez - az * ex) / cross + const u = (ax * dz - az * dx) / cross + if (t > 0 && t < 1 && u >= 0 && u <= 1) cuts.push(t) + } + const ordered = [...new Set(cuts)].sort((a, b) => a - b) + for (let i = 0; i < ordered.length - 1; i++) { + const t0 = ordered[i]!, + t1 = ordered[i + 1]! + const covered = containsPoint(footprints.polygons, at((t0 + t1) / 2)) + if (t1 - t0 <= 1e-12 || (covered && !options?.includeCovered)) continue + const previous = result.at(-1) + if ( + previous?.polygonIndex === polygonIndex && + previous.edgeIndex === edgeIndex && + previous.t1 === t0 && + !options?.includeCovered + ) { + previous.t1 = t1 + previous.end = at(t1) + } else + result.push({ + polygonIndex, + edgeIndex, + t0, + t1, + start: at(t0), + end: at(t1), + ...(options?.includeCovered ? { covered } : {}), + }) + } + } + return result +} + +export function clearLevelFootprintCaches(): void { + sharedPlateCache.clear() +} diff --git a/packages/core/src/lib/level-name.test.ts b/packages/core/src/lib/level-name.test.ts new file mode 100644 index 0000000000..6f613f18ba --- /dev/null +++ b/packages/core/src/lib/level-name.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test } from 'bun:test' +import { getDefaultLevelName, getLevelDisplayName } from './level-name' + +describe('level names', () => { + test('an unnamed level reads by its place in the building', () => { + expect([-2, -1, 0, 1, 2].map(getDefaultLevelName)).toEqual([ + 'Basement 2', + 'Basement', + 'Ground floor', + 'Floor 1', + 'Floor 2', + ]) + expect(getLevelDisplayName({ level: 0 })).toBe('Ground floor') + expect(getLevelDisplayName({ name: ' ', level: 1 })).toBe('Floor 1') + }) + + test('the "Level N" an older build stamped reads like no name; a real name wins', () => { + expect(getLevelDisplayName({ name: 'Level 0', level: 0 })).toBe('Ground floor') + expect(getLevelDisplayName({ name: 'Level 2', level: 2 })).toBe('Floor 2') + // A "Level N" that does not match its own place was chosen by someone. + expect(getLevelDisplayName({ name: 'Level 3', level: 1 })).toBe('Level 3') + expect(getLevelDisplayName({ name: 'Attic', level: 2 })).toBe('Attic') + }) +}) diff --git a/packages/core/src/lib/level-name.ts b/packages/core/src/lib/level-name.ts index dd4f904f4d..6366607ed6 100644 --- a/packages/core/src/lib/level-name.ts +++ b/packages/core/src/lib/level-name.ts @@ -1,11 +1,19 @@ import type { LevelNode } from '../schema' +/** What an unnamed level is called: Ground floor, Floor 1, Floor 2…, Basement, Basement 2… */ export function getDefaultLevelName(level: number): string { - if (level === 0) return 'Ground Floor' + if (level === 0) return 'Ground floor' if (level > 0) return `Floor ${level}` - return `Basement ${-level}` + return level === -1 ? 'Basement' : `Basement ${-level}` } +/** + * The one way a level's name is shown. A name the user gave wins; a level + * without one — or still carrying the "Level N" an older build stamped on + * every new level — reads by its place in the building. Display only: the + * stored name is never rewritten. + */ export function getLevelDisplayName(level: Pick): string { - return level.name || getDefaultLevelName(level.level) + const name = level.name?.trim() + return name && name !== `Level ${level.level}` ? name : getDefaultLevelName(level.level) } diff --git a/packages/core/src/lib/mezzanine-audit.test.ts b/packages/core/src/lib/mezzanine-audit.test.ts new file mode 100644 index 0000000000..2ef35fc54a --- /dev/null +++ b/packages/core/src/lib/mezzanine-audit.test.ts @@ -0,0 +1,453 @@ +import { afterEach, expect, test } from 'bun:test' +import { + applyZoneTransformPlan, + createMezzanine, + deleteZone, + duplicateZone, + setZoneIntent, + structureChangeBatch, + transformZone, + ZoneIntentPatch, +} from '../commands/structure' +import { applyToScratch } from '../commands/structure/shared' +import { getFloorPlacedElevation } from '../hooks/spatial-grid/floor-placed-elevation' +import { spatialGridManager } from '../hooks/spatial-grid/spatial-grid-manager' +import { nodeRegistry, registerNode } from '../registry' +import { + type AnyNode, + CabinetNode, + ItemNode, + ShelfNode, + type SlabNode, + StairNode, + StairSegmentNode, + type ZoneNode, +} from '../schema' +import { type SceneCommit, subscribeSceneCommits } from '../store/history-control' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { migrateCeilingRoomLinks } from '../utils/room-zone-migration' +import { mezzanineFixture, mezzaninePolygon } from './__fixtures__/mezzanine' +import { exposedIntervals } from './level-footprints' +import { initSpaceDetectionSync } from './space-detection' + +globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} + +const asset = { + id: 'chair', + category: 'seating', + name: 'Chair', + thumbnail: '', + src: 'asset://chair', + dimensions: [0.5, 1, 0.5], +} +const item = (id: string, supportSlabId?: string) => + ItemNode.parse({ id, parentId: 'level_mezz', position: [2, 0, 2], supportSlabId, asset }) +let stop = () => {} +afterEach(() => { + stop() + stop = () => {} + spatialGridManager.clear() + nodeRegistry._reset() +}) +function registerItem() { + nodeRegistry._reset() + registerNode({ + kind: 'item', + schemaVersion: 1, + schema: ItemNode, + category: 'utility', + defaults: () => ({}), + capabilities: { + floorPlaced: { footprint: () => ({ dimensions: [0.5, 1, 0.5], rotation: [0, 0, 0] }) }, + }, + }) +} +function store(nodes: Record) { + useScene.setState({ + nodes, + rootNodeIds: [], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + useScene.temporal.getState().resume() + clearSceneHistory() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) +} + +test('H1 create pins every existing floor intent in the same commit; per-frame election stays on host', () => { + const { before, host, mintId } = mezzanineFixture() + const lower = item('item_lower') + const pinned = item('item_pinned', 'ground') + const cabinet = CabinetNode.parse({ + id: 'cabinet_lower', + parentId: host.parentId, + position: [2, 0, 2], + }) + const shelf = ShelfNode.parse({ id: 'shelf_lower', parentId: host.parentId, position: [2, 0, 2] }) + const stair = StairNode.parse({ id: 'stair_lower', parentId: host.parentId, position: [2, 0, 2] }) + const outside = { + ...lower, + id: 'item_outside' as const, + position: [6, 0, 2] as [number, number, number], + } + registerItem() + store({ + ...before, + ...Object.fromEntries([lower, pinned, cabinet, shelf, stair, outside].map((n) => [n.id, n])), + }) + const initial = useScene.getState().nodes + const ground = Object.values(before).find((n) => n.type === 'slab')! + const commits: SceneCommit[] = [] + const unsubscribe = subscribeSceneCommits((commit) => commits.push(commit)) + const plan = createMezzanine(initial, { hostZoneId: host.id, polygon: mezzaninePolygon, mintId }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + unsubscribe() + const nodes = useScene.getState().nodes + for (const n of [lower, cabinet, shelf, stair]) + expect(nodes[n.id]).toMatchObject({ supportSlabId: ground.id }) + expect(nodes[pinned.id]).toEqual(pinned) + expect(nodes[outside.id]).toEqual(outside) + for (const slab of Object.values(nodes).filter((n) => n.type === 'slab')) + spatialGridManager.handleNodeCreated(slab, host.parentId!) + expect( + getFloorPlacedElevation({ node: nodes[lower.id]!, nodes, position: lower.position }), + ).toBeCloseTo(0.05) + expect( + getFloorPlacedElevation({ + node: { ...nodes[lower.id]!, supportSlabId: undefined } as AnyNode, + nodes, + position: lower.position, + }), + ).toBeCloseTo(2.5) + expect(commits).toHaveLength(1) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(initial) + useScene.temporal.getState().redo() + const upper = item('item_upper') + const withUpper = { ...nodes, [upper.id]: upper } + const deletion = deleteZone(withUpper, { zoneId: plan.zoneId, contents: 'delete' }) + expect(deletion.payload.itemIds).toEqual([upper.id]) +}) + +for (const duplicate of [false, true]) + test(`H2 host ${duplicate ? 'duplicate' : 'move and rotate'} carries polygon, seed, grouping and support hosts`, () => { + const f = mezzanineFixture() + const ground = Object.values(f.nodes).find((n) => n.type === 'slab' && n.support !== 'open')! + const lower = item('item_lower', ground.id) + const upper = item('item_upper', f.plate.id) + const stair = StairNode.parse({ + id: 'stair_copy', + parentId: f.level.id, + position: [2, 0, 2], + deckSlabId: f.plate.id, + }) + const ceiling = Object.values(f.nodes).find( + (n) => n.type === 'ceiling' && n.zoneId === f.zone.id, + )! + const light = { ...item('item_light'), parentId: ceiling.id } + const original = { + ...f.nodes, + [f.zone.id]: { ...f.zone, hostZoneId: 'zone_stale' }, + [lower.id]: lower, + [upper.id]: upper, + [stair.id]: stair, + [light.id]: light, + } + let nodes: Record = original + const input = { + zoneId: f.host.id, + translate: [20, 0] as [number, number], + rotate: { angle: Math.PI / 2, pivot: [0, 0] as [number, number] }, + mintId: f.mintId, + } + const plan = duplicate ? duplicateZone(nodes, input) : transformZone(nodes, input) + expect(plan.conflicts).toBeUndefined() + applyZoneTransformPlan(plan, { + getNodes: () => nodes, + applyChanges: (changes) => { + nodes = applyToScratch(nodes, structureChangeBatch(changes)) + }, + reconcile: () => { + nodes = f.reconcile(nodes).nodes + }, + }) + const id = plan.idMap[f.zone.id]![0]! + const copied = nodes[id] as ZoneNode + expect(copied.polygon).toEqual(f.zone.polygon.map(([x, z]) => [20 + z, -x])) + expect(copied.seed![0]).toBeCloseTo(20 + f.zone.seed![1]) + expect(copied.seed![1]).toBeCloseTo(-f.zone.seed![0]) + if (duplicate) { + expect(nodes[f.zone.id]).toEqual(original[f.zone.id]) + expect(copied.hostZoneId).toBe(plan.zoneId) + const plate = Object.values(nodes).find((n) => n.type === 'slab' && n.zoneIds?.includes(id))! + expect(nodes[plan.idMap[upper.id]![0]!]).toMatchObject({ supportSlabId: plate.id }) + expect(nodes[plan.idMap[stair.id]![0]!]).toMatchObject({ deckSlabId: plate.id }) + const copiedGround = Object.values(nodes).find( + (n) => n.type === 'slab' && n.zoneIds?.includes(plan.zoneId), + )! + expect(nodes[plan.idMap[lower.id]![0]!]).toMatchObject({ supportSlabId: copiedGround.id }) + const copiedCeiling = Object.values(nodes).find( + (n) => n.type === 'ceiling' && n.zoneId === id, + )! + expect(nodes[plan.idMap[light.id]![0]!]).toMatchObject({ parentId: copiedCeiling.id }) + } + }) + +for (const contents of ['keep', 'delete'] as const) + test(`H3 deleting a host ${contents}s stacked contents in one undo step without orphan zones`, () => { + const f = mezzanineFixture() + const upper = item('item_upper', f.plate.id) + store({ ...f.nodes, [f.zone.id]: { ...f.zone, hostZoneId: undefined }, [upper.id]: upper }) + const initial = useScene.getState().nodes + const commits: SceneCommit[] = [] + const unsubscribe = subscribeSceneCommits((c) => commits.push(c)) + const plan = deleteZone(initial, { zoneId: f.host.id, contents }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + unsubscribe() + const nodes = useScene.getState().nodes + expect(nodes[f.zone.id]).toBeUndefined() + expect(nodes[f.plate.id]).toBeUndefined() + expect( + Object.values(nodes).filter((n) => n.type === 'zone' || n.type === 'ceiling'), + ).toHaveLength(0) + if (contents === 'keep') + expect((nodes[upper.id] as import('../schema').ItemNode).supportSlabId).toBeUndefined() + else expect(nodes[upper.id]).toBeUndefined() + expect(commits).toHaveLength(1) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(initial) + }) + +test('H4 support cannot be set or cleared through zone intent', () => { + const { nodes, zone, host } = mezzanineFixture() + for (const support of ['open', null]) { + const patch = { floor: { support } } + expect(ZoneIntentPatch.safeParse(patch).success).toBe(false) + expect(() => setZoneIntent(nodes, { zoneId: host.id, patch: patch as never })).toThrow() + } + for (const floor of [null, { elevation: null }]) + expect(setZoneIntent(nodes, { zoneId: zone.id, patch: { floor } }).conflicts?.[0]?.code).toBe( + 'mezzanine-intent', + ) +}) + +test('M5 elevation errors are structured and respect thickness and the storey margin', () => { + const { before, nodes, zone, host, mintId } = mezzanineFixture() + for (const elevation of [-1, 0.2, 4.71]) { + const create = createMezzanine(before, { + hostZoneId: host.id, + polygon: mezzaninePolygon, + elevation, + mintId, + }) + const edit = setZoneIntent(nodes, { zoneId: zone.id, patch: { floor: { elevation } } }) + for (const plan of [create, edit]) { + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]?.code).toBe('mezzanine-elevation') + } + } + expect( + setZoneIntent(nodes, { zoneId: zone.id, patch: { floor: { thickness: 2.5 } } }).conflicts?.[0] + ?.code, + ).toBe('mezzanine-elevation') + for (const elevation of [0.21, 4.7]) + expect( + setZoneIntent(nodes, { zoneId: zone.id, patch: { floor: { elevation } } }).conflicts, + ).toBeUndefined() +}) + +test('M6 a floor opt-out removes the mezzanine ceiling and restores the whole host ceiling', () => { + const { nodes, zone, host, plate, apply } = mezzanineFixture() + const changed = apply( + nodes, + setZoneIntent(nodes, { zoneId: zone.id, patch: { hasFloor: false } }), + ) + expect(changed[plate.id]).toBeUndefined() + expect(Object.values(changed).filter((n) => n.type === 'ceiling')).toMatchObject([ + { zoneId: host.id, holes: [] }, + ]) +}) + +test('M7 overlapping stacked zones are refused but touching outlines are allowed', () => { + const { nodes, host, mintId } = mezzanineFixture() + expect( + createMezzanine(nodes, { hostZoneId: host.id, polygon: mezzaninePolygon, mintId }) + .conflicts?.[0]?.code, + ).toBe('overlaps-mezzanine') + expect( + createMezzanine(nodes, { + hostZoneId: host.id, + polygon: [ + [4, 0.1], + [6, 0.1], + [6, 3], + [4, 3], + ], + mintId, + }).conflicts, + ).toBeUndefined() +}) + +test('M8 wall-centre outlines clip to wall faces and pin lower furniture in one undo step', () => { + const { before, host, mintId } = mezzanineFixture() + const lower = item('item_lower') + store({ ...before, [lower.id]: lower }) + const initial = useScene.getState().nodes + const ground = Object.values(before).find( + (n) => n.type === 'slab' && n.zoneIds?.includes(host.id), + )! + const polygon: [number, number][] = [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ] + const plan = createMezzanine(initial, { hostZoneId: host.id, polygon, mintId }) + expect(plan.conflicts).toBeUndefined() + expect(plan.changes).toContainEqual({ + op: 'update', + id: lower.id, + data: { supportSlabId: ground.id }, + }) + applyZoneTransformPlan(plan) + const nodes = useScene.getState().nodes + expect(nodes[plan.zoneId]).toMatchObject({ polygon, hostZoneId: host.id }) + expect(nodes[lower.id]).toMatchObject({ supportSlabId: ground.id }) + const plate = Object.values(nodes).find( + (n): n is SlabNode => n.type === 'slab' && !!n.zoneIds?.includes(plan.zoneId), + )! + expect(plate.polygon).toEqual(mezzaninePolygon) + expect(plate.railing).toHaveLength(2) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(initial) +}) + +test('M10 exposed intervals include hole rings and railings leave a stair arrival gap', () => { + const f = mezzanineFixture() + const hole: [number, number][] = [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], + ] + expect(exposedIntervals([{ outer: f.plate.polygon, holes: [hole] }], []).length).toBe(8) + const segment = StairSegmentNode.parse({ + id: 'sseg_arrival', + parentId: 'stair_arrival', + width: 1.2, + length: 2, + height: 2.5, + }) + const stair = StairNode.parse({ + id: 'stair_arrival', + parentId: f.level.id, + position: [6, 0, 1.5], + rotation: -Math.PI / 2, + children: [segment.id], + deckSlabId: f.plate.id, + }) + store({ + ...f.nodes, + [f.plate.id]: { ...f.plate, holes: [hole], holeMetadata: [{ source: 'manual' }] }, + }) + useScene.getState().applyNodeChanges({ + create: [ + { node: stair, parentId: f.level.id }, + { node: segment, parentId: stair.id }, + ], + }) + const rails = () => (useScene.getState().nodes[f.plate.id] as SlabNode).railing! + const length = () => + rails().reduce( + (sum, { start, end }) => sum + Math.hypot(end[0] - start[0], end[1] - start[1]), + 0, + ) + expect(length()).toBeCloseTo(2.9 + 3.9 + 4 - 1.2) + useScene.getState().updateNode(segment.id, { width: 2 }) + expect(length()).toBeCloseTo(2.9 + 3.9 + 4 - 2) + useScene.getState().updateNode(stair.id, { rotation: 0 }) + expect(length()).toBeCloseTo(2.9 + 3.9 + 4) + useScene.getState().updateNode(stair.id, { position: [1.5, 0, 0], rotation: 0 }) + expect(length()).toBeLessThan(2.9 + 3.9 + 4) + useScene.getState().deleteNode(stair.id) + expect(length()).toBeCloseTo(2.9 + 3.9 + 4) +}) + +test('LOW ceiling migration repairs ordinary stale links while preserving mezzanine links', () => { + const { nodes, host, zone } = mezzanineFixture() + const ceiling = Object.values(nodes).find((n) => n.type === 'ceiling' && n.zoneId === host.id)! + const changed = migrateCeilingRoomLinks({ + ...nodes, + zone_wrong: { ...host, id: 'zone_wrong', polygon: host.polygon.map(([x, z]) => [x + 20, z]) }, + [ceiling.id]: { ...ceiling, holes: [], holeMetadata: [], zoneId: 'zone_wrong' }, + }).nodes + expect(changed[ceiling.id]).toMatchObject({ zoneId: host.id }) + const mezzCeiling = Object.values(nodes).find( + (n) => n.type === 'ceiling' && n.zoneId === zone.id, + )! + expect(changed[mezzCeiling.id]).toEqual(mezzCeiling) +}) + +for (const duplicate of [false, true]) + test(`H2 host ${duplicate ? 'duplicate' : 'transform'} with stacked contents publishes one commit and undoes completely`, () => { + const f = mezzanineFixture() + const upper = item('item_upper', f.plate.id) + store({ ...f.nodes, [upper.id]: upper }) + const initial = useScene.getState().nodes + const input = { zoneId: f.host.id, translate: [20, 0] as [number, number], mintId: f.mintId } + const plan = duplicate ? duplicateZone(initial, input) : transformZone(initial, input) + const commits: SceneCommit[] = [] + const unsubscribe = subscribeSceneCommits((c) => commits.push(c)) + applyZoneTransformPlan(plan) + unsubscribe() + expect(commits).toHaveLength(1) + const nodes = useScene.getState().nodes + expect( + Object.values(nodes).filter((n) => n.type === 'zone' && n.floor?.support === 'open'), + ).toHaveLength(duplicate ? 2 : 1) + const targetZone = plan.idMap[f.zone.id]![0]! + const plate = Object.values(nodes).find( + (n) => n.type === 'slab' && n.zoneIds?.includes(targetZone), + )! + expect(nodes[plan.idMap[upper.id]![0]!]).toMatchObject({ supportSlabId: plate.id }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(initial) + }) + +test('H1 deletion uses footprint election and hole veto, including items straddling open edges', () => { + const f = mezzanineFixture() + registerItem() + const edge = { ...item('item_edge'), position: [4.1, 0, 2] as [number, number, number] } + const inHole = item('item_hole') + const plate = { + ...f.plate, + holes: [ + [ + [1.5, 1.5], + [2.5, 1.5], + [2.5, 2.5], + [1.5, 2.5], + ], + ] as [number, number][][], + } + const nodes = { ...f.nodes, [plate.id]: plate, [edge.id]: edge, [inHole.id]: inHole } + for (const slab of Object.values(nodes).filter((n) => n.type === 'slab')) + spatialGridManager.handleNodeCreated(slab, f.level.id) + expect(getFloorPlacedElevation({ node: edge, nodes, position: edge.position })).toBeCloseTo(2.5) + expect(getFloorPlacedElevation({ node: inHole, nodes, position: inHole.position })).toBeCloseTo( + 0.05, + ) + expect(deleteZone(nodes, { zoneId: f.zone.id, contents: 'delete' }).payload.itemIds).toEqual([ + edge.id, + ]) +}) diff --git a/packages/core/src/lib/mezzanine.test.ts b/packages/core/src/lib/mezzanine.test.ts new file mode 100644 index 0000000000..d93617b2ef --- /dev/null +++ b/packages/core/src/lib/mezzanine.test.ts @@ -0,0 +1,248 @@ +import { afterEach, expect, test } from 'bun:test' +import { createMezzanine, deleteZone, setZoneIntent } from '../commands/structure' +import { spatialGridManager } from '../hooks/spatial-grid/spatial-grid-manager' +import { AnyNode, ItemNode, type SlabNode, StairNode } from '../schema' +import { assertDerivedNodeWrites, filterDerivedNodeWrites } from '../store/derived-node-guard' +import { computeWallSlabSupport } from '../systems/slab/slab-support' +import { resolveStairTotalRise } from '../systems/stair/stair-rise-query' +import { migrateFloorPlates } from '../utils/floor-plate-migration' +import { reconcileStructureOnLoad } from '../utils/reconcile-structure-on-load' +import { migrateCeilingRoomLinks, migrateRoomZones } from '../utils/room-zone-migration' +import { mezzanineFixture, mezzaninePolygon } from './__fixtures__/mezzanine' +import { area } from './polygon-boolean' +import { deriveZoneQuantityReport } from './zone-quantities' + +afterEach(() => spatialGridManager.clear()) + +test('mezzanine preserves host identity, whole plate, area, quantities and walls', () => { + const { before, nodes, host, walls, reconcile } = mezzanineFixture() + expect(nodes[host.id]).toEqual(host) + const ground = Object.values(before).find((n) => n.type === 'slab')! + expect(nodes[ground.id]).toEqual(ground) + const initial = deriveZoneQuantityReport(host, before) + const current = deriveZoneQuantityReport(host, nodes) + expect(current.footprintArea).toBe(initial.footprintArea) + expect(current.floorSurface).toEqual(initial.floorSurface) + expect(current.wallSurface).toEqual(initial.wallSurface) + const slabs = Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab') + for (const wall of walls) { + expect(nodes[wall.id]).toEqual(before[wall.id]) + expect(computeWallSlabSupport(wall, slabs, walls, undefined, undefined, 0, nodes)).toEqual( + computeWallSlabSupport(wall, [ground as SlabNode], walls, undefined, undefined, 0, before), + ) + } + expect(reconcile(nodes).patches).toEqual([]) +}) + +test('mezzanine thin plate stops at wall faces with railing only on open intervals', () => { + const { zone, plate } = mezzanineFixture() + expect(plate).toMatchObject({ + boundary: 'auto', + support: 'open', + zoneIds: [zone.id], + elevation: 2.5, + thickness: 0.2, + fillToTerrain: false, + }) + expect(plate.polygon).toEqual(mezzaninePolygon) + expect( + plate.railing?.map(({ start, end }) => ({ + start: start.map((v) => Math.round(v * 1e4) / 1e4), + end: end.map((v) => Math.round(v * 1e4) / 1e4), + })), + ).toEqual([ + { start: [4, 0.1], end: [4, 3] }, + { start: [4, 3], end: [0.1, 3] }, + ]) +}) + +test('host ceiling has a room hole; mezzanine ceiling requires two metres and honors opt-out', () => { + for (const [height, expected] of [ + [3.9, false], + [4, true], + [5, true], + ] as const) { + const { nodes, host, zone, plate, apply } = mezzanineFixture(height) + const ceilings = Object.values(nodes).filter((n) => n.type === 'ceiling') + const hostCeiling = ceilings.find((n) => n.zoneId === host.id)! + expect(hostCeiling.holeMetadata).toEqual([{ source: 'room' }]) + expect(area(hostCeiling.holes.map((outer) => ({ outer, holes: [] })))).toBeCloseTo( + area([{ outer: plate.polygon, holes: [] }]), + ) + expect(ceilings.some((n) => n.zoneId === zone.id)).toBe(expected) + const changed = apply( + nodes, + setZoneIntent(nodes, { zoneId: zone.id, patch: { hasCeiling: false } }), + ) + expect(Object.values(changed).some((n) => n.type === 'ceiling' && n.zoneId === zone.id)).toBe( + false, + ) + } +}) + +test('mezzanine support election follows the pointed surface and stairs target its plate', () => { + const { nodes, plate, level } = mezzanineFixture() + for (const slab of Object.values(nodes).filter((n) => n.type === 'slab')) + spatialGridManager.handleNodeCreated(slab, level.id) + const pointed = spatialGridManager.getPointedSupportSurface(level.id, [2, 6, 2], [0, -1, 0]) + expect(pointed).toEqual({ slabId: plate.id, elevation: 2.5, point: [2, 2] }) + expect( + spatialGridManager.getSlabSupportForItem( + level.id, + [2, 0, 2], + [0.5, 1, 0.5], + [0, 0, 0], + pointed.elevation, + ), + ).toEqual({ slabId: plate.id, elevation: plate.elevation }) + expect( + spatialGridManager.getPointedSupportSurface(level.id, [2, 1, 2], [0, -1, 0]).elevation, + ).toBe(0.05) + const stair = StairNode.parse({ parentId: level.id, deckSlabId: plate.id }) + expect(resolveStairTotalRise(stair, nodes, () => 0.05)).toBeCloseTo(2.45) +}) + +test('mezzanine intent updates preserve its plate ID and deletion removes construction and ceiling hole', () => { + const { nodes, zone, host, plate, apply } = mezzanineFixture() + const changed = apply( + nodes, + setZoneIntent(nodes, { + zoneId: zone.id, + patch: { floor: { elevation: 3.2, thickness: 0.3, finish: 'wood' } }, + }), + ) + expect(changed[plate.id]).toMatchObject({ elevation: 3.2, thickness: 0.3 }) + expect(Object.values(changed).some((n) => n.type === 'ceiling' && n.zoneId === zone.id)).toBe( + false, + ) + const removed = apply(changed, deleteZone(changed, { zoneId: zone.id, contents: 'keep' })) + expect(removed[plate.id]).toBeUndefined() + expect(removed[host.id]).toEqual(host) + expect(Object.values(removed).filter((n) => n.type === 'ceiling')).toMatchObject([ + { zoneId: host.id, holes: [] }, + ]) +}) + +test('deleting mezzanine contents preserves items pinned to the host floor', () => { + const { nodes, zone, plate, apply, host } = mezzanineFixture() + const ground = Object.values(nodes).find( + (n) => n.type === 'slab' && n.zoneIds?.includes(host.id), + )! + const asset = { + id: 'chair', + category: 'seating', + name: 'Chair', + thumbnail: '', + src: 'https://example.com/chair.glb', + } + const lower = ItemNode.parse({ + id: 'item_lower', + parentId: zone.parentId, + position: [2, 0, 2], + supportSlabId: ground.id, + asset, + }) + const upper = ItemNode.parse({ ...lower, id: 'item_upper', supportSlabId: plate.id }) + const withItems = { ...nodes, [lower.id]: lower, [upper.id]: upper } + const removed = apply(withItems, deleteZone(withItems, { zoneId: zone.id, contents: 'delete' })) + expect(removed[lower.id]).toEqual(lower) + expect(removed[upper.id]).toBeUndefined() +}) + +test('MCP refuses and in-app filtering ignores hand-written mezzanine plate, railing, construction and ceiling holes', () => { + const { nodes, plate, host } = mezzanineFixture() + expect(() => + assertDerivedNodeWrites(nodes, { create: [{ node: { ...plate, id: 'slab_illegal' } }] }), + ).toThrow() + for (const data of [ + { railing: [] }, + { support: undefined }, + { elevation: 4 }, + { thickness: 1 }, + { boundary: undefined }, + ]) { + expect(() => assertDerivedNodeWrites(nodes, { update: [{ id: plate.id, data }] })).toThrow() + expect(filterDerivedNodeWrites(nodes, { update: [{ id: plate.id, data }] }).update).toEqual([]) + } + const ceiling = Object.values(nodes).find((n) => n.type === 'ceiling' && n.zoneId === host.id)! + expect(() => + assertDerivedNodeWrites(nodes, { update: [{ id: ceiling.id, data: { holes: [] } }] }), + ).toThrow() +}) + +test('createMezzanine validates reference containment, simple polygon, area and snapped defaults', () => { + const { before, host, mintId } = mezzanineFixture(5.13) + const plan = createMezzanine(before, { hostZoneId: host.id, polygon: mezzaninePolygon, mintId }) + expect(plan.changes[0]).toMatchObject({ + op: 'create', + node: { floor: { elevation: 2.55, thickness: 0.2, support: 'open' } }, + }) + for (const polygon of [ + [ + [-1, 0], + [2, 0], + [2, 2], + [-1, 2], + ], + [ + [1, 1], + [1.5, 1], + [1.5, 1.5], + [1, 1.5], + ], + [ + [1, 1], + [4, 4], + [1, 4], + [4, 1], + ], + ] as [number, number][][]) + expect(createMezzanine(before, { hostZoneId: host.id, polygon, mintId }).changes).toEqual([]) +}) + +test('full-clear mezzanine stays independent and survives schema/load roundtrip', () => { + const { before, host, apply, reconcile } = mezzanineFixture() + const plan = createMezzanine(before, { + hostZoneId: host.id, + polygon: [ + [0.1, 0.1], + [7.9, 0.1], + [7.9, 5.9], + [0.1, 5.9], + ], + elevation: 0.3, + mintId: () => 'zone_zzzz', + }) + const nodes = apply(before, plan) + expect(Object.values(nodes).filter((n) => n.type === 'slab')).toHaveLength(2) + expect(nodes[host.id]).toEqual(host) + const parsed = Object.fromEntries(Object.entries(nodes).map(([id, n]) => [id, AnyNode.parse(n)])) + const rooms = migrateRoomZones(parsed).nodes + const ceilings = migrateCeilingRoomLinks(rooms).nodes + const plates = migrateFloorPlates(ceilings).nodes + const loaded = reconcileStructureOnLoad(plates).nodes + expect(loaded[plan.zoneId]).toEqual(nodes[plan.zoneId]) + expect(Object.values(loaded).filter((n) => n.type === 'ceiling')).toEqual( + Object.values(nodes).filter((n) => n.type === 'ceiling'), + ) + expect(reconcile(loaded).patches).toEqual([]) +}) + +test('geometry determines the host cutout without hostZoneId; wall edits clip the derived plate only', () => { + const { nodes, zone, plate, host, walls, reconcile } = mezzanineFixture() + const ungrouped = { ...zone } + delete ungrouped.hostZoneId + const wall = walls[0]! + const updated = reconcile({ + ...nodes, + [zone.id]: ungrouped, + [wall.id]: { ...nodes[wall.id]!, thickness: 0.6 } as AnyNode, + }).nodes + const clipped = updated[plate.id] as SlabNode + expect(Math.min(...clipped.polygon.map(([, z]) => z))).toBeCloseTo(0.3) + expect(updated[zone.id]).toEqual(ungrouped) + expect(updated[wall.id]).toEqual({ ...nodes[wall.id]!, thickness: 0.6 }) + expect( + Object.values(updated).find((n) => n.type === 'ceiling' && n.zoneId === host.id), + ).toMatchObject({ holeMetadata: [{ source: 'room' }] }) +}) diff --git a/packages/core/src/lib/node-ancestry.ts b/packages/core/src/lib/node-ancestry.ts new file mode 100644 index 0000000000..0583583701 --- /dev/null +++ b/packages/core/src/lib/node-ancestry.ts @@ -0,0 +1,82 @@ +import type { AnyNode, AnyNodeId } from '../schema' + +export function resolveLevelId(node: AnyNode, nodes: Record): string { + // If the node itself is a level + if (node.type === 'level') return node.id + + // Walk up parent chain to find level + // This assumes you track parentId or can derive it + let current: AnyNode | undefined = node + + while (current) { + if (current.type === 'level') return current.id + // Find parent (you might need to add parentId to your schema or derive it) + if (current.parentId) { + current = nodes[current.parentId] + } else { + current = undefined + } + } + + return 'default' // fallback for orphaned items +} + +/** + * Walks the parent chain of `nodeId` and returns the id of the first ancestor + * whose `type` is `'level'`, or `null` when no level ancestor exists (orphaned + * node, top-level building node, etc.). Unlike `resolveLevelId`, this variant: + * + * - accepts a node **id** rather than a resolved node, saving the caller a + * `nodes[id]` lookup when only the id is at hand. + * - returns `null` instead of the `'default'` fallback, which lets callers + * distinguish "genuinely has no level" from "is a level". + * - has a loop guard (16 iterations) so a corrupt parent-chain cycle cannot + * hang the frame loop. + */ +export function findLevelAncestorId( + nodeId: AnyNodeId, + nodes: Record, +): string | null { + let current: AnyNode | undefined = nodes[nodeId] + let guard = 0 + while (current && guard < 16) { + if (current.type === 'level') return current.id + current = current.parentId ? nodes[current.parentId] : undefined + guard += 1 + } + return null +} + +/** + * Returns the building id that contains the given level, or `null` if + * the level is unparented or no enclosing building exists. + * + * Most scenes record the relationship via `level.parentId → + * building.id`, but older serialisations occasionally drop `parentId` + * even though the building's `children` array still references the + * level. The fallback scan covers that case. + * + * Used by `FloorplanRegistryLayer` to discover building-scoped kinds + * (`def.floorplanScope === 'building'`) without hardcoding any kind + * name in the editor layer. + */ +export function resolveBuildingForLevel( + levelId: AnyNodeId, + nodes: Record, +): AnyNodeId | null { + const level = nodes[levelId] as AnyNode | undefined + if (!level) return null + const directParent = (level as { parentId?: AnyNodeId | null }).parentId ?? null + if (directParent) { + const candidate = nodes[directParent] + if (candidate?.type === 'building') return candidate.id as AnyNodeId + } + for (const candidate of Object.values(nodes)) { + if (candidate?.type !== 'building') continue + const children = (candidate as { children?: AnyNodeId[] }).children + if (Array.isArray(children) && children.includes(levelId)) { + return candidate.id as AnyNodeId + } + } + return null +} diff --git a/packages/core/src/lib/opening-floor-datum.test.ts b/packages/core/src/lib/opening-floor-datum.test.ts new file mode 100644 index 0000000000..c7dac09395 --- /dev/null +++ b/packages/core/src/lib/opening-floor-datum.test.ts @@ -0,0 +1,42 @@ +import { expect, test } from 'bun:test' +import { type AnyNode, DoorNode, WallNode } from '../schema' +import { getWallBodyCenterOffset } from '../systems/wall/wall-frame' +import { getOpeningWallCut } from './opening-floor-datum' +import { area, difference } from './polygon-boolean' + +// The aperture is the doorway floor (the wall's own footprint); the band is what +// the wall body loses and must reach past both faces, or the CSG cut is coplanar. +for (const [label, extra] of [ + ['straight', {}], + ['justified', { justification: 'a' }], + ['curved', { curveOffset: 0.8 }], +] as const) + test(`opening cut band contains the aperture and overshoots both faces: ${label}`, () => { + const wall = WallNode.parse({ + id: 'wall_band', + parentId: 'level_band', + start: [0, 0], + end: [4, 0.03], + thickness: 0.12, + children: ['door_band'], + ...extra, + }) + const door = DoorNode.parse({ + id: 'door_band', + parentId: wall.id, + wallId: wall.id, + position: [2, 1.05, 0], + width: 0.9, + height: 2.1, + }) + const nodes: Record = { [wall.id]: wall, [door.id]: door } + const cut = getOpeningWallCut(wall, door, nodes) + expect(area(cut.aperture)).toBeGreaterThan(0) + expect(area(difference(cut.aperture, cut.band))).toBeLessThan(1e-4) + // A centred twin reaching 5 cm past both faces still fits inside the band. + const face = Math.abs(getWallBodyCenterOffset(wall)) + (wall.thickness ?? 0) / 2 + const twin = WallNode.parse({ ...wall, justification: undefined, thickness: 2 * face + 0.1 }) + const twinCut = getOpeningWallCut(twin, door, { [twin.id]: twin, [door.id]: door }) + expect(area(twinCut.aperture)).toBeGreaterThan(area(cut.aperture) + 0.05) + expect(area(difference(twinCut.aperture, cut.band))).toBeLessThan(1e-4) + }) diff --git a/packages/core/src/lib/opening-floor-datum.ts b/packages/core/src/lib/opening-floor-datum.ts new file mode 100644 index 0000000000..4d2dbd1f55 --- /dev/null +++ b/packages/core/src/lib/opening-floor-datum.ts @@ -0,0 +1,231 @@ +import type { AnyNode, DoorNode, SlabNode, WallNode, WindowNode } from '../schema' +import { getWallPlaneTop } from '../services/storey' +import { + computeWallSlabSupport, + type WallSlabSupport, + type WallSlabSupportSegment, +} from '../systems/slab/slab-support' +import { getWallCurveFrameAt, getWallCurveLength } from '../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { getWallBodyCenterOffset } from '../systems/wall/wall-frame' +import { resolveWallTop } from '../systems/wall/wall-top' +import { + isFloorAnchoredOpening, + openingAperture, + wallOpeningBand, +} from './floor-opening-footprints' +import { area, intersection, union } from './polygon-boolean' +import { levelBaseElevationAt } from './terrain-support-query' + +const supportCache = new WeakMap< + Readonly>, + Map +>() +const childrenCache = new WeakMap< + Readonly>, + Map +>() + +export function wallSupportForNodes( + wall: WallNode, + nodes: Readonly>, +): WallSlabSupport { + let cached = supportCache.get(nodes) + if (!cached) { + cached = new Map() + supportCache.set(nodes, cached) + } + const previous = cached.get(wall) + if (previous) return previous + let levels = childrenCache.get(nodes) + if (!levels) { + levels = new Map() + childrenCache.set(nodes, levels) + } + let level = levels.get(wall.parentId!) + if (!level) { + const children = Object.values(nodes) + .filter((node) => node.parentId === wall.parentId) + .sort((a, b) => a.id.localeCompare(b.id)) + level = { + walls: children.filter((n): n is WallNode => n.type === 'wall'), + slabs: children.filter((n): n is SlabNode => n.type === 'slab'), + } + levels.set(wall.parentId!, level) + } + const ground = levelBaseElevationAt(nodes, wall.parentId!, wall.start[0], wall.start[1]) + const result = computeWallSlabSupport( + wall, + level.slabs, + level.walls, + wall.supportSlabId, + undefined, + ground, + nodes, + ) + cached.set(wall, result) + return result +} + +export function supportSegmentAt(segment: WallSlabSupportSegment, t: number): number { + return ( + segment.elevation + + ((t - segment.start) / (segment.end - segment.start)) * + ((segment.endElevation ?? segment.elevation) - segment.elevation) + ) +} + +export function openingDatumFromSupport( + wall: WallNode, + opening: Pick, + support: WallSlabSupport, +): number { + if (!isFloorAnchoredOpening(opening)) return support.elevation + const length = getWallCurveLength(wall) + const from = Math.max(0, (opening.position[0] - opening.width / 2) / length) + const to = Math.min(1, (opening.position[0] + opening.width / 2) / length) + const heights = [...support.faceDatum.a, ...support.faceDatum.b].flatMap((segment) => { + const start = Math.max(from, segment.start), + end = Math.min(to, segment.end) + return end > start ? [supportSegmentAt(segment, start), supportSegmentAt(segment, end)] : [] + }) + return heights.length ? Math.max(...heights) : support.elevation +} + +/** Unclamped floor intent, used by authoring feasibility and legacy migration. */ +export function getOpeningFloorTarget( + wall: WallNode, + opening: Pick, + nodes: Readonly>, +): number { + return openingDatumFromSupport(wall, opening, wallSupportForNodes(wall, nodes)) +} + +export function openingFitsAtDatum( + wall: WallNode, + opening: Pick, + datum: number, + nodes: Readonly>, + support = wallSupportForNodes(wall, nodes), +): boolean { + const top = resolveWallTop(wall, getWallPlaneTop(wall, wall.parentId!, nodes), support.elevation) + return datum + opening.position[1] + opening.height / 2 <= top + 1e-9 +} + +export function getOpeningFloorDatum( + wall: WallNode, + opening: Pick, + nodes: Readonly>, + support = wallSupportForNodes(wall, nodes), +): number { + const target = openingDatumFromSupport(wall, opening, support) + if (target === support.elevation) return target + return openingFitsAtDatum(wall, opening, target, nodes, support) ? target : support.elevation +} + +const cutPlans = new WeakMap< + Readonly>, + Map< + string, + { footprints: Map; covers: Map> } + > +>() + +export function getOpeningWallCut( + wall: WallNode, + opening: DoorNode | WindowNode, + nodes: Readonly>, + support = wallSupportForNodes(wall, nodes), +) { + let levels = cutPlans.get(nodes) + if (!levels) { + levels = new Map() + cutPlans.set(nodes, levels) + } + let plan = levels.get(wall.parentId!) + if (!plan) { + const walls = Object.values(nodes).filter( + (n): n is WallNode => n.type === 'wall' && n.parentId === wall.parentId, + ) + if (!walls.some((w) => w.id === wall.id)) walls.push(wall) + const miters = calculateLevelMiters(walls) + const footprints = new Map( + walls.map((w) => [ + w.id as string, + getWallPlanFootprint(w, miters).map(({ x, y }): [number, number] => [x, y]), + ]), + ) + plan = { footprints, covers: new Map() } + levels.set(wall.parentId!, plan) + } + const { footprints, covers } = plan + const aperture = openingAperture(wall, opening, footprints) + const datum = getOpeningFloorDatum(wall, opening, nodes, support) + const cover = + covers.get(datum) ?? + union( + Object.values(nodes).flatMap((n) => + n.type === 'slab' && + n.parentId === wall.parentId && + n.support !== 'open' && + Math.abs(n.elevation - datum) < 0.001 - 1e-9 + ? [{ outer: n.polygon, holes: n.holes }] + : [], + ), + ) + covers.set(datum, cover) + const covered = + area(aperture) > 0 && area(intersection(aperture, cover)) >= area(aperture) - 0.00001 + const length = getWallCurveLength(wall) + const from = (opening.position[0] - opening.width / 2) / length, + to = (opening.position[0] + opening.width / 2) / length + const bottoms = [...support.faceBottom.a, ...support.faceBottom.b] + .filter((s) => s.end > from && s.start < to) + .map((s) => Math.min(s.elevation, s.endElevation ?? s.elevation)) + const bottom = + isFloorAnchoredOpening(opening) && covered + ? Math.min(support.elevation, ...bottoms) + : datum + opening.position[1] - opening.height / 2 + return { + // The floor the doorway exposes: exactly the wall's own footprint. + aperture, + // What the wall body loses: the same span, overshooting both faces. + band: wallOpeningBand(wall, Math.max(0, from), Math.min(1, to)), + datum, + bottom, + top: datum + opening.position[1] + opening.height / 2, + covered, + } +} + +export function getOpeningWallPlacement( + wall: WallNode, + opening: Pick & { + metadata?: Record + }, + nodes: Readonly>, +) { + if (opening.metadata?.curvedWindowMaster || getWallCurveLength(wall) < 1e-6) + return { position: opening.position, rotation: opening.rotation } + const frame = getWallCurveFrameAt(wall, opening.position[0] / getWallCurveLength(wall)) + const angle = Math.atan2(wall.end[1] - wall.start[1], wall.end[0] - wall.start[0]), + cos = Math.cos(angle), + sin = Math.sin(angle) + const offset = getWallBodyCenterOffset(wall) + opening.position[2] + const dx = frame.point.x + frame.normal.x * offset - wall.start[0], + dz = frame.point.y + frame.normal.y * offset - wall.start[1] + return { + position: [ + dx * cos + dz * sin, + opening.position[1] + + getOpeningFloorDatum(wall, opening, nodes) - + wallSupportForNodes(wall, nodes).elevation, + -dx * sin + dz * cos, + ] as [number, number, number], + rotation: [ + opening.rotation[0], + opening.rotation[1] + angle - Math.atan2(frame.tangent.y, frame.tangent.x), + opening.rotation[2], + ] as [number, number, number], + } +} diff --git a/packages/core/src/lib/own-floor-intent.ts b/packages/core/src/lib/own-floor-intent.ts new file mode 100644 index 0000000000..27f2148371 --- /dev/null +++ b/packages/core/src/lib/own-floor-intent.ts @@ -0,0 +1,255 @@ +import { boundaries, diffStructure, roomFace } from '../commands/structure/shared' +import type { AnyNode, AnyNodeId, SlabNode, ZoneNode } from '../schema' +import { resolveCeilingHeight } from '../services/level-height' +import { getLevelElevations, getWallPlaneTop } from '../services/storey' +import { MIN_WALL_HEIGHT, resolveWallTop } from '../systems/wall/wall-top' +import { reconcileStructureWithStableIds } from '../utils/structure-id' +import { mintFloorFootprintKey } from './floor-footprint-key' +import { floorPlateHoldsUnderside } from './floor-foundation-datum' +import { floorIntentConflicts } from './floor-intent-changes' +import { isFloorAnchoredOpening } from './floor-opening-footprints' +import { floorRoomFaces } from './floor-room-faces' +import { getOpeningFloorDatum, wallSupportForNodes } from './opening-floor-datum' +import { getRoomBaseElevation, roundFloorElevation } from './room-floor-feasibility' + +type Update = { id: AnyNodeId; data: Partial } + +export function ownFloorIntentChanges( + nodes: Readonly>, + updates: readonly Update[], +) { + const result: Update[] = [] + let changed = false + const refuse = (id: string, detail: string) => ({ + updates: [] as Update[], + conflicts: [ + { code: 'room-floor-footprint', nodeIds: [id], message: `Level the floors first. ${detail}` }, + ], + }) + for (const update of updates) { + const zone = nodes[update.id] + const data = update.data as Partial + if ( + zone?.type !== 'zone' || + !Object.hasOwn(data, 'floor') || + (!zone.floor?.footprint && !data.floor?.footprint) + ) { + result.push(update) + continue + } + const floor = { ...data.floor } + const mint = floor.footprint === 'new' + if (mint) floor.footprint = mintFloorFootprintKey(zone.id) + const key = floor.footprint + if (key === zone.floor?.footprint) { + if (key && floor.elevation !== zone.floor?.elevation) { + const conflicts = floorIntentConflicts(nodes, [update]) + if (conflicts.length) return { updates: [] as Update[], conflicts } + } + result.push(update) + continue + } + if ( + zone.spaceRole !== 'room' || + zone.floor?.support === 'open' || + zone.floor?.sourceSlabId || + zone.hasFloor === false + ) + return refuse( + zone.id, + 'Only a grounded room with a generated floor can change its footprint.', + ) + const faces = floorRoomFaces(boundaries(nodes, zone.parentId!)) + const face = roomFace(nodes, zone, faces) + const neighbours = Object.values(nodes).filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.spaceRole === 'room' && + node.id !== zone.id && + node.parentId === zone.parentId && + node.floor?.support !== 'open' && + node.hasFloor !== false && + !!roomFace(nodes, node, faces)?.spans.some((other) => + face?.spans.some( + (span) => + span.boundaryId === other.boundaryId && + span.face !== other.face && + Math.min(span.t1, other.t1) - Math.max(span.t0, other.t0) > 1e-6, + ), + ), + ) + const base = Object.values(nodes).find( + (node): node is SlabNode => + node.type === 'slab' && node.plateRole === 'base' && !!node.zoneIds?.includes(zone.id), + ) + if (!base) return refuse(zone.id, 'This room has no single base plate to convert.') + const top = roundFloorElevation(zone.floor?.elevation ?? getRoomBaseElevation(nodes, zone.id)) + if ( + mint && + floorPlateHoldsUnderside(nodes, base) && + base.thickness + top - base.elevation < 0.02 - 1e-9 + ) + return refuse(zone.id, 'The floor must retain at least 0.02 m above its soffit.') + // Room intent stores the level-local walking top, preserving its world height + // when the destination base is at a different height. + floor.elevation = top + if ( + !key && + !base.zoneIds?.some( + (id) => + id !== zone.id && + nodes[id]?.type === 'zone' && + nodes[id].floor?.footprint === zone.floor?.footprint, + ) + ) { + const target = Object.values(nodes) + .filter( + (node): node is SlabNode => + node.type === 'slab' && + node.plateRole === 'base' && + node.id !== base.id && + !!node.zoneIds?.some((id) => + neighbours.some((room) => room.id === id && !room.floor?.footprint), + ), + ) + .sort((a, b) => a.id.localeCompare(b.id))[0] + if (target) + result.push({ + id: base.id, + data: { + floorHeight: target.floorHeight ?? target.elevation, + referenceFloorElevation: target.referenceFloorElevation, + thickness: target.thickness, + foundation: target.foundation, + slots: target.slots, + }, + }) + } + result.push({ ...update, data: { ...data, floor } }) + changed = true + } + if (!changed) return { updates: result, conflicts: [] } + const draft = { ...nodes } + for (const { id, data } of result) draft[id] = { ...draft[id], ...data } as AnyNode + let next = reconcileStructureWithStableIds({ nodes: draft }).nodes + const beforeLevels = getLevelElevations(nodes) + const afterLevels = getLevelElevations(next) + for (const [id, level] of beforeLevels) + if (Math.abs(level.baseY - (afterLevels.get(id)?.baseY ?? level.baseY)) > 1e-6) + return refuse(id, 'Changing the footprint would move another storey.') + const wallUpdates: Update[] = [] + for (const old of Object.values(nodes)) { + const current = next[old.id] + if (old.type !== 'wall' || current?.type !== 'wall' || !old.parentId) continue + const oldTop = resolveWallTop( + old, + getWallPlaneTop(old, old.parentId, nodes), + wallSupportForNodes(old, nodes).elevation, + ) + const support = wallSupportForNodes(current, next).elevation + const newTop = resolveWallTop( + current, + getWallPlaneTop(current, current.parentId!, next), + support, + ) + if (Math.abs(oldTop - newTop) <= 1e-6) continue + if (oldTop - support < MIN_WALL_HEIGHT) + return refuse( + old.id, + `The preserved wall top would leave less than ${MIN_WALL_HEIGHT} m of wall.`, + ) + wallUpdates.push({ id: old.id, data: { height: roundFloorElevation(oldTop - support) } }) + } + if (wallUpdates.length) { + result.push(...wallUpdates) + for (const { id, data } of wallUpdates) draft[id] = { ...draft[id], ...data } as AnyNode + next = reconcileStructureWithStableIds({ nodes: draft }).nodes + } + const ceilingUpdates: Update[] = [] + for (const old of Object.values(nodes)) { + const current = next[old.id] + if (old.type !== 'ceiling' || current?.type !== 'ceiling') continue + const height = resolveCeilingHeight(old, nodes) + if (Math.abs(height - resolveCeilingHeight(current, next)) > 1e-6) + ceilingUpdates.push({ + id: old.id, + data: { height, metadata: { ...old.metadata, floorReassignmentHeight: true } }, + }) + } + if (ceilingUpdates.length) { + result.push(...ceilingUpdates) + for (const { id, data } of ceilingUpdates) draft[id] = { ...draft[id], ...data } as AnyNode + next = reconcileStructureWithStableIds({ nodes: draft }).nodes + for (const { id, data } of ceilingUpdates) { + const ceiling = next[id] + if ( + ceiling?.type !== 'ceiling' || + Math.abs(resolveCeilingHeight(ceiling, next) - (data as { height: number }).height) > 1e-6 + ) + return refuse( + id, + 'Changing the footprint cannot preserve the ceiling beneath the covering floor.', + ) + } + } + const openingUpdates: Update[] = [] + for (const old of Object.values(nodes)) { + const current = next[old.id] + if ( + (old.type !== 'door' && old.type !== 'window') || + (current?.type !== 'door' && current?.type !== 'window') + ) + continue + const oldWall = nodes[old.parentId!], + newWall = next[current.parentId!] + if (oldWall?.type !== 'wall' || newWall?.type !== 'wall') continue + const delta = + getOpeningFloorDatum(oldWall, old, nodes) + + old.position[1] - + getOpeningFloorDatum(newWall, current, next) - + current.position[1] + if (Math.abs(delta) <= 1e-6) continue + openingUpdates.push({ + id: old.id, + data: { + position: [current.position[0], current.position[1] + delta, current.position[2]], + // Keep the anchoring rule when compensation crosses the implicit sill threshold. + verticalAnchor: isFloorAnchoredOpening(old) ? 'floor' : 'wall', + }, + }) + } + if (openingUpdates.length) { + result.push(...openingUpdates) + for (const { id, data } of openingUpdates) draft[id] = { ...draft[id], ...data } as AnyNode + next = reconcileStructureWithStableIds({ nodes: draft }).nodes + } + for (const old of Object.values(nodes)) { + const current = next[old.id] + if ( + (old.type !== 'door' && old.type !== 'window') || + (current?.type !== 'door' && current?.type !== 'window') + ) + continue + const oldWall = nodes[old.parentId!], + newWall = next[current.parentId!] + if (oldWall?.type !== 'wall' || newWall?.type !== 'wall') continue + if ( + Math.abs( + getOpeningFloorDatum(oldWall, old, nodes) + + old.position[1] - + getOpeningFloorDatum(newWall, current, next) - + current.position[1], + ) > 1e-6 + ) + return refuse(old.id, 'Changing the footprint would move a door or window.') + } + const diff = diffStructure(nodes, next) + const conflicts = floorIntentConflicts( + nodes, + diff.flatMap((patch) => (patch.op === 'update' ? [{ id: patch.id, data: patch.data }] : [])), + diff.flatMap((patch) => (patch.op === 'create' ? [patch.node] : [])), + diff.flatMap((patch) => (patch.op === 'delete' ? [patch.id] : [])), + ) + if (conflicts.length) return refuse(result[0]!.id, conflicts.map((c) => c.message).join(' ')) + return { updates: result, conflicts: [] } +} diff --git a/packages/core/src/lib/own-floor.test.ts b/packages/core/src/lib/own-floor.test.ts new file mode 100644 index 0000000000..3a8ace441d --- /dev/null +++ b/packages/core/src/lib/own-floor.test.ts @@ -0,0 +1,787 @@ +import { afterEach, expect, test } from 'bun:test' +import { setRoomFloorConstruction } from '../commands/structure/set-room-floor-construction' +import { setZoneIntent } from '../commands/structure/set-zone-intent' +import { applyToScratch, structureChangeBatch } from '../commands/structure/shared' +import { + type AnyNode, + CeilingNode, + DoorNode, + SeparatorNode, + type SlabNode, + WindowNode, + type ZoneNode, +} from '../schema' +import { assertDerivedNodeWrites, filterDerivedNodeWrites } from '../store/derived-node-guard' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { floorStepFixture } from '../systems/slab/__fixtures__/floor-step' +import { reconcileStructureWithStableIds } from '../utils/structure-id' +import { floorFootprintName } from './floor-footprint-name' +import { + floorFootprintSupportClass, + footprintSupportsNode, + groundFloorConstruction, +} from './floor-foundation-datum' +import { keyedFloorPlateId } from './floor-plate-id' +import { resolveFloorStepFinish } from './floor-step-finish' +import { getOpeningFloorDatum, getOpeningWallCut, wallSupportForNodes } from './opening-floor-datum' +import { computePlateSurfacePartition, plateLevelContext } from './plate-surface' +import { area, containsPoint, intersection } from './polygon-boolean' +import { getRoomBaseElevation } from './room-floor-feasibility' +import { initSpaceDetectionSync } from './space-detection' + +const reconcile = (nodes: Record) => ({ + ...reconcileStructureWithStableIds({ nodes }).nodes, +}) +const bases = (nodes: Record) => + Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab' && n.plateRole === 'base') +const shape = (plate: SlabNode) => ({ outer: plate.polygon, holes: plate.holes }) +const zone = (nodes: Record, id: string) => nodes[id] as ZoneNode +function scene(separator = false, low = -0.4) { + const f = floorStepFixture(separator) + const nodes = Object.fromEntries(Object.entries(f.nodes).filter(([, n]) => n.type !== 'slab')) + nodes[f.level.id] = { + ...f.level, + height: 3, + children: f.level.children.filter((id) => nodes[id]), + } + nodes[f.zones[1]!.id] = { ...f.zones[1]!, name: 'Lanai', floor: { elevation: low } } + if (!separator) { + nodes[f.door.id] = f.door + nodes[f.divider.id] = { ...f.divider, children: [f.door.id] } + } + return { ...f, nodes: reconcile(nodes) } +} +function toggle(nodes: Record, id: string, own: boolean) { + const plan = setZoneIntent(nodes, { + zoneId: id, + patch: { floor: { footprint: own ? 'new' : null } }, + }) + expect(plan.conflicts ?? []).toEqual([]) + return reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))) +} + +test('partition: shared rooms and own singletons have stable IDs and independent construction', () => { + const s = scene() + const id = s.zones[1]!.id + const nodes = toggle(s.nodes, id, true) + expect(bases(nodes)).toHaveLength(2) + const own = bases(nodes).find((p) => p.zoneIds?.includes(id))! + expect(own.id).toBe(keyedFloorPlateId(s.level.id, zone(nodes, id).floor!.footprint!, 0)) + expect(own.elevation).toBe(-0.4) + expect(zone(nodes, id).floor?.elevation).toBeUndefined() + expect(floorFootprintName(nodes, own)).toBe('Lanai floor') + expect(area([shape(bases(nodes).find((p) => p.id !== own.id)!)])).toBeLessThan( + area([shape(bases(s.nodes)[0]!)]), + ) + expect(bases(reconcile(nodes))).toEqual(bases(nodes)) + const plan = setRoomFloorConstruction(nodes, { + zoneId: id, + patch: { foundationHeight: 0.15, thickness: 0.1, slots: { edge: 'library:red' } }, + }) + expect(plan.conflicts ?? []).toEqual([]) + const edited = reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))) + const { grade } = groundFloorConstruction(nodes, own) + expect((edited[own.id] as SlabNode).elevation).toBeCloseTo(grade + 0.25) + expect(edited[own.id]).toMatchObject({ + thickness: 0.1, + slots: { edge: 'library:red' }, + }) +}) + +test.each([ + [0.05, 0.05, 0], + [0.05, 0.3, 1], +])('own neighbours elect higher floor then lowest zone id (%s/%s)', (a, b, owner) => { + const s = scene(false, b) + for (const [i, elevation] of [a, b].entries()) { + const z = zone(s.nodes, s.zones[i]!.id) + s.nodes[z.id] = { ...z, floor: { footprint: `floor_${i}`, elevation } } + } + const nodes = reconcile(s.nodes) + const plates = bases(nodes) + expect(plates).toHaveLength(2) + const winner = plates.find((p) => p.zoneIds?.includes(s.zones[owner]!.id))! + expect(containsPoint([shape(winner)], [4, 1])).toBe(true) + expect(area(intersection(shape(plates[0]!), shape(plates[1]!)))).toBeCloseTo(0, 6) +}) + +test('a shared room owns the whole wall even where another span borders an own room', () => { + const s = scene(false, 0.05) + const nodes = toggle(s.nodes, s.zones[1]!.id, true) + const shared = bases(nodes).find((p) => p.zoneIds?.includes(s.zones[0]!.id))! + const own = bases(nodes).find((p) => p.id !== shared.id)! + expect(containsPoint([shape(shared)], [4, 1])).toBe(true) + expect(containsPoint([shape(own)], [4, 1])).toBe(false) + expect(containsPoint([shape(own)], [6, 0])).toBe(false) + expect(containsPoint([shape(shared)], [6, 0])).toBe(true) +}) + +test.each([ + false, + true, +])('equal-height own/shared and own/own have no side seam (both=%s)', (both) => { + const s = scene(true, 0.05) + let nodes = toggle(s.nodes, s.zones[1]!.id, true) + if (both) nodes = toggle(nodes, s.zones[0]!.id, true) + const context = plateLevelContext(nodes[s.level.id]!, (id) => nodes[id]) + for (const plate of bases(nodes)) { + const sides = computePlateSurfacePartition(plate, context)!.sides + const seam = sides.filter( + (side) => + Math.abs(side.start[0] - 4) < 1e-6 && + Math.abs(side.end[0] - 4) < 1e-6 && + (side.start[1] + side.end[1]) / 2 > 0.1 && + (side.start[1] + side.end[1]) / 2 < 3.9, + ) + expect(seam.length).toBeGreaterThan(0) + expect(seam.every((side) => side.role === 'hidden')).toBe(true) + } +}) + +test('shared/own doorway keeps the higher landing, lower-face step, and doorway paint', () => { + const s = scene() + const nodes = toggle(s.nodes, s.zones[1]!.id, true) + const high = s.zones[0]!.id + nodes[high] = { + ...zone(nodes, high), + floorStepOverrides: [{ key: s.door.id, finish: 'library:red' }], + } + const wall = nodes[s.divider.id] as typeof s.divider + expect(getOpeningFloorDatum(wall, s.door, nodes)).toBeCloseTo(0.05) + expect(wallSupportForNodes(wall, nodes).faceDatum.b[0]!.elevation).toBeCloseTo(-0.4) + const cut = getOpeningWallCut(wall, s.door, nodes) + const shared = bases(nodes).find((p) => p.zoneIds?.includes(high))! + expect(area(intersection(cut.aperture, shape(shared)))).toBeCloseTo(area(cut.aperture), 5) + const context = plateLevelContext(nodes[s.level.id]!, (id) => nodes[id]) + const sides = computePlateSurfacePartition(shared, context)!.sides.filter( + (side) => side.stepKey === s.door.id && side.role === 'riser', + ) + expect(sides.length).toBeGreaterThan(0) + expect(sides.some((side) => Math.abs(side.top! - side.bottom! - 0.45) < 1e-6)).toBe(true) + expect(resolveFloorStepFinish(zone(nodes, high), s.door.id, null, [zone(nodes, high)])).toBe( + 'library:red', + ) +}) + +let stop = () => {} +afterEach(() => { + stop() + useScene.temporal.getState().resume() +}) +globalThis.requestAnimationFrame ??= (cb) => { + cb(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} +test('detach and reattach preserve walking heights and doorway geometry in one undo each', () => { + const s = scene() + useScene.setState({ + nodes: s.nodes, + rootNodeIds: [s.level.id], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + useScene.temporal.getState().resume() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) + for (const own of [true, false]) { + clearSceneHistory() + const before = useScene.getState().nodes + const plan = setZoneIntent(before, { + zoneId: s.zones[1]!.id, + patch: { floor: { footprint: own ? 'new' : null } }, + }) + expect(plan.conflicts ?? []).toEqual([]) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const after = useScene.getState().nodes + const room = zone(after, s.zones[1]!.id) + expect(room.floor?.elevation ?? getRoomBaseElevation(after, room.id)).toBeCloseTo(-0.4) + expect(bases(after)).toHaveLength(own ? 2 : 1) + expect(getOpeningWallCut(after[s.divider.id] as typeof s.divider, s.door, after)).toEqual( + getOpeningWallCut(before[s.divider.id] as typeof s.divider, s.door, before), + ) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + } +}) + +test('an isolated room retains its floor key', () => { + const s = scene(true, 0.05) + delete s.nodes[s.boundary.id] + const nodes = reconcile(s.nodes) + const room = Object.values(nodes).find((n): n is ZoneNode => n.type === 'zone')! + const after = toggle(nodes, room.id, true) + expect(zone(after, room.id).floor?.footprint).toStartWith('floor_') + expect(bases(after)).toHaveLength(1) +}) + +test('split and merge carry the own flag and height; duplicated room carries its intent', async () => { + const { duplicateZone } = await import('../commands/structure/duplicate-zone') + const s = scene(true) + const id = s.zones[1]!.id + const nodes = toggle(s.nodes, id, true) + const divider = SeparatorNode.parse({ + id: 'separator_own_split', + parentId: s.level.id, + start: [6, 0], + end: [6, 4], + }) + const split = reconcile({ ...nodes, [divider.id]: divider }) + const children = Object.values(split).filter( + (n): n is ZoneNode => n.type === 'zone' && !!n.floor?.footprint, + ) + expect(children).toHaveLength(2) + expect(children.some((room) => room.id === id)).toBe(true) + for (const room of children) expect(room.floor?.footprint).toBe(zone(nodes, id).floor?.footprint) + expect( + floorFootprintName(split, bases(split).find((plate) => plate.zoneIds?.includes(id))!), + ).toBe('Lanai floor') + for (const room of children) expect(getRoomBaseElevation(split, room.id)).toBeCloseTo(-0.4) + delete split[divider.id] + const merged = reconcile(split) + expect( + Object.values(merged).filter((n) => n.type === 'zone' && !!n.floor?.footprint), + ).toHaveLength(1) + const survivor = Object.values(merged).find( + (node): node is ZoneNode => node.type === 'zone' && !!node.floor?.footprint, + )! + expect(survivor.floor?.footprint).toBe(zone(nodes, id).floor?.footprint) + expect(merged[id]).toBeUndefined() + merged[survivor.id] = { ...survivor, name: 'Merged room' } + expect( + floorFootprintName( + merged, + bases(merged).find((plate) => plate.zoneIds?.includes(survivor.id))!, + ), + ).toBe('Merged room floor') + let counter = 0 + const plan = duplicateZone(nodes, { + zoneId: id, + translate: [10, 0], + mintId: (kind) => `${kind}_own_copy_${counter++}`, + }) + expect(plan.conflicts ?? []).toEqual([]) + const copied = reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))) + expect(zone(copied, plan.zoneId).floor?.footprint).toBe(zone(nodes, id).floor?.footprint) + expect(getRoomBaseElevation(copied, plan.zoneId)).toBeCloseTo(-0.4) +}) + +test('infeasible relative height on an own floor refuses clearly; in-app writes are filtered', () => { + const s = scene() + const id = s.zones[1]!.id + const nodes = toggle(s.nodes, id, true) + const patch = { floor: { ...zone(nodes, id).floor, elevation: 4 } } + expect(setZoneIntent(nodes, { zoneId: id, patch }).changes).toEqual([]) + expect(() => assertDerivedNodeWrites(nodes, { update: [{ id, data: patch }] })).toThrow( + 'does not fit', + ) + expect(filterDerivedNodeWrites(nodes, { update: [{ id, data: patch }] }).update).toEqual([]) +}) + +test('upper own plates classify support independently, preserve the soffit and have no foundation', async () => { + const { BuildingNode, LevelNode, SlabNode, ZoneNode } = await import('../schema') + const { floorFootprintSupportClass } = await import('./floor-foundation-datum') + const { reconcileStructureOnLoad } = await import('../utils/reconcile-structure-on-load') + const s = scene(true, 0.03) + const lower = LevelNode.parse({ id: 'level_own_ground', parentId: 'building_own', level: 0 }) + const upper = { ...s.nodes[s.level.id], parentId: 'building_own', level: 1 } as typeof lower + const building = BuildingNode.parse({ id: 'building_own', children: [lower.id, upper.id] }) + const lowerRoom = ZoneNode.parse({ + id: 'zone_own_ground', + name: 'Ground room', + parentId: lower.id, + spaceRole: 'room', + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + }) + const lowerPlate = SlabNode.parse({ + id: 'slab_own_ground', + parentId: lower.id, + plateRole: 'base', + zoneIds: [lowerRoom.id], + polygon: lowerRoom.polygon, + }) + const input = { + ...s.nodes, + [lower.id]: lower, + [upper.id]: upper, + [building.id]: building, + [lowerRoom.id]: lowerRoom, + [lowerPlate.id]: lowerPlate, + } + const nodes = toggle(input, s.zones[1]!.id, true) + const own = bases(nodes).find((p) => p.zoneIds?.includes(s.zones[1]!.id))! + const shared = bases(nodes).find((p) => p.zoneIds?.includes(s.zones[0]!.id))! + expect(floorFootprintSupportClass(nodes, own)).toBe('ground-bearing') + expect(floorFootprintSupportClass(nodes, shared)).toBe('supported') + expect(own.foundation?.type).toBe('none') + expect(own.thickness).toBeCloseTo(0.03) + expect(own.elevation - own.thickness).toBeCloseTo(0) + const loaded = reconcileStructureOnLoad(nodes).nodes + expect(loaded[own.id]).toMatchObject({ elevation: 0.03, thickness: 0.03 }) + let edited = nodes + for (const floorHeight of [0.05, 0.03]) { + const plan = setRoomFloorConstruction(edited, { + zoneId: s.zones[1]!.id, + patch: { floorHeight }, + }) + expect(plan.conflicts ?? []).toEqual([]) + edited = reconcile(applyToScratch(edited, structureChangeBatch(plan.changes))) + expect(edited[own.id]).toMatchObject({ + elevation: floorHeight, + thickness: floorHeight, + foundation: { type: 'none' }, + }) + } + expect(edited).toEqual(nodes) + const bad = { + ...input, + [s.zones[1]!.id]: { ...zone(input, s.zones[1]!.id), floor: { elevation: -0.2 } }, + } + const plan = setZoneIntent(bad, { + zoneId: s.zones[1]!.id, + patch: { floor: { footprint: 'new' } }, + }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]?.message).toContain('Level the floors first') + expect( + filterDerivedNodeWrites(bad, { + update: [{ id: s.zones[1]!.id, data: { floor: { elevation: -0.2, footprint: 'new' } } }], + }).update, + ).toEqual([]) +}) + +test('a floor opening intersects and cuts both own and shared plates', async () => { + const { FloorOpeningNode } = await import('../schema') + const s = scene(true, 0.05) + const nodes = toggle(s.nodes, s.zones[1]!.id, true) + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_own', + parentId: s.level.id, + polygon: [ + [3, 1], + [5, 1], + [5, 3], + [3, 3], + ], + cutsAdjacent: false, + }) + const cut = reconcile({ ...nodes, [opening.id]: opening }) + for (const plate of bases(cut)) + expect(area(intersection(shape(plate), opening.polygon))).toBeCloseTo(0, 5) + expect(bases(cut).reduce((sum, p) => sum + area([shape(p)]), 0)).toBeCloseTo( + bases(nodes).reduce((sum, p) => sum + area([shape(p)]), 0) - 4, + 5, + ) +}) + +test('reattaching after a height edit preserves implicit wall tops with explicit heights', async () => { + const { getWallPlaneTop } = await import('../services/storey') + const { resolveCeilingHeight } = await import('../services/level-height') + const { resolveWallTop } = await import('../systems/wall/wall-top') + const s = scene(true, 0.05) + const id = s.zones[1]!.id + const detached = toggle(s.nodes, id, true) + const plan = setRoomFloorConstruction(detached, { zoneId: id, patch: { floorHeight: 0.3 } }) + expect(plan.conflicts ?? []).toEqual([]) + const raised = reconcile(applyToScratch(detached, structureChangeBatch(plan.changes))) + const joined = toggle(raised, id, false) + for (const old of Object.values(raised)) { + if (old.type !== 'wall') continue + const next = joined[old.id] as typeof old + const top = (wall: typeof old, nodes: Record) => + resolveWallTop( + wall, + getWallPlaneTop(wall, wall.parentId!, nodes), + wallSupportForNodes(wall, nodes).elevation, + ) + expect(top(next, joined)).toBeCloseTo(top(old, raised)) + } + for (const old of Object.values(raised)) { + if (old.type !== 'ceiling') continue + expect(resolveCeilingHeight(joined[old.id] as typeof old, joined)).toBeCloseTo( + resolveCeilingHeight(old, raised), + ) + } + const again = reconcile(joined) + for (const ceiling of Object.values(joined)) { + if (ceiling.type === 'ceiling') + expect(resolveCeilingHeight(again[ceiling.id] as typeof ceiling, again)).toBeCloseTo( + resolveCeilingHeight(ceiling, joined), + ) + } + expect(zone(joined, id).floor?.elevation).toBeCloseTo(0.3) +}) + +test('an upper storey spanning shared and own footprints still requires raising both or neither', async () => { + const { BuildingNode, LevelNode, SlabNode } = await import('../schema') + const s = scene(true, 0.05) + let nodes = toggle(s.nodes, s.zones[1]!.id, true) + const upper = LevelNode.parse({ id: 'level_own_above', parentId: 'building_own_above', level: 1 }) + const building = BuildingNode.parse({ + id: 'building_own_above', + children: [s.level.id, upper.id], + }) + const plate = SlabNode.parse({ + id: 'slab_own_above', + parentId: upper.id, + polygon: [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ], + }) + nodes = { + ...nodes, + [s.level.id]: { ...nodes[s.level.id], parentId: building.id } as AnyNode, + [building.id]: building, + [upper.id]: { ...upper, children: [plate.id] }, + [plate.id]: plate, + } + const plan = setRoomFloorConstruction(nodes, { + zoneId: s.zones[1]!.id, + patch: { floorHeight: 0.3 }, + }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts?.[0]?.message).toContain('raise both or neither') +}) + +test('partition retains a multi-room shared set alongside an own singleton and existing platforms', async () => { + const { doorwayStepsFixture } = await import('../systems/slab/__fixtures__/doorway-steps') + const before = doorwayStepsFixture([0.05, 0.3, 0.05]) + const nodes = toggle(before, 'zone_c', true) + expect( + bases(nodes) + .map((plate) => plate.zoneIds!.slice().sort()) + .sort(), + ).toEqual([['zone_a', 'zone_b'], ['zone_c']]) + const platform = Object.values(nodes).find( + (n): n is SlabNode => n.type === 'slab' && n.plateRole === 'platform', + )! + expect(platform.zoneIds).toEqual(['zone_b']) + expect(platform.elevation).toBe(0.3) + expect( + floorFootprintName(nodes, bases(nodes).find((plate) => plate.zoneIds!.length === 2)!), + ).toBe('Shared floor') +}) + +test('conversion preserves explicit wall tops as their plate support changes', async () => { + const { resolveWallTop } = await import('../systems/wall/wall-top') + const s = scene() + const id = s.zones[1]!.id + const wall = { ...s.walls[1]!, height: 2.6 } + const before = { ...s.nodes, [wall.id]: wall } + const top = (nodes: Record) => + resolveWallTop( + nodes[wall.id] as typeof wall, + 3, + wallSupportForNodes(nodes[wall.id] as typeof wall, nodes).elevation, + ) + const detached = toggle(before, id, true) + expect(top(detached)).toBeCloseTo(top(before)) + const attached = toggle(detached, id, false) + expect(top(attached)).toBeCloseTo(top(before)) + expect((attached[wall.id] as typeof wall).height).toBeCloseTo(wall.height) +}) + +test('touching rooms join a key into one named plate and retain raised and sunken room tops', () => { + const s = scene(true, -0.2) + const id = s.zones[1]!.id + const keyed = toggle(s.nodes, id, true) + const key = zone(keyed, id).floor!.footprint! + const ownId = bases(keyed).find((plate) => plate.zoneIds?.includes(id))!.id + const plan = setZoneIntent(keyed, { + zoneId: s.zones[0]!.id, + patch: { floor: { footprint: key } }, + }) + expect(plan.conflicts ?? []).toEqual([]) + const joined = reconcile(applyToScratch(keyed, structureChangeBatch(plan.changes))) + expect(bases(joined)).toHaveLength(1) + expect(bases(joined)[0]!.id).toBe(ownId) + expect(bases(joined)[0]!.zoneIds?.slice().sort()).toEqual(s.zones.map((room) => room.id).sort()) + expect(bases(joined)[0]!.elevation).toBeCloseTo(-0.2) + expect(zone(joined, s.zones[0]!.id).floor?.elevation).toBeCloseTo(0.05) + expect(floorFootprintName(joined, bases(joined)[0]!)).not.toBe('Shared floor') + for (const elevation of [0.3, -0.3]) { + const raised = setZoneIntent(joined, { zoneId: id, patch: { floor: { elevation } } }) + expect(raised.conflicts ?? []).toEqual([]) + const next = reconcile(applyToScratch(joined, structureChangeBatch(raised.changes))) + expect(zone(next, id).floor?.elevation).toBe(elevation) + expect(bases(next)[0]!.elevation).toBeCloseTo(-0.2) + expect(bases(reconcile(next))).toEqual(bases(next)) + } +}) + +test('disconnected pieces of a key have stable component IDs and synchronized construction', async () => { + const { duplicateZone } = await import('../commands/structure/duplicate-zone') + const s = scene(true, 0.05) + const id = s.zones[1]!.id + let nodes = toggle(s.nodes, id, true) + let count = 0 + const copy = duplicateZone(nodes, { + zoneId: id, + translate: [10, 0], + mintId: (kind) => `${kind}_key_copy_${count++}`, + }) + nodes = reconcile(applyToScratch(nodes, structureChangeBatch(copy.changes))) + const key = zone(nodes, id).floor!.footprint! + const pieces = bases(nodes).filter((p) => + p.zoneIds?.some((id) => zone(nodes, id).floor?.footprint === key), + ) + expect(pieces).toHaveLength(2) + expect(pieces.map((p) => p.id).sort()).toEqual( + [0, 1].map((i) => keyedFloorPlateId(s.level.id, key, i)).sort(), + ) + const edit = setRoomFloorConstruction(nodes, { + zoneId: id, + patch: { + floorHeight: 0.2, + thickness: 0.12, + foundation: { type: 'solid', material: 'library:red' }, + slots: { edge: 'library:blue' }, + }, + }) + expect(edit.conflicts ?? []).toEqual([]) + const next = reconcile(applyToScratch(nodes, structureChangeBatch(edit.changes))) + for (const piece of pieces) + expect(next[piece.id]).toMatchObject({ + elevation: 0.2, + thickness: 0.12, + foundation: { type: 'solid', material: 'library:red' }, + slots: { edge: 'library:blue' }, + }) +}) + +test('floor choices expose current and touching keys, exclude distant floors, and flag drawn and mezzanine supports', async () => { + const { roomFloorChoices } = await import('./room-floor-choices') + const { SlabNode } = await import('../schema') + const s = scene(true, 0.05) + const id = s.zones[1]!.id + const nodes = toggle(s.nodes, id, true) + const choices = roomFloorChoices(nodes, id) + expect(choices).toHaveLength(2) + expect(choices[0]).toMatchObject({ + key: zone(nodes, id).floor!.footprint, + current: true, + name: 'Lanai floor', + }) + expect(choices[1]).toMatchObject({ key: null, current: false }) + const slab = SlabNode.parse({ parentId: s.level.id, polygon: zone(nodes, id).polygon }) + const drawn = { + ...nodes, + [slab.id]: slab, + [id]: { ...zone(nodes, id), floor: { sourceSlabId: slab.id } }, + } + expect(roomFloorChoices(drawn, id).find((choice) => choice.current)).toMatchObject({ + plateId: slab.id, + drawn: true, + }) + const mezz = { ...zone(nodes, id), floor: { support: 'open' as const, elevation: 1.5 } } + const deck = { ...slab, support: 'open' as const, zoneIds: [id] } + expect(roomFloorChoices({ [id]: mezz, [deck.id]: deck }, id)[0]).toMatchObject({ + current: true, + mezzanine: true, + }) +}) + +test('joining an existing floor preserves world tops and is one undo step', () => { + const s = scene(true, -0.2) + const id = s.zones[1]!.id + const nodes = toggle(s.nodes, id, true) + useScene.setState({ + nodes, + rootNodeIds: [s.level.id], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + useScene.temporal.getState().resume() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) + clearSceneHistory() + const before = useScene.getState().nodes + const plan = setZoneIntent(before, { + zoneId: s.zones[0]!.id, + patch: { floor: { footprint: zone(nodes, id).floor!.footprint! } }, + }) + expect(plan.conflicts ?? []).toEqual([]) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + const after = useScene.getState().nodes + expect(bases(after)).toHaveLength(1) + expect(zone(after, s.zones[0]!.id).floor?.elevation).toBeCloseTo(0.05) + expect(getRoomBaseElevation(after, id)).toBeCloseTo(-0.2) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) +}) + +test('wall ownership ties use the lowest key, independently of room IDs', () => { + const s = scene(false, 0.05) + const keys = ['floor_z', 'floor_a'] + for (const [i, room] of s.zones.entries()) + s.nodes[room.id] = { ...zone(s.nodes, room.id), floor: { footprint: keys[i], elevation: 0.05 } } + const nodes = reconcile(s.nodes) + expect(bases(nodes)).toHaveLength(2) + const winner = bases(nodes).find((plate) => plate.zoneIds?.includes(s.zones[1]!.id))! + expect(containsPoint([shape(winner)], [4, 1])).toBe(true) +}) + +test('level duplication mints a fresh key, keeps its groups and preserves keyed construction', async () => { + const { cloneLevelSubtree } = await import('../utils/clone-scene-graph') + const s = scene(true, -0.2) + const id = s.zones[1]!.id + const nodes = toggle(s.nodes, id, true) + const copy = cloneLevelSubtree(nodes, s.level.id) + const copiedRoom = copy.clonedNodes.find((node) => node.id === copy.idMap.get(id)) as ZoneNode + expect(copiedRoom.floor?.footprint).toStartWith('floor_') + expect(copiedRoom.floor?.footprint).not.toBe(zone(nodes, id).floor?.footprint) + const copied = reconcile({ + ...nodes, + ...Object.fromEntries(copy.clonedNodes.map((node) => [node.id, node])), + }) + expect(getRoomBaseElevation(copied, copiedRoom.id)).toBeCloseTo(-0.2) + expect(bases(copied).find((plate) => plate.zoneIds?.includes(copiedRoom.id))!.id).toBe( + keyedFloorPlateId(copy.newLevelId, copiedRoom.floor!.footprint!), + ) +}) + +test('clearing a keyed construction height restores its resting floor top', () => { + const s = scene(true, 0.05) + const id = s.zones[1]!.id + let nodes = toggle(s.nodes, id, true) + for (const floorHeight of [0.3, null]) { + const plan = setRoomFloorConstruction(nodes, { zoneId: id, patch: { floorHeight } }) + expect(plan.conflicts ?? []).toEqual([]) + nodes = reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))) + expect(getRoomBaseElevation(nodes, id)).toBeCloseTo(floorHeight ?? 0.05) + } +}) + +test('leaving a multi-room key preserves the remaining rooms and construction', () => { + const s = scene(true, -0.2) + const id = s.zones[1]!.id + let nodes = toggle(s.nodes, id, true) + const key = zone(nodes, id).floor!.footprint! + const join = setZoneIntent(nodes, { + zoneId: s.zones[0]!.id, + patch: { floor: { footprint: key } }, + }) + nodes = reconcile(applyToScratch(nodes, structureChangeBatch(join.changes))) + const before = getRoomBaseElevation(nodes, id) + const left = toggle(nodes, s.zones[0]!.id, false) + expect(getRoomBaseElevation(left, id)).toBeCloseTo(before) + expect(zone(left, id).floor?.footprint).toBe(key) + expect( + zone(left, s.zones[0]!.id).floor?.elevation ?? getRoomBaseElevation(left, s.zones[0]!.id), + ).toBeCloseTo(0.05) + expect(bases(left)).toHaveLength(2) +}) + +test('Wawa-shaped sunken Lanai round-trips exterior doors and windows through an ordinary own key', () => { + const s = scene(false, -0.1) + const exterior = s.walls[1]! + const door = DoorNode.parse({ + parentId: exterior.id, + wallId: exterior.id, + position: [1, 1.2, 0], + height: 2.4, + }) + const window = WindowNode.parse({ + parentId: exterior.id, + wallId: exterior.id, + position: [3, 1.6, 0], + height: 0.6, + }) + const before = reconcile({ + ...s.nodes, + [exterior.id]: { ...exterior, children: [door.id, window.id] }, + [door.id]: door, + [window.id]: window, + }) + const world = (nodes: Record) => + [door, window].map((opening) => { + const current = nodes[opening.id] as typeof opening + const wall = nodes[exterior.id] as typeof exterior + return { ...getOpeningWallCut(wall, current, nodes), datum: undefined } + }) + let detached = toggle(before, s.zones[1]!.id, true) + expect(world(detached)).toEqual(world(before)) + // Load the literal persisted key through the same derivation as any other string. + const id = s.zones[1]!.id + detached = reconcile({ + ...detached, + [id]: { ...zone(detached, id), floor: { footprint: 'own', elevation: -0.1 } }, + }) + expect(zone(detached, id).floor?.footprint).toBe('own') + const attached = toggle(detached, id, false) + expect(world(attached)).toEqual(world(before)) + expect(zone(attached, id).floor?.elevation).toBeCloseTo(-0.1) +}) + +test.each([ + undefined, + 2.5, +])('ceiling edge slivers do not carry the adjacent floor (height=%s)', (height) => { + const s = scene(false, -0.1) + const id = s.zones[1]!.id + const detached = toggle(s.nodes, id, true) + const ceiling = CeilingNode.parse({ + parentId: s.level.id, + height, + polygon: [ + [0, 0], + [4.12, 0], + [4.12, 4], + [0, 4], + ], + }) + const nodes = { ...detached, [ceiling.id]: ceiling } + const own = bases(nodes).find((p) => p.zoneIds?.includes(id))! + const shared = bases(nodes).find((p) => !p.zoneIds?.includes(id))! + expect(footprintSupportsNode(own, ceiling, nodes)).toBe(false) + expect(footprintSupportsNode(shared, ceiling, nodes)).toBe(true) + const plan = setRoomFloorConstruction(nodes, { zoneId: id, patch: { floorHeight: -0.05 } }) + expect(plan.conflicts ?? []).toEqual([]) + expect(plan.changes.some((p) => p.op === 'update' && p.id === ceiling.id)).toBe(false) + const spanning = { + ...ceiling, + polygon: [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ] as [number, number][], + } + const refused = setRoomFloorConstruction( + { ...nodes, [ceiling.id]: spanning }, + { zoneId: id, patch: { floorHeight: -0.05 } }, + ) + expect(refused.conflicts?.[0]?.message).toContain('raise both or neither') +}) + +test('keyed plates stay ground-bearing on their foundation; solid only while raised', () => { + const s = scene(true, -0.1) + const id = s.zones[1]!.id + let nodes = toggle(s.nodes, id, true) + for (const foundationHeight of [0.2, 0, 0.05, 0]) { + const plan = setRoomFloorConstruction(nodes, { zoneId: id, patch: { foundationHeight } }) + expect(plan.conflicts ?? []).toEqual([]) + nodes = reconcile(applyToScratch(nodes, structureChangeBatch(plan.changes))) + const plate = bases(nodes).find((p) => p.zoneIds?.includes(id))! + const { grade } = groundFloorConstruction(nodes, plate) + expect(plate.elevation).toBeCloseTo(grade + foundationHeight + plate.thickness) + expect(floorFootprintSupportClass(nodes, plate)).toBe('ground-bearing') + expect(plate.foundation?.type).toBe(foundationHeight > 0 ? 'solid' : 'none') + } +}) diff --git a/packages/core/src/lib/plate-corpus.test.ts b/packages/core/src/lib/plate-corpus.test.ts new file mode 100644 index 0000000000..cf30d4eff8 --- /dev/null +++ b/packages/core/src/lib/plate-corpus.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { WallNode } from '../schema' +import { getWallCurveFrameAt } from '../systems/wall/wall-curve' +import { getWallFaceOffsets } from '../systems/wall/wall-frame' +import { plateFootprint } from './level-footprints' +import { area, containsPoint, difference, union } from './polygon-boolean' +import { createRoomTopologyIndex } from './space-detection' + +const cases = [ + { id: 'scene-02', rooms: 8, group: [2] }, + { id: 'scene-14', rooms: 3, group: [0, 1, 2] }, + { id: 'scene-15', rooms: 5, group: [0] }, + { id: 'scene-18', rooms: 28, group: [10] }, + { id: 'scene-28', rooms: 7, group: [4, 6] }, +] + +describe('production plate union regressions', () => { + test.each(cases)('$id preserves the union of room faces', ({ id, rooms: count, group }) => { + const coordinates = JSON.parse( + readFileSync(new URL(`./__fixtures__/plate-corpus/${id}.json`, import.meta.url), 'utf8'), + ) as Partial[] + const walls = coordinates.map((geometry, i) => + WallNode.parse({ ...geometry, id: `wall_${i}`, parentId: 'level_fixture' }), + ) + const index = createRoomTopologyIndex() + index.rebuild(Object.fromEntries(walls.map((wall) => [wall.id, wall]))) + const rooms = index.getLevelTopology('level_fixture')!.rooms + expect(rooms).toHaveLength(count) + const members = group.map((i) => rooms[i]!) + const faces = union(members.map((room) => ({ outer: room.polygon, holes: room.holes }))) + expect(area(faces)).toBeGreaterThan(0) + const plate = plateFootprint(members) + expect(plate.length).toBeGreaterThan(0) + expect(area(plate)).toBeGreaterThanOrEqual(area(faces)) + const boundaryIds = new Set( + members.flatMap((room) => + room.spans.filter((span) => span.kind === 'wall').map((span) => span.boundaryId), + ), + ) + for (const wallId of boundaryIds) { + const footprint = members[0]!.context.wallFootprints.get(wallId)! + const wall = walls.find((wall) => wall.id === wallId)! + const { a, b } = getWallFaceOffsets(wall) + const spans = members.flatMap((room) => + room.spans.filter((span) => span.boundaryId === wallId), + ) + if (spans.some((span) => span.t0 === 0 && span.t1 === 1)) + expect(area(difference(footprint, plate, { throwOnError: true })), wallId).toBeLessThan( + 1e-6, + ) + for (const span of spans) + for (let i = 1; i < 32; i++) { + const { point, normal } = getWallCurveFrameAt( + wall, + span.t0 + ((span.t1 - span.t0) * i) / 32, + ) + for (const offset of [a * 0.99, 0, b * 0.99]) { + const probe: [number, number] = [ + point.x + normal.x * offset, + point.y + normal.y * offset, + ] + if (containsPoint([{ outer: footprint, holes: [] }], probe)) + expect(containsPoint(plate, probe), wallId).toBe(true) + } + } + } + if (id === 'scene-28') expect(containsPoint(plate, [1.2, 4.86])).toBe(true) + expect(plateFootprint([...members].reverse())).toBe(plate) + }) +}) diff --git a/packages/core/src/lib/plate-recovery.test.ts b/packages/core/src/lib/plate-recovery.test.ts new file mode 100644 index 0000000000..7af16b510f --- /dev/null +++ b/packages/core/src/lib/plate-recovery.test.ts @@ -0,0 +1,83 @@ +import { expect, spyOn, test } from 'bun:test' +import clipping from 'polygon-clipping' +import { WallNode } from '../schema' +import { getWallFaceLine } from '../systems/wall/wall-frame' +import { plateFootprint } from './level-footprints' +import { area, containsPoint, difference, type Ring } from './polygon-boolean' +import type { TopologyRoom } from './room-topology-index' + +function fixture(justification?: 'a' | 'b') { + const wall = WallNode.parse({ + id: 'wall_recovery', + parentId: 'level_recovery', + start: [0, 0], + end: [2, 0], + thickness: 0.2, + justification, + }) + const a = getWallFaceLine(wall, 'a') + const b = getWallFaceLine(wall, 'b') + const polygon = [a.start, b.start, b.end, a.end].map(({ x, y }): [number, number] => [x, y]) + const footprints = new Map([[wall.id, polygon]]) + const room: TopologyRoom = { + id: 'room_recovery', + polygon: [ + [0, 0], + [2, 0], + [2, 2], + [0, 2], + ], + holes: [], + context: { revision: 1, walls: new Map([[wall.id, wall]]), wallFootprints: footprints }, + spans: [ + { roomId: 'room_recovery', boundaryId: wall.id, kind: 'wall', face: 'a', t0: 0, t1: 1 }, + ], + } + return { room, wall, footprints, polygon } +} + +test.each([ + { name: 'self-union', failures: [1, 3], justification: undefined }, + { name: 'centred raw rectangle', failures: [1, 3, 5], justification: undefined }, + { name: 'a-justified raw rectangle', failures: [1, 3, 5], justification: 'a' as const }, + { name: 'b-justified raw rectangle', failures: [1, 3, 5], justification: 'b' as const }, +])('$name preserves boundary coverage after clipping failures', ({ failures, justification }) => { + const { room, wall, polygon } = fixture(justification) + const originalUnion = clipping.union + let calls = 0 + const clip = spyOn(clipping, 'union').mockImplementation((...inputs) => { + calls += 1 + if (failures.includes(calls)) throw new Error('Clipping failure') + return originalUnion(...inputs) + }) + const warn = spyOn(console, 'warn').mockImplementation(() => {}) + try { + const plate = plateFootprint([room]) + expect(area(difference(polygon, plate, { throwOnError: true }))).toBeLessThan(1e-6) + expect(containsPoint(plate, [1, 1])).toBe(true) + expect(plateFootprint([room])).toBe(plate) + } finally { + clip.mockRestore() + warn.mockRestore() + } +}) + +test('an unverifiable footprint cannot cache an incomplete plate', () => { + const { room, wall, footprints, polygon } = fixture() + const invalid: Ring = [ + [Number.NaN, 0], + [1, 0], + [1, 1], + ] + footprints.set(wall.id, invalid) + const warn = spyOn(console, 'warn').mockImplementation(() => {}) + try { + expect(() => plateFootprint([room])).toThrow('wall_recovery on level level_recovery') + footprints.set(wall.id, polygon) + const plate = plateFootprint([room]) + expect(area(difference(polygon, plate, { throwOnError: true }))).toBeLessThan(1e-6) + expect(containsPoint(plate, [1, -0.05])).toBe(true) + } finally { + warn.mockRestore() + } +}) diff --git a/packages/core/src/lib/plate-reference.test.ts b/packages/core/src/lib/plate-reference.test.ts new file mode 100644 index 0000000000..ae67de0829 --- /dev/null +++ b/packages/core/src/lib/plate-reference.test.ts @@ -0,0 +1,66 @@ +import { expect, test } from 'bun:test' +import { BlockNode, ItemNode, ShelfNode, SlabNode, StairNode, StairSegmentNode } from '../schema' +import { replacementPlateFor } from './plate-reference' + +const slab = (id: string, x: number, z: number, elevation: number, parentId = 'level_test') => + SlabNode.parse({ + id, + parentId, + polygon: [ + [x, z], + [x + 2, z], + [x + 2, z + 2], + [x, z + 2], + ], + elevation, + }) + +test('a straddling item remaps by its rotated footprint even when its centre is off the upper plate', () => { + const lower = slab('slab_lower', -1, -1, 0.05) + const upper = slab('slab_upper', 1, -1, 0.55) + const item = ItemNode.parse({ + position: [0.9, 0, 0], + rotation: [0, Math.PI / 4, 0], + asset: { + id: 'test', + name: 'Test', + category: 'test', + thumbnail: '', + src: 'asset://test', + dimensions: [1, 1, 1], + }, + }) + item.parentId = 'level_test' + expect(replacementPlateFor(item, 'supportSlabId', [lower, upper], {})).toBe(upper.id) +}) + +test('a retired stair deck remaps at the last flight arrival on the original destination level', () => { + const old = slab('slab_old', -1, -1, 1.5, 'level_upper') + const arrival = slab('slab_arrival', -1, 3.5, 1.5, 'level_upper') + const nearStart = slab('slab_start', -1, -1, 1.5, 'level_upper') + const stair = StairNode.parse({ + id: 'stair_test', + parentId: 'level_lower', + stairType: 'straight', + deckSlabId: old.id, + }) + const segment = StairSegmentNode.parse({ id: 'sseg_test', parentId: stair.id, length: 4 }) + stair.children = [segment.id] + const nodes = { [stair.id]: stair, [segment.id]: segment, [old.id]: old } + expect(replacementPlateFor(stair, 'deckSlabId', [nearStart, arrival], nodes)).toBe(arrival.id) + expect(replacementPlateFor(stair, 'deckSlabId', [nearStart], nodes)).toBeUndefined() +}) + +test('parametric furniture and topology blocks remap by their bodies across a plate boundary', () => { + const upper = slab('slab_upper', 1, -1, 0.55) + const lower = slab('slab_lower', -1, -1, 0.05) + const shelf = ShelfNode.parse({ + parentId: 'level_test', + position: [0.9, 0, 0], + width: 1, + depth: 1, + }) + const block = BlockNode.parse({ parentId: 'level_test', position: [0.9, 0, 0] }) + expect(replacementPlateFor(shelf, 'supportSlabId', [lower, upper], {})).toBe(upper.id) + expect(replacementPlateFor(block, 'supportSlabId', [lower, upper], {})).toBe(upper.id) +}) diff --git a/packages/core/src/lib/plate-reference.ts b/packages/core/src/lib/plate-reference.ts new file mode 100644 index 0000000000..80fa2bf444 --- /dev/null +++ b/packages/core/src/lib/plate-reference.ts @@ -0,0 +1,130 @@ +import { proceduralFootprint } from '../procedural-items/query' +import type { AnyNode, SlabNode } from '../schema' +import { getFenceCenterlineFrameAt } from '../systems/fence/fence-centerline' +import { getStairFloorPlacedFootprints } from '../systems/stair/stair-floor-footprints' +import { stairArrivalOpening } from '../systems/stair/stair-footprint' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { planFootprintCorners } from './plan-footprint' +import { + area, + containsPoint, + intersection, + type MultiPolygon, + type Ring, + union, +} from './polygon-boolean' + +export function replacementPlateFor( + node: AnyNode, + field: 'supportSlabId' | 'deckSlabId', + plates: readonly SlabNode[], + nodes: Readonly>, +): string | undefined { + let footprint: Ring | MultiPolygon = [] + let point: [number, number] | undefined + if (field === 'deckSlabId' && node.type === 'stair') { + if (!node.position || !node.children) return undefined + const arrival = stairArrivalOpening(node, nodes) + if (arrival.length) + point = [ + arrival.reduce((s, p) => s + p[0], 0) / arrival.length, + arrival.reduce((s, p) => s + p[1], 0) / arrival.length, + ] + } else if (node.type === 'item') { + footprint = planFootprintCorners( + node.position, + node.asset.dimensions.map((v, i) => v * node.scale[i]!) as [number, number, number], + node.rotation[1], + ) + } else if (node.type === 'procedural-item') { + const box = proceduralFootprint(node) + footprint = planFootprintCorners(box.position, box.dimensions, box.rotation[1]) + } else if (node.type === 'stair') { + footprint = union( + getStairFloorPlacedFootprints(node, nodes).map((box) => + planFootprintCorners(box.position ?? node.position, box.dimensions, box.rotation[1]), + ), + ) + } else if (node.type === 'block') { + const positions = node.topology.vertices.map((vertex) => vertex.position) + if (positions.length) { + const minX = Math.min(...positions.map((p) => p[0])), + maxX = Math.max(...positions.map((p) => p[0])) + const minZ = Math.min(...positions.map((p) => p[2])), + maxZ = Math.max(...positions.map((p) => p[2])) + const x = (minX + maxX) / 2, + z = (minZ + maxZ) / 2 + footprint = planFootprintCorners( + [ + node.position[0] + x * Math.cos(node.rotation) + z * Math.sin(node.rotation), + node.position[1], + node.position[2] - x * Math.sin(node.rotation) + z * Math.cos(node.rotation), + ], + [maxX - minX, 0, maxZ - minZ], + node.rotation, + ) + } + } else if (node.type === 'fence') { + const sides = [1, -1].map((sign) => + Array.from({ length: 97 }, (_, i): [number, number] => { + const frame = getFenceCenterlineFrameAt(node, i / 96) + return [ + frame.point.x + (sign * frame.normal.x * node.thickness) / 2, + frame.point.y + (sign * frame.normal.y * node.thickness) / 2, + ] + }), + ) + footprint = [...sides[0]!, ...sides[1]!.reverse()] + } else if (node.type === 'wall') { + const walls = Object.values(nodes).filter( + (candidate): candidate is typeof node => + candidate.type === 'wall' && candidate.parentId === node.parentId, + ) + footprint = getWallPlanFootprint(node, calculateLevelMiters(walls)).map( + (point): [number, number] => [point.x, point.y], + ) + } else if ('polygon' in node && Array.isArray(node.polygon)) footprint = node.polygon as Ring + else if ('position' in node && Array.isArray(node.position)) { + const rotation = + 'rotation' in node ? (Array.isArray(node.rotation) ? node.rotation[1] : node.rotation) : 0 + if ( + 'width' in node && + 'depth' in node && + typeof node.width === 'number' && + typeof node.depth === 'number' + ) + footprint = planFootprintCorners( + node.position as [number, number, number], + [node.width, 0, node.depth], + typeof rotation === 'number' ? rotation : 0, + ) + else point = [node.position[0], node.position[2]] + } + return plates + .filter( + (plate) => + plate.parentId === + (field === 'deckSlabId' && 'deckSlabId' in node + ? (nodes[node.deckSlabId ?? '']?.parentId ?? node.parentId) + : node.parentId) && + (node.type !== 'wall' || + (plate.support !== 'open' && + plate.plateRole !== 'platform' && + plate.plateRole !== 'sunken')), + ) + .map((plate) => ({ + plate, + overlap: point + ? Number(containsPoint([{ outer: plate.polygon, holes: plate.holes }], point)) + : footprint.length + ? area(intersection(footprint, { outer: plate.polygon, holes: plate.holes })) + : 0, + })) + .filter((p) => p.overlap > 0) + .sort( + (a, b) => + b.plate.elevation - a.plate.elevation || + b.overlap - a.overlap || + a.plate.id.localeCompare(b.plate.id), + )[0]?.plate.id +} diff --git a/packages/core/src/lib/plate-riser-ownership.test.ts b/packages/core/src/lib/plate-riser-ownership.test.ts new file mode 100644 index 0000000000..c3e0a0b16c --- /dev/null +++ b/packages/core/src/lib/plate-riser-ownership.test.ts @@ -0,0 +1,62 @@ +import { expect, test } from 'bun:test' +import { type AnyNode, SeparatorNode, type SlabNode } from '../schema' +import { floorStepFixture } from '../systems/slab/__fixtures__/floor-step' +import { reconcileStructureWithStableIds } from '../utils/structure-id' +import { computePlateSurfacePartition, plateLevelContext } from './plate-surface' + +// Step paint scope (UX round §7, Wassim §13 Q4): the room you step down from +// owns the step, whatever stands between the two rooms. A riser left without +// an owner would fall back to the plate-wide `riser` finish, so one room's +// step paint would repaint every such step of the footprint. + +type Between = 'door' | 'wall' | 'separator' + +function upperAndSunkRoom(between: Between) { + const f = floorStepFixture() + const nodes: Record = Object.fromEntries( + Object.entries(f.nodes).filter(([, n]) => n.type !== 'slab' && n.type !== 'door'), + ) + const level = f.level + let children = level.children.filter((id) => nodes[id]) + if (between === 'door') { + nodes[f.door.id] = f.door + nodes[f.divider.id] = { ...f.divider, children: [f.door.id] } + } else if (between === 'wall') { + nodes[f.divider.id] = { ...f.divider, children: [] } + } else { + delete nodes[f.divider.id] + const separator = SeparatorNode.parse({ + start: f.divider.start, + end: f.divider.end, + parentId: level.id, + }) + nodes[separator.id] = separator + children = [...children.filter((id) => id !== f.divider.id), separator.id] + } + nodes[level.id] = { ...level, height: 3, children } + for (const [i, zone] of f.zones.entries()) + nodes[zone.id] = { ...zone, floor: { elevation: i ? -0.4 : 0.05 } } + const reconciled = reconcileStructureWithStableIds({ nodes }).nodes + const base = Object.values(reconciled).find( + (n): n is SlabNode => n.type === 'slab' && n.plateRole === 'base', + )! + const sides = computePlateSurfacePartition( + base, + plateLevelContext(reconciled[level.id]!, (id) => reconciled[id]), + )!.sides + return { upper: f.zones[0]!.id, sides } +} + +test.each([ + 'door', + 'wall', + 'separator', +] as const)('every step down into a sunken room across a %s is the upper room’s', (between) => { + const { upper, sides } = upperAndSunkRoom(between) + const risers = sides.filter((side) => side.role === 'riser') + // A plain wall covers its drop down to the sunken floor: nothing to paint. + expect(risers.length > 0).toBe(between !== 'wall') + expect(risers.every((side) => side.zoneId === upper)).toBe(true) + // Only the footprint's exterior band stays the plate's own. + expect(sides.filter((side) => side.role === 'edge').every((side) => !side.zoneId)).toBe(true) +}) diff --git a/packages/core/src/lib/plate-step.test.ts b/packages/core/src/lib/plate-step.test.ts new file mode 100644 index 0000000000..d760c7b8fa --- /dev/null +++ b/packages/core/src/lib/plate-step.test.ts @@ -0,0 +1,145 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { type AnyNode, SlabNode, WallNode, ZoneNode } from '../schema' +import { floorStepFixture } from '../systems/slab/__fixtures__/floor-step' +import { + computePlateSurfacePartition, + type PlateLevelContext, + plateLevelContext, + platePartitionSignature, + plateSideRuns, +} from './plate-surface' + +const rect = (x0: number, z0: number, x1: number, z1: number): [number, number][] => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], +] +const plate = (polygon: [number, number][], elevation: number, holes: [number, number][][] = []) => + SlabNode.parse({ boundary: 'auto', polygon, elevation, thickness: 0.05, holes }) +const context = (slabs: SlabNode[]): PlateLevelContext => ({ walls: [], zones: [], slabs }) + +function fixture() { + const { nodes } = JSON.parse( + readFileSync( + new URL('../../../nodes/src/slab/__fixtures__/sunken-pit-scene.json', import.meta.url), + 'utf8', + ), + ) as { nodes: Record } + const host = SlabNode.parse(nodes.slab_2wetb55oie8qzyhb) + return { host, ctx: plateLevelContext(nodes[host.parentId!]!, (id) => nodes[id]) } +} + +test('sunken fixture: every hole interval carries the lower plate top', () => { + const { host, ctx } = fixture() + const sides = computePlateSurfacePartition(host, ctx)!.sides.filter( + (side) => side.role === 'riser', + ) + expect(sides).toHaveLength(6) + for (const side of sides) expect(side.dropTo).toBeCloseTo(-0.5957, 4) +}) + +test('straight separator splits risers where the lower neighbour changes height', () => { + const upper = plate(rect(0, 0, 4, 4), 0.05) + const lower = plate(rect(4, 0, 8, 2), -0.6) + const deeper = plate(rect(4, 2, 8, 4), -1.2) + const partition = computePlateSurfacePartition(upper, context([upper, lower, deeper]))! + expect(plateSideRuns(partition, [4, 0], [4, 4])).toEqual([ + { t0: 0, t1: 0.5, role: 'riser', dropTo: -0.6 }, + { t0: 0.5, t1: 1, role: 'riser', dropTo: -1.2 }, + ]) +}) + +test('nested pits stop at their immediate lower neighbour', () => { + const outer = plate(rect(0, 0, 8, 8), 0.05, [rect(1, 1, 7, 7)]) + const middle = plate(rect(1, 1, 7, 7), -0.6, [rect(2, 2, 6, 6)]) + const inner = plate(rect(2, 2, 6, 6), -1.2) + const ctx = context([outer, middle, inner]) + for (const [host, dropTo] of [ + [outer, -0.6], + [middle, -1.2], + ] as const) { + const risers = computePlateSurfacePartition(host, ctx)!.sides.filter((s) => s.role === 'riser') + expect(risers).toHaveLength(4) + expect(risers.every((s) => s.dropTo === dropTo)).toBe(true) + } +}) + +test('fully wall-covered pit intervals stay hidden without drop faces', () => { + const hole = rect(1, 1, 3, 3) + const host = plate(rect(0, 0, 4, 4), 0.05, [hole]) + const lower = plate(hole, -0.6) + const ctx = context([host, lower]) + ctx.walls = hole.map((start, i) => + WallNode.parse({ start, end: hole[(i + 1) % hole.length], thickness: 0.2 }), + ) + const sides = computePlateSurfacePartition(host, ctx)!.sides + expect(sides.filter((s) => s.role === 'riser')).toHaveLength(0) + const hidden = sides.filter((s) => s.role === 'hidden') + expect(hidden.length).toBeGreaterThanOrEqual(4) + expect(hidden.every((s) => s.dropTo === undefined)).toBe(true) +}) + +test('open-below holes and rooms without a plate have no drop target', () => { + const hole = rect(1, 1, 3, 3) + const host = plate(rect(0, 0, 4, 4), 0.05, [hole]) + const ctx = context([host]) + ctx.zones = [ + ZoneNode.parse({ + name: 'Open room', + spaceRole: 'room', + polygon: hole, + floor: { elevation: -0.6 }, + }), + ] + const risers = computePlateSurfacePartition(host, ctx)!.sides.filter((s) => s.role === 'riser') + expect(risers).toHaveLength(4) + expect(risers.every((s) => s.dropTo === undefined)).toBe(true) + expect( + computePlateSurfacePartition({ ...host, support: 'open' }, ctx)!.sides.every( + (s) => s.dropTo === undefined, + ), + ).toBe(true) +}) + +test('neighbour elevation edits invalidate the cached drop target', () => { + const { host, ctx } = fixture() + const before = computePlateSurfacePartition(host, ctx)! + const changed = { + ...ctx, + slabs: ctx.slabs.map((s) => (s.id === 'slab_m7byobc8mtx1apva' ? { ...s, elevation: -0.8 } : s)), + } + expect(platePartitionSignature(host, changed)).not.toBe(platePartitionSignature(host, ctx)) + const after = computePlateSurfacePartition(host, changed)! + expect(after).not.toBe(before) + expect(after.sides.filter((s) => s.role === 'riser').every((s) => s.dropTo === -0.8)).toBe(true) +}) + +test('two rooms divided by a straight separator carry the sunken floor target', () => { + const { slabs, nodes, level, zones } = floorStepFixture(true) + const host = { ...slabs[0]!, thickness: 0.05 } + const ctx = plateLevelContext(level, (id) => (id === host.id ? host : nodes[id])) + const partition = computePlateSurfacePartition(host, ctx)! + const runs = plateSideRuns(partition, [4, 0.2], [4, 3.8]) + expect(runs).toEqual([{ t0: 0, t1: 1, role: 'riser', dropTo: -0.4, zoneId: zones[0]!.id }]) +}) + +test('mezzanines do not shorten step drops and support changes invalidate the partition', () => { + const host = plate(rect(0, 0, 4, 4), 2) + const floor = plate(rect(4, 0, 8, 4), 0.05) + const neighbour = plate(rect(4, 0, 8, 4), 1.3) + const solid = context([host, floor, neighbour]) + const open = context([host, floor, { ...neighbour, support: 'open' }]) + const before = computePlateSurfacePartition(host, solid)! + expect(plateSideRuns(before, [4, 0], [4, 4])[0]!.dropTo).toBe(1.3) + expect(platePartitionSignature(host, open)).not.toBe(platePartitionSignature(host, solid)) + const after = computePlateSurfacePartition(host, open)! + expect(after).not.toBe(before) + expect(plateSideRuns(after, [4, 0], [4, 4])[0]!.dropTo).toBe(0.05) + const noFloor = computePlateSurfacePartition( + host, + context([host, { ...neighbour, support: 'open' }]), + )! + expect(noFloor.sides.every((side) => side.dropTo === undefined)).toBe(true) +}) diff --git a/packages/core/src/lib/plate-surface.test.ts b/packages/core/src/lib/plate-surface.test.ts new file mode 100644 index 0000000000..83ee898c7b --- /dev/null +++ b/packages/core/src/lib/plate-surface.test.ts @@ -0,0 +1,323 @@ +import { describe, expect, test } from 'bun:test' +import { SlabNode, WallNode, ZoneNode } from '../schema' +import { + classifyPlateSideAt, + clearPlateSurfaceCaches, + computePlateSurfacePartition, + type PlateLevelContext, + parseRoomFinishRole, + plateFinishKey, + roomFinishRole, +} from './plate-surface' +import { area, containsPoint, intersection, union } from './polygon-boolean' + +const WOOD = 'library:wood-woodplank48' +const TILE = 'library:flooring-tiles3' +const TERRAZZO = 'library:flooring-terrazzo19' + +function wall(id: string, start: [number, number], end: [number, number]) { + return WallNode.parse({ id, parentId: 'level_1', start, end, thickness: 0.2, height: 2.5 }) +} + +function zone(id: string, polygon: Array<[number, number]>, floor?: ZoneNode['floor']) { + return ZoneNode.parse({ + id, + parentId: 'level_1', + name: id, + polygon, + spaceRole: 'room', + ...(floor ? { floor } : {}), + }) +} + +/** + * Two 4 × 4 rooms sharing a 0.2 m divider, one with a finish region, plus a + * manual slab sitting on the right-hand room's floor. + * + * wall centrelines: outer rectangle (0,0)–(8.2,4.2), divider at x = 4.1 + * clear polygons: A = x 0.1…4.0, B = x 4.2…8.1, both z 0.1…4.1 + */ +function twoRoomLevel() { + const walls = [ + wall('wall_n', [0, 0], [8.2, 0]), + wall('wall_e', [8.2, 0], [8.2, 4.2]), + wall('wall_s', [8.2, 4.2], [0, 4.2]), + wall('wall_w', [0, 4.2], [0, 0]), + wall('wall_mid', [4.1, 0], [4.1, 4.2]), + ] + const zones = [ + zone( + 'zone_a', + [ + [0, 0], + [4.1, 0], + [4.1, 4.2], + [0, 4.2], + ], + { + finish: WOOD, + regions: [ + { + id: 'region_1', + finish: TERRAZZO, + polygon: [ + [0.5, 0.5], + [2, 0.5], + [2, 2], + [0.5, 2], + ], + }, + ], + }, + ), + zone( + 'zone_b', + [ + [4.1, 0], + [8.2, 0], + [8.2, 4.2], + [4.1, 4.2], + ], + { finish: TILE }, + ), + ] + const plate = SlabNode.parse({ + id: 'slab_plate', + parentId: 'level_1', + boundary: 'auto', + autoFromWalls: true, + zoneIds: ['zone_a', 'zone_b'], + elevation: 0.05, + thickness: 0.2, + polygon: [ + [-0.1, -0.1], + [8.3, -0.1], + [8.3, 4.3], + [-0.1, 4.3], + ], + }) + const manual = SlabNode.parse({ + id: 'slab_manual', + parentId: 'level_1', + elevation: 0.05, + thickness: 0.05, + polygon: [ + [6, 2], + [7.5, 2], + [7.5, 3.5], + [6, 3.5], + ], + }) + const context: PlateLevelContext = { walls, zones, slabs: [plate, manual] } + return { plate, manual, context } +} + +function roleAt( + partition: NonNullable>, + point: [number, number], +): string | null { + const hits = partition.cells.filter((cell) => containsPoint(cell.polygons, point)) + expect(hits.length).toBeLessThanOrEqual(1) + return hits[0]?.role ?? null +} + +describe('plate top partition', () => { + test('room finishes, a region and a manual slab split one plate top', () => { + clearPlateSurfaceCaches() + const { plate, manual, context } = twoRoomLevel() + const partition = computePlateSurfacePartition(plate, context) + if (!partition) throw new Error('expected a partition') + + expect(partition.plainTop).toBe(false) + // One cell per distinct resolved surface: region, room A, room B, plate. + expect(partition.cells.map((cell) => cell.role)).toEqual([ + roomFinishRole('zone_a', 'region_1'), + roomFinishRole('zone_a'), + roomFinishRole('zone_b'), + 'surface', + ]) + expect(partition.cells.map((cell) => cell.materialKey)).toEqual([ + plateFinishKey(TERRAZZO), + plateFinishKey(WOOD), + plateFinishKey(TILE), + plateFinishKey(undefined), + ]) + + // Sample points: inside the region, room A outside it, room B, under the + // divider, under the outer wall, and where the manual slab masks the plate. + expect(roleAt(partition, [1, 1])).toBe(roomFinishRole('zone_a', 'region_1')) + expect(roleAt(partition, [3, 3])).toBe(roomFinishRole('zone_a')) + expect(roleAt(partition, [0.6, 3.5])).toBe(roomFinishRole('zone_a')) + expect(roleAt(partition, [5, 1])).toBe(roomFinishRole('zone_b')) + expect(roleAt(partition, [4.1, 2])).toBe('surface') + expect(roleAt(partition, [0, 2])).toBe('surface') + expect(roleAt(partition, [8.25, 2])).toBe('surface') + expect(roleAt(partition, [6.75, 2.75])).toBeNull() + + // The mask is exactly the manual slab, and no cell reaches into it. + expect(area(partition.masked)).toBeCloseTo(1.5 * 1.5, 4) + for (const cell of partition.cells) { + expect(area(intersection(cell.polygons, partition.masked))).toBeLessThan(1e-6) + } + // The cells plus the mask tile the whole plate top, with no overlap. + const total = partition.cells.reduce((sum, cell) => sum + area(cell.polygons), 0) + expect(total + area(partition.masked)).toBeCloseTo(8.4 * 4.4, 3) + expect(area(union([...partition.cells.flatMap((cell) => cell.polygons)]))).toBeCloseTo(total, 3) + expect(manual.polygon).toHaveLength(4) + }) + + test('the same inputs build the same partition twice', () => { + clearPlateSurfaceCaches() + const first = computePlateSurfacePartition(twoRoomLevel().plate, twoRoomLevel().context) + clearPlateSurfaceCaches() + const second = computePlateSurfacePartition(twoRoomLevel().plate, twoRoomLevel().context) + expect(JSON.stringify(second)).toBe(JSON.stringify(first)) + }) + + test('a plate with no room finish keeps one plain surface cell', () => { + clearPlateSurfaceCaches() + const { plate, context } = twoRoomLevel() + const bare = context.zones.map((z) => ({ ...z, floor: undefined })) + const partition = computePlateSurfacePartition(plate, { + ...context, + zones: bare, + slabs: [plate], + }) + if (!partition) throw new Error('expected a partition') + expect(partition.plainTop).toBe(true) + expect(partition.cells).toHaveLength(1) + expect(partition.cells[0]?.role).toBe('surface') + }) + + test('a manual slab has no partition', () => { + clearPlateSurfaceCaches() + const { manual, context } = twoRoomLevel() + expect(computePlateSurfacePartition(manual, context)).toBeNull() + }) +}) + +describe('plate side exposure', () => { + /** + * A raised plate whose north edge stands under a wall, whose east edge steps + * down onto a lower plate, and whose south and west edges face the outside. + */ + function steppedLevel() { + const plate = SlabNode.parse({ + id: 'slab_upper', + parentId: 'level_1', + boundary: 'auto', + autoFromWalls: true, + zoneIds: ['zone_upper'], + elevation: 0.35, + thickness: 0.2, + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + }) + const lower = SlabNode.parse({ + id: 'slab_lower', + parentId: 'level_1', + boundary: 'auto', + autoFromWalls: true, + zoneIds: ['zone_lower'], + elevation: 0.05, + thickness: 0.2, + polygon: [ + [4, 0], + [8, 0], + [8, 4], + [4, 4], + ], + }) + const context: PlateLevelContext = { + walls: [wall('wall_n', [0, 0], [4, 0])], + zones: [ + zone('zone_upper', [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ]), + zone('zone_lower', [ + [4, 0], + [8, 0], + [8, 4], + [4, 4], + ]), + ], + slabs: [plate, lower], + } + return { plate, context } + } + + test('classifies exterior, riser and wall-covered edges', () => { + clearPlateSurfaceCaches() + const { plate, context } = steppedLevel() + const partition = computePlateSurfacePartition(plate, context) + if (!partition) throw new Error('expected a partition') + + // East: faces the lower plate and the room it carries → a riser. + expect(classifyPlateSideAt(partition, [4, 2])).toBe('riser') + // South and west: nothing on the far side → exterior edges. + expect(classifyPlateSideAt(partition, [2, 4])).toBe('edge') + expect(classifyPlateSideAt(partition, [0, 2])).toBe('edge') + // The facade covers the top, but its slab thickness remains visible. + expect(classifyPlateSideAt(partition, [2, 0])).toBe('edge') + expect(partition.sides.some((side) => side.role === 'riser')).toBe(true) + expect( + partition.sides.some( + (side) => + side.role === 'edge' && Math.abs(side.start[1]) < 1e-9 && Math.abs(side.end[1]) < 1e-9, + ), + ).toBe(true) + }) + + test('an open hole rim is an edge', () => { + clearPlateSurfaceCaches() + const { plate, context } = steppedLevel() + const withHole = SlabNode.parse({ + ...plate, + holes: [ + [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], + ], + ], + holeMetadata: [{ source: 'manual' }], + }) + const partition = computePlateSurfacePartition(withHole, { + ...context, + slabs: [withHole, ...context.slabs.slice(1)], + }) + if (!partition) throw new Error('expected a partition') + expect(classifyPlateSideAt(partition, [1.5, 1])).toBe('edge') + }) +}) + +describe('room finish roles', () => { + test('round-trip a room role and a region role', () => { + expect(parseRoomFinishRole(roomFinishRole('zone_1'))).toEqual({ + zoneId: 'zone_1', + regionId: null, + }) + expect(parseRoomFinishRole(roomFinishRole('zone_1', 'region_2'))).toEqual({ + zoneId: 'zone_1', + regionId: 'region_2', + }) + expect(parseRoomFinishRole('surface')).toBeNull() + expect(parseRoomFinishRole('edge')).toBeNull() + }) + + test('equal finishes share a material key, different ones do not', () => { + expect(plateFinishKey(WOOD)).toBe(plateFinishKey(WOOD)) + expect(plateFinishKey(WOOD)).not.toBe(plateFinishKey(TILE)) + expect(plateFinishKey({ properties: { color: '#ff0000' } })).toBe( + plateFinishKey({ properties: { color: '#ff0000' } }), + ) + }) +}) diff --git a/packages/core/src/lib/plate-surface.ts b/packages/core/src/lib/plate-surface.ts new file mode 100644 index 0000000000..969a0180dd --- /dev/null +++ b/packages/core/src/lib/plate-surface.ts @@ -0,0 +1,984 @@ +import type { + AnyNode, + AnyNodeId, + DoorNode, + SlabNode, + WallNode, + WindowNode, + ZoneNode, +} from '../schema' +import { DEFAULT_SLAB_ELEVATION } from '../schema/nodes/slab' +import { getWallCurveFrameAt, getWallCurveStationAtPoint } from '../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { openingLandings } from './floor-opening-footprints' +import type { PlateRoom } from './floor-plates' +import { floorRoomFaces } from './floor-room-faces' +import { exposedIntervals } from './level-footprints' +import { getOpeningWallCut, wallSupportForNodes } from './opening-floor-datum' +import { + area, + difference, + intersection, + type MultiPolygon, + containsPoint as polygonContainsPoint, + type Ring, + union, +} from './polygon-boolean' +import { roomFloorPlate } from './room-floor-plate' + +/** + * Who draws the walking surface of a floor plate, and what the plate's vertical + * faces are. + * + * A plate (`slab.boundary === 'auto'`) spans every room it carries plus the + * wall footprints between them, so one mesh cannot hold one finish: the top is + * partitioned into cells by the polygon kernel and each cell draws its own + * resolved material. Priority, highest first: + * + * 1. a manual slab top at the same height → masked out of the plate entirely + * 2. the zone's `floor.regions` → later entries win + * 3. the zone's `floor.finish` → inside the zone CLEAR polygon + * 4. the plate's own `surface` slot → under walls and unfinished rooms + * + * The side faces are classified per exposed interval: `edge` where the face + * looks at the exterior, `riser` where it looks at a lower plate or the open + * air of a sub-zone step. Wall-covered steps are hidden except under doors; + * facade edges still show the slab thickness. + * + * Everything here is pure 2D and memoised per plate per topology/finish + * revision — `computePlateSurfacePartition` is the only entry point a renderer + * needs and never runs per frame. + */ + +/** A zone floor finish: a `MaterialRef` string, or an inline legacy material. */ +export type PlateFinish = string | Record + +export type PlateTopCell = { + /** Paint role for a hit on this cell — a slab slot id or a `room:` route. */ + role: string + /** Finish drawing the cell; absent = the plate's own `surface` slot. */ + finish?: PlateFinish + /** Equal keys ⇒ one shared material instance, so batches never fragment. */ + materialKey: string + polygons: MultiPolygon +} + +export type PlateSideRole = 'edge' | 'riser' | 'hidden' + +export type PlateSideInterval = { + start: [number, number] + end: [number, number] + role: PlateSideRole + /** Lower neighbouring plate top, in level-local metres. */ + dropTo?: number + zoneId?: string + /** + * The doorway a room-owned riser steps through (`lib/floor-step-finish`): + * the door it sits under, else the lower room it looks at. + */ + stepKey?: string + bottom?: number + top?: number +} + +export type PlateSurfacePartition = { + /** Disjoint, together covering the plate top minus `masked`. */ + cells: PlateTopCell[] + /** Plate top covered by a manual surface or solid platform. */ + masked: MultiPolygon + sides: PlateSideInterval[] + /** True when the top is one plain `surface` cell — renderers skip the clip. */ + plainTop: boolean +} + +export type PlateLevelContext = { + walls: WallNode[] + zones: ZoneNode[] + slabs: SlabNode[] + openings?: (DoorNode | WindowNode)[] + platform?: boolean + nodes?: Readonly> +} + +const contextNodesCache = new WeakMap< + PlateLevelContext, + { signature: string; nodes: Readonly> } +>() + +function surfaceNodes(context: PlateLevelContext): Readonly> { + const signature = JSON.stringify([ + wallSignature(context.walls), + zoneSignature(context.zones), + slabSignature(context.slabs), + context.openings, + ]) + const cached = contextNodesCache.get(context) + if (cached?.signature === signature) return cached.nodes + const nodes = { + ...context.nodes, + ...Object.fromEntries( + [...context.walls, ...context.zones, ...context.slabs, ...(context.openings ?? [])].map( + (node) => [node.id, node], + ), + ), + } + contextNodesCache.set(context, { signature, nodes }) + return nodes +} + +/** Manual tops within this of the plate top hide the plate instead of z-fighting it. */ +const TOP_MATCH_TOLERANCE = 0.01 +const MIN_CELL_AREA = 1e-6 +/** Sampling offset used to look across an exposed plate edge. */ +const EXPOSURE_PROBE = 0.02 +const PLATE_SURFACE_ROLE = 'surface' + +export function isFloorPlate(slab: Pick): boolean { + return slab.boundary === 'auto' +} + +/** `room:` paints the room's floor finish; `/regionId` paints one region. */ +export function roomFinishRole(zoneId: string, regionId?: string): string { + return regionId ? `room:${zoneId}/${regionId}` : `room:${zoneId}` +} + +export function parseRoomFinishRole( + role: string, +): { zoneId: string; regionId: string | null } | null { + if (!role.startsWith('room:')) return null + const rest = role.slice('room:'.length) + const slash = rest.indexOf('/') + if (slash < 0) return rest ? { zoneId: rest, regionId: null } : null + const zoneId = rest.slice(0, slash) + const regionId = rest.slice(slash + 1) + return zoneId && regionId ? { zoneId, regionId } : null +} + +/** Stable identity of a finish, so two rooms painted alike share one material. */ +export function plateFinishKey(finish: PlateFinish | undefined): string { + if (finish === undefined) return `slot:${PLATE_SURFACE_ROLE}` + return typeof finish === 'string' ? `ref:${finish}` : `inline:${JSON.stringify(finish)}` +} + +/** Level neighbourhood a plate partition reads — walls, zones and sibling slabs. */ +export function plateLevelContext( + parent: AnyNode | null, + resolve: (id: AnyNodeId) => AnyNode | undefined, +): PlateLevelContext { + const walls: WallNode[] = [] + const zones: ZoneNode[] = [] + const slabs: SlabNode[] = [] + const childIds = (parent as { children?: AnyNodeId[] } | null)?.children + if (!Array.isArray(childIds)) return { walls, zones, slabs } + for (const id of childIds) { + const child = resolve(id) + if (child?.type === 'wall') walls.push(child) + else if (child?.type === 'zone') zones.push(child) + else if (child?.type === 'slab') slabs.push(child) + } + const openings = walls.flatMap((wall) => + wall.children.flatMap((id) => { + const child = resolve(id) + return child?.type === 'door' || child?.type === 'window' ? [child] : [] + }), + ) + const nodes = Object.fromEntries( + [...childIds.map(resolve).filter((node): node is AnyNode => !!node), ...openings].map( + (node) => [node.id, node], + ), + ) + let ancestor = parent + while (ancestor && !nodes[ancestor.id]) { + nodes[ancestor.id] = ancestor + ancestor = ancestor.parentId ? (resolve(ancestor.parentId as AnyNodeId) ?? null) : null + } + return { walls, zones, slabs, openings, nodes } +} + +function round(value: number): number { + return Math.round(value * 1e4) / 1e4 +} + +function wallSignature(walls: readonly WallNode[]): string { + return JSON.stringify( + walls.map((wall) => [ + wall.id, + wall.start.map(round), + wall.end.map(round), + round(wall.thickness ?? 0), + wall.justification ?? null, + wall.curveOffset ?? null, + wall.supportSlabId, + wall.supportOffset, + wall.height, + ]), + ) +} + +function zoneSignature(zones: readonly ZoneNode[]): string { + return JSON.stringify( + zones.map((zone) => [ + zone.id, + zone.spaceRole, + zone.hasFloor, + zone.polygon, + zone.holes, + zone.floor?.finish ?? null, + zone.floorStepFinish, + zone.floorStepOverrides ?? null, + zone.floorEdgeFinish, + zone.floor?.elevation ?? null, + (zone.floor?.regions ?? []).map((region) => [region.id, region.polygon, region.finish]), + ]), + ) +} + +function slabSignature(slabs: readonly SlabNode[]): string { + return JSON.stringify( + slabs.map((slab) => [ + slab.id, + slab.boundary ?? null, + slab.autoFromWalls, + slab.recessed, + slab.support, + slab.plateRole, + slab.thickness, + slab.elevation ?? DEFAULT_SLAB_ELEVATION, + slab.polygon, + slab.holes, + slab.zoneIds ?? null, + ]), + ) +} + +/** + * Everything the partition of ONE plate depends on. Written into the geometry + * builder's memo and into the slab dependency tracker, so a finish edit rebuilds + * exactly the plates that show it and nothing else re-clips. + */ +export function platePartitionSignature(plate: SlabNode, context: PlateLevelContext): string { + return JSON.stringify([ + plate.id, + plate.support, + plate.plateRole, + context.platform ?? false, + round(plate.elevation ?? DEFAULT_SLAB_ELEVATION), + plate.polygon, + plate.holes, + plate.zoneIds ?? null, + plate.slots?.surface ?? null, + wallSignature(context.walls), + zoneSignature(context.zones), + slabSignature(context.slabs), + (context.openings ?? []).map((opening) => [ + opening.id, + opening.parentId, + opening.position, + opening.width, + opening.height, + opening.verticalAnchor, + ]), + ]) +} + +const wallCoverCache = new WeakMap< + readonly WallNode[], + { signature: string; cover: MultiPolygon } +>() +const wallCoverBySignature = new Map() +const MAX_CACHE_ENTRIES = 32 + +function remember(cache: Map, key: string, value: T): T { + cache.delete(key) + cache.set(key, value) + if (cache.size > MAX_CACHE_ENTRIES) { + const oldest = cache.keys().next() + if (!oldest.done) cache.delete(oldest.value) + } + return value +} + +/** Joined plan footprints of every wall on the level — the "under a wall" mask. */ +export function levelWallCover(walls: readonly WallNode[]): MultiPolygon { + if (!walls.length) return [] + const signature = wallSignature(walls) + const cached = wallCoverCache.get(walls) + if (cached?.signature === signature) return cached.cover + const shared = wallCoverBySignature.get(signature) + if (shared) { + wallCoverCache.set(walls, { signature, cover: shared }) + return shared + } + const miters = calculateLevelMiters([...walls]) + const cover = union( + walls.map((wall) => + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ), + ) + wallCoverCache.set(walls, { signature, cover }) + return remember(wallCoverBySignature, signature, cover) +} + +const surfacePolygonCache = new WeakMap() +function surfacePolygon(node: Pick): MultiPolygon { + const signature = JSON.stringify([node.polygon, node.holes]) + const cached = surfacePolygonCache.get(node) + if (cached?.signature === signature) return cached.polygon + const polygon = + node.polygon.length < 3 ? [] : union([{ outer: node.polygon, holes: node.holes ?? [] }]) + surfacePolygonCache.set(node, { signature, polygon }) + return polygon +} + +function overlappingPolygons( + polygons: MultiPolygon, + target: MultiPolygon, + padding = 0.0001, +): MultiPolygon { + const points = target.flatMap((polygon) => polygon.outer) + const minX = Math.min(...points.map((point) => point[0])) - padding + const maxX = Math.max(...points.map((point) => point[0])) + padding + const minZ = Math.min(...points.map((point) => point[1])) - padding + const maxZ = Math.max(...points.map((point) => point[1])) + padding + return polygons.filter( + ({ outer }) => + Math.max(...outer.map((point) => point[0])) >= minX && + Math.min(...outer.map((point) => point[0])) <= maxX && + Math.max(...outer.map((point) => point[1])) >= minZ && + Math.min(...outer.map((point) => point[1])) <= maxZ, + ) +} + +const pointBounds = new WeakMap< + MultiPolygon, + Array<{ polygon: MultiPolygon; minX: number; maxX: number; minZ: number; maxZ: number }> +>() +function containsPoint(polygons: MultiPolygon, point: [number, number]): boolean { + let bounds = pointBounds.get(polygons) + if (!bounds) { + bounds = polygons.map((polygon) => ({ + polygon: [polygon], + minX: Math.min(...polygon.outer.map((p) => p[0])) - 1e-10, + maxX: Math.max(...polygon.outer.map((p) => p[0])) + 1e-10, + minZ: Math.min(...polygon.outer.map((p) => p[1])) - 1e-10, + maxZ: Math.max(...polygon.outer.map((p) => p[1])) + 1e-10, + })) + pointBounds.set(polygons, bounds) + } + return bounds.some( + (bound) => + point[0] >= bound.minX && + point[0] <= bound.maxX && + point[1] >= bound.minZ && + point[1] <= bound.maxZ && + polygonContainsPoint(bound.polygon, point), + ) +} + +function zoneFace(zone: ZoneNode): MultiPolygon { + return surfacePolygon(zone) +} + +function slabTop(slab: SlabNode): MultiPolygon { + return surfacePolygon(slab) +} + +function isManualSlab(slab: SlabNode): boolean { + return slab.boundary !== 'auto' && !slab.autoFromWalls +} + +type Candidate = { role: string; finish: PlateFinish | undefined; polygons: MultiPolygon } + +/** + * Top cells, highest priority first. Each candidate takes only what the ones + * before it left, so regions beat the room finish and the room finish beats the + * plate's own slot — with no overlap and no double-drawn triangle. + */ +function partitionTop( + plate: SlabNode, + top: MultiPolygon, + context: PlateLevelContext, + wallCover: MultiPolygon, + prepared: ReturnType, +): { cells: PlateTopCell[]; masked: MultiPolygon } { + const elevation = plate.elevation ?? DEFAULT_SLAB_ELEVATION + const covering = context.slabs.filter( + (slab) => + slab.id !== plate.id && + !slab.recessed && + ((isManualSlab(slab) && + Math.abs((slab.elevation ?? DEFAULT_SLAB_ELEVATION) - elevation) <= TOP_MATCH_TOLERANCE) || + (slab.plateRole === 'platform' && + slab.elevation > elevation && + slab.elevation - slab.thickness <= elevation + 1e-6)), + ) + const masked = covering.length + ? intersection(union(covering.map(slabTop)), top) + : ([] as MultiPolygon) + + let remaining = masked.length ? difference(top, masked) : top + const cells: PlateTopCell[] = [] + if (!remaining.length) return { cells, masked } + + const carried = new Map(context.zones.map((zone) => [zone.id as string, zone])) + const zones = (plate.zoneIds ?? []) + .map((id) => carried.get(id)) + .filter((zone): zone is ZoneNode => zone?.spaceRole === 'room') + + const thresholdOwners = prepared.landings + .filter((landing) => !landing.exterior || Math.abs(landing.elevation - elevation) < 0.001) + .flatMap((landing) => + landing.polygons.map((polygon) => ({ + polygon, + zone: context.zones.find((zone) => zone.id === landing.zoneId), + })), + ) + const clearByZone = new Map() + for (const zone of zones) { + const face = zoneFace(zone) + if (!face.length) continue + const clear = + plate.plateRole === 'platform' || plate.plateRole === 'sunken' + ? top + : wallCover.length + ? difference( + face, + union( + overlappingPolygons( + prepared.walls.flatMap((entry) => entry.polygon), + face, + ), + ), + ) + : face + const withThreshold = plate.plateRole + ? union([ + clear, + ...thresholdOwners + .filter((entry) => entry.zone?.id === zone.id) + .map((entry) => entry.polygon), + ]) + : clear + if (withThreshold.length) clearByZone.set(zone.id, withThreshold) + } + + const candidates: Candidate[] = [] + for (const zone of zones) { + const clear = clearByZone.get(zone.id) + if (!clear) continue + const regions = zone.floor?.regions ?? [] + // Later entries win, so the last region is the first candidate. + for (let index = regions.length - 1; index >= 0; index -= 1) { + const region = regions[index]! + if (region.polygon.length < 3) continue + const polygons = intersection(union([region.polygon as Ring]), clear) + if (!polygons.length) continue + candidates.push({ + role: roomFinishRole(zone.id, region.id), + finish: region.finish, + polygons, + }) + } + } + for (const zone of zones) { + const clear = clearByZone.get(zone.id) + const finish = zone.floor?.finish + if (!clear || (finish === undefined && !plate.plateRole)) continue + candidates.push({ role: roomFinishRole(zone.id), finish, polygons: clear }) + } + + const claimed: MultiPolygon = [] + for (const candidate of candidates) { + const clipped = intersection(candidate.polygons, remaining) + const blockers = overlappingPolygons(claimed, clipped) + const part = blockers.length ? difference(clipped, blockers) : clipped + if (area(part) < MIN_CELL_AREA) continue + cells.push({ + role: candidate.role, + finish: candidate.finish, + materialKey: plateFinishKey(candidate.finish), + polygons: part, + }) + claimed.push(...part) + } + if (claimed.length) remaining = difference(remaining, claimed) + + if (area(remaining) >= MIN_CELL_AREA) { + cells.push({ + role: PLATE_SURFACE_ROLE, + materialKey: plateFinishKey(undefined), + polygons: remaining, + }) + } + return { cells, masked } +} + +/** + * Classify every edge interval, including wall-covered facade edges. Only a + * covered step facing a lower floor is hidden; exterior slab thickness stays visible. + */ +const preparedLevels = new Map>() + +function levelInputs(context: PlateLevelContext) { + const signature = JSON.stringify([ + wallSignature(context.walls), + zoneSignature(context.zones), + slabSignature(context.slabs), + context.openings, + Object.values(context.nodes ?? {}).filter( + (node) => !['wall', 'zone', 'slab', 'door', 'window'].includes(node.type), + ), + ]) + const cached = preparedLevels.get(signature) + if (cached) return cached + return remember(preparedLevels, signature, prepareLevel(context)) +} + +function prepareLevel(context: PlateLevelContext) { + const nodes = surfaceNodes(context) + const miters = calculateLevelMiters(context.walls) + const footprints = new Map( + context.walls.map((wall) => [ + wall.id as string, + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ]), + ) + const walls = context.walls.map((wall) => ({ + wall, + polygon: union([footprints.get(wall.id)!]), + get support() { + return wallSupportForNodes(wall, nodes) + }, + })) + const openings = (context.openings ?? []).flatMap((opening) => { + const wall = context.walls.find((wall) => wall.id === opening.parentId) + if (!wall) return [] + const cut = getOpeningWallCut(wall, opening, nodes) + return [{ opening, wall, aperture: cut.aperture, cut }] + }) + const boundaries = [ + ...context.walls, + ...Object.values(nodes).filter((node) => node.type === 'separator'), + ] + const faces = floorRoomFaces(boundaries) + const rooms: PlateRoom[] = context.zones.flatMap((zone) => { + const carried = roomFloorPlate(context.slabs, zone.id) + if (!carried || carried.support === 'open' || zone.hasFloor === false) return [] + const face = faces + .map((face) => ({ + face, + overlap: area( + intersection(zoneFace(zone), { outer: face.referencePolygon, holes: face.holes }), + ), + })) + .sort((a, b) => b.overlap - a.overlap)[0] + return face?.overlap + ? [ + { + ...face.face, + id: zone.id, + polygon: face.face.referencePolygon, + zone, + context: { + revision: 0, + walls: new Map(context.walls.map((w) => [w.id, w])), + wallFootprints: footprints, + }, + }, + ] + : [] + }) + const landings = openingLandings( + rooms, + (room) => roomFloorPlate(context.slabs, room.zone.id)!.elevation, + nodes, + new Map(openings.map((entry) => [entry.opening.id, entry.aperture])), + ) + return { + nodes, + footprints, + walls, + openings, + rooms, + landings, + wallCover: levelWallCover(context.walls), + } +} + +export function plateOpeningLandings(context: PlateLevelContext) { + return levelInputs(context).landings +} + +function classifySides( + plate: SlabNode, + top: MultiPolygon, + context: PlateLevelContext, + prepared: ReturnType, +): PlateSideInterval[] { + const elevation = plate.elevation + const bottom = elevation - plate.thickness + const { nodes, rooms, landings } = prepared + const nearby = (polygon: MultiPolygon) => overlappingPolygons(polygon, top, 0.03).length > 0 + const walls = prepared.walls.filter((entry) => nearby(entry.polygon)) + const openings = prepared.openings.filter((entry) => nearby(entry.aperture)) + const wallCover = + walls.length === prepared.walls.length + ? prepared.wallCover + : union(walls.map((entry) => entry.polygon)) + const solids = context.slabs + .filter((slab) => slab.id !== plate.id && slab.support !== 'open') + .map((slab) => ({ slab, polygon: slabTop(slab) })) + .filter((entry) => nearby(entry.polygon)) + const zones = context.zones + .filter( + (zone) => + zone.spaceRole === 'room' && zone.hasFloor !== false && zone.floor?.support !== 'open', + ) + .map((zone) => ({ + zone, + polygon: zoneFace(zone), + elevation: + roomFloorPlate(context.slabs, zone.id)?.elevation ?? zone.floor?.elevation ?? elevation, + })) + const nearbyZones = zones.filter((entry) => nearby(entry.polygon)) + const outlines = top.flatMap(({ outer, holes }) => + [outer, ...holes].map((outer) => ({ outer, holes: [] })), + ) + const cuts = [ + ...nearbyZones.flatMap((z) => z.polygon), + ...solids.flatMap((s) => s.polygon), + ...openings.flatMap((o) => o.aperture), + ] + const result: PlateSideInterval[] = [] + for (const interval of exposedIntervals(outlines, context.walls, wallCover, { + includeCovered: true, + splitAt: cuts, + })) { + let { start, end } = interval + let dx = end[0] - start[0], + dz = end[1] - start[1] + const length = Math.hypot(dx, dz) + if (length < 1e-7) continue + const midpoint: [number, number] = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2] + if ( + containsPoint(top, [midpoint[0] + (dz / length) * 0.002, midpoint[1] - (dx / length) * 0.002]) + ) { + ;[start, end] = [end, start] + dx = -dx + dz = -dz + } + const outside: [number, number] = [ + midpoint[0] + (dz / length) * 0.002, + midpoint[1] - (dx / length) * 0.002, + ] + const inside: [number, number] = [ + midpoint[0] - (dz / length) * 0.002, + midpoint[1] + (dx / length) * 0.002, + ] + if ( + plate.plateRole === 'base' && + solids.some( + (solid) => + solid.slab.plateRole === 'base' && + Math.abs(solid.slab.elevation - elevation) < 0.001 - 1e-9 && + containsPoint(solid.polygon, outside), + ) + ) { + result.push({ start, end, role: 'hidden' }) + continue + } + const adjacent = + plate.support === 'open' + ? undefined + : nearbyZones + .filter( + (z) => containsPoint(z.polygon, outside) && z.elevation <= elevation - 0.001 + 1e-9, + ) + .sort((a, b) => b.elevation - a.elevation)[0] + const neighbour = + plate.support !== 'open' + ? solids + .filter( + (s) => + containsPoint(s.polygon, outside) && s.slab.elevation <= elevation - 0.001 + 1e-9, + ) + .sort((a, b) => b.slab.elevation - a.slab.elevation)[0] + : undefined + const low = neighbour + ? Math.min(bottom, neighbour.slab.elevation) + : context.platform && !plate.plateRole + ? Math.min(0, bottom) + : bottom + const opening = openings.find((entry) => containsPoint(entry.aperture, midpoint)) + const landingOwner = opening + ? landings.find((landing) => !landing.exterior && landing.openingId === opening.opening.id) + ?.zoneId + : undefined + const spanOwner = rooms.find( + (room) => + Math.abs( + (roomFloorPlate(context.slabs, room.zone.id)?.elevation ?? elevation) - elevation, + ) < 0.001 && + room.spans.some((span) => { + const boundary = nodes[span.boundaryId] + if (boundary?.type !== 'separator') return false + const bx = boundary.end[0] - boundary.start[0], + bz = boundary.end[1] - boundary.start[1], + squared = bx * bx + bz * bz + const t = + ((midpoint[0] - boundary.start[0]) * bx + (midpoint[1] - boundary.start[1]) * bz) / + squared + const distance = + Math.abs( + (midpoint[0] - boundary.start[0]) * bz - (midpoint[1] - boundary.start[1]) * bx, + ) / Math.sqrt(squared) + const face = + (inside[0] - midpoint[0]) * -bz + (inside[1] - midpoint[1]) * bx > 0 ? 'a' : 'b' + return distance < 0.003 && t >= span.t0 && t <= span.t1 && face === span.face + }), + )?.zone.id + const ownerId = plate.plateRole === 'base' ? (landingOwner ?? spanOwner) : plate.zoneIds?.[0] + const blockers: Array<[number, number]> = [] + if ( + neighbour && + plate.plateRole === 'base' && + solids.some( + (s) => + s.slab.plateRole === 'platform' && + containsPoint(s.polygon, inside) && + !containsPoint(s.polygon, outside), + ) + ) + blockers.push([low, elevation]) + if (plate.support !== 'open') { + for (const solid of solids) + if (containsPoint(solid.polygon, outside)) + blockers.push([solid.slab.elevation - solid.slab.thickness, solid.slab.elevation]) + for (const entry of walls) { + if (!containsPoint(entry.polygon, outside) && !containsPoint(entry.polygon, midpoint)) + continue + const wall = entry.wall + const t = getWallCurveStationAtPoint(wall, midpoint) + const frame = getWallCurveFrameAt(wall, t) + const face = + (inside[0] - frame.point.x) * frame.normal.x + + (inside[1] - frame.point.y) * frame.normal.y > + 0 + ? 'a' + : 'b' + const run = entry.support.faceBottom[face].find((run) => run.start <= t && run.end >= t) + const wallBottom = run?.elevation ?? entry.support.elevation + const aperture = openings.find( + (o) => o.wall.id === wall.id && containsPoint(o.aperture, midpoint), + ) + if (!aperture) blockers.push([wallBottom, Infinity]) + else { + const cut = aperture.cut + blockers.push([wallBottom, cut.bottom], [cut.top, Infinity]) + } + } + } + let ranges: Array<[number, number]> = [[low, elevation]] + for (const [lo, hi] of blockers) + ranges = ranges.flatMap(([a, b]) => + hi <= a || lo >= b + ? [[a, b]] + : [ + ...(lo > a ? [[a, lo] as [number, number]] : []), + ...(hi < b ? [[hi, b] as [number, number]] : []), + ], + ) + const role = adjacent || neighbour ? ('riser' as const) : ('edge' as const) + const owner = role === 'riser' || plate.plateRole !== 'base' ? ownerId : undefined + // A door jamb's side of the step meets the aperture only at its edge, so + // the doorway is looked for on both sides of the face too. + const doorway = + opening ?? + openings.find( + (entry) => containsPoint(entry.aperture, inside) || containsPoint(entry.aperture, outside), + ) + const stepKey = + owner && role === 'riser' + ? (doorway?.opening.id ?? + adjacent?.zone.id ?? + neighbour?.slab.zoneIds?.[0] ?? + neighbour?.slab.id) + : undefined + if (!ranges.length) result.push({ start, end, role: 'hidden' }) + for (const [from, to] of ranges) + if (to - from >= 0.001 - 1e-9) + result.push({ + start, + end, + role, + zoneId: owner, + ...(stepKey ? { stepKey } : {}), + bottom: from, + top: to, + ...(from < bottom - 0.001 ? { dropTo: from } : {}), + }) + } + return result +} + +const partitionCache = new Map() + +/** + * The plate's top cells and side classification, memoised on + * `platePartitionSignature`. Returns `null` for anything that is not an + * unrecessed floor plate — manual slabs and pools keep the plain two-slot path. + */ +export function computePlateSurfacePartition( + plate: SlabNode, + context: PlateLevelContext, +): PlateSurfacePartition | null { + if (!isFloorPlate(plate) || plate.recessed || plate.polygon.length < 3) return null + const signature = platePartitionSignature(plate, context) + const cached = partitionCache.get(signature) + if (cached) return cached + + const top = slabTop(plate) + if (!top.length) return null + const wallCover = levelWallCover(context.walls) + const prepared = levelInputs(context) + const { cells, masked } = partitionTop(plate, top, context, wallCover, prepared) + const sides = classifySides(plate, top, context, prepared) + const partition: PlateSurfacePartition = { + cells, + masked, + sides, + plainTop: + masked.length === 0 && + cells.length <= 1 && + (cells[0]?.role ?? PLATE_SURFACE_ROLE) === PLATE_SURFACE_ROLE, + } + return remember(partitionCache, signature, partition) +} + +/** + * The doorway keys of every step `zoneId` owns on its level — what the room + * scope of a step paints. Reads the same memoised partitions the renderer does. + */ +export function floorStepKeysOf( + nodes: Readonly>, + levelId: string, + zoneId: string, +): string[] { + const level = nodes[levelId] + if (!level) return [] + const context = plateLevelContext(level, (id) => nodes[id]) + const keys = new Set() + for (const plate of context.slabs) { + if (!isFloorPlate(plate)) continue + const partition = computePlateSurfacePartition(plate, { + ...context, + platform: plate.plateRole === 'platform', + }) + for (const side of partition?.sides ?? []) + if (side.role === 'riser' && side.zoneId === zoneId && side.stepKey) keys.add(side.stepKey) + } + return [...keys].sort() +} + +/** Test seam — drops every memo so a test can assert a rebuild is deterministic. */ +export function clearPlateSurfaceCaches(): void { + partitionCache.clear() + preparedLevels.clear() + wallCoverBySignature.clear() +} + +/** + * Role of a plate side face at a point on the plate outline. + */ +export function classifyPlateSideAt( + partition: PlateSurfacePartition, + point: readonly [number, number], + tolerance = 1e-6, +): PlateSideRole { + return plateSideAt(partition, point, tolerance)?.role ?? 'edge' +} + +function plateSideAt( + partition: PlateSurfacePartition, + point: readonly [number, number], + tolerance: number, +): PlateSideInterval | undefined { + let bestDistance = tolerance + let closest: PlateSideInterval | undefined + for (const side of partition.sides) { + const dx = side.end[0] - side.start[0] + const dz = side.end[1] - side.start[1] + const lengthSq = dx * dx + dz * dz + if (lengthSq < 1e-18) continue + const t = ((point[0] - side.start[0]) * dx + (point[1] - side.start[1]) * dz) / lengthSq + if (t < -tolerance || t > 1 + tolerance) continue + const clamped = Math.max(0, Math.min(1, t)) + const distance = Math.hypot( + point[0] - (side.start[0] + dx * clamped), + point[1] - (side.start[1] + dz * clamped), + ) + if (distance <= bestDistance) { + bestDistance = distance + closest = side + } + } + return closest +} + +/** + * Where the classification changes along one plate outline segment, as + * parameters in `[0, 1]` of that segment. A side quad is cut at these stations + * so a single edge can be exterior for part of its length and a step for the + * rest. + */ +export function plateSideRuns( + partition: PlateSurfacePartition, + start: readonly [number, number], + end: readonly [number, number], +): Array<{ t0: number; t1: number; role: PlateSideRole; dropTo?: number; zoneId?: string }> { + const dx = end[0] - start[0] + const dz = end[1] - start[1] + const lengthSq = dx * dx + dz * dz + if (lengthSq < 1e-18) return [{ t0: 0, t1: 1, role: 'edge' }] + + const stations = new Set([0, 1]) + for (const side of partition.sides) { + for (const point of [side.start, side.end]) { + const t = ((point[0] - start[0]) * dx + (point[1] - start[1]) * dz) / lengthSq + if (t > 1e-9 && t < 1 - 1e-9) stations.add(t) + } + } + const ordered = [...stations].sort((a, b) => a - b) + const runs: Array<{ + t0: number + t1: number + role: PlateSideRole + dropTo?: number + zoneId?: string + }> = [] + for (let index = 0; index < ordered.length - 1; index += 1) { + const t0 = ordered[index]! + const t1 = ordered[index + 1]! + if (t1 - t0 < 1e-9) continue + const mid = (t0 + t1) / 2 + const side = plateSideAt( + partition, + [start[0] + dx * mid, start[1] + dz * mid], + Math.max(1e-6, Math.hypot(dx, dz) * 1e-4), + ) + const role = side?.role ?? 'edge' + const dropTo = side?.dropTo + const previous = runs.at(-1) + if (previous?.role === role && previous.dropTo === dropTo && previous.zoneId === side?.zoneId) + previous.t1 = t1 + else + runs.push({ + t0, + t1, + role, + ...(dropTo === undefined ? {} : { dropTo }), + ...(side?.zoneId ? { zoneId: side.zoneId } : {}), + }) + } + return runs.length ? runs : [{ t0: 0, t1: 1, role: 'edge' }] +} diff --git a/packages/core/src/lib/polygon-boolean.test.ts b/packages/core/src/lib/polygon-boolean.test.ts new file mode 100644 index 0000000000..2ec11caa25 --- /dev/null +++ b/packages/core/src/lib/polygon-boolean.test.ts @@ -0,0 +1,187 @@ +import { describe, expect, spyOn, test } from 'bun:test' +import clipping from 'polygon-clipping' +import { + area, + containsPoint, + difference, + distanceToBoundary, + intersection, + type Ring, + union, +} from './polygon-boolean' + +const square: Ring = [ + [0, 0], + [1, 0], + [1, 1], + [0, 1], +] + +describe('polygon boolean kernel', () => { + test('touching squares merge with no duplicate or collinear vertices', () => { + const adjacent: Ring = [ + [1, 0], + [2, 0], + [2, 1], + [1, 1], + [1, 0], + ] + const merged = union([square, adjacent]) + expect(merged).toEqual([ + { + outer: [ + [0, 0], + [2, 0], + [2, 1], + [0, 1], + ], + holes: [], + }, + ]) + expect(intersection(square, adjacent)).toEqual([]) + expect(union([adjacent.slice().reverse(), square.slice().reverse()])).toEqual(merged) + }) + + test('square with a hole preserves area, membership, hole rims and boundary distance', () => { + const outer: Ring = [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ] + const hole: Ring = [ + [1, 1], + [3, 1], + [3, 3], + [1, 3], + ] + const result = difference(outer, hole) + expect(result).toHaveLength(1) + expect(result[0]!.holes).toHaveLength(1) + expect(area(result)).toBe(12) + expect(containsPoint(result, [2, 2])).toBe(false) + expect(containsPoint(result, [0.5, 2])).toBe(true) + expect(containsPoint(result, [1, 2])).toBe(true) + expect(distanceToBoundary(result, [2, 2])).toBe(1) + expect(distanceToBoundary(result, [5, 2])).toBe(1) + expect(area(intersection(result, outer))).toBe(12) + expect(union([result, hole])).toEqual(union([outer])) + }) + + test('quantises inputs to 0.1 mm and removes sub-1e-6 square metre slivers', () => { + expect(union([square.map(([x, z]) => [x + 0.000_04, z - 0.000_04])])).toEqual(union([square])) + expect( + union([ + [ + [0, 0], + [0.001, 0], + [0.001, 0.0005], + [0, 0.0005], + ], + ]), + ).toEqual([]) + expect( + difference(square, [ + [0.000_000_1, 0], + [1, 0], + [1, 1], + [0.000_000_1, 1], + ]), + ).toEqual([]) + }) + + test('disconnected components and holes have deterministic ordering', () => { + const shifted = square.map(([x, z]): [number, number] => [x + 3, z]) + expect(union([shifted, square])).toEqual(union([square, shifted])) + expect(union([])).toEqual([]) + expect(difference([], square)).toEqual([]) + expect(intersection(square, [])).toEqual([]) + expect(distanceToBoundary([], [0, 0])).toBe(Number.POSITIVE_INFINITY) + }) + test('quantising a narrow notch preserves its reversal until clipping resolves it', () => { + const notch: Ring = [ + [0, 0], + [2, 0], + [2, 1.99996], + [1, 1], + [1.99996, 2], + [0, 2], + ] + const expected = union([ + [ + [0, 0], + [2, 0], + [2, 2], + [0, 2], + ], + ]) + expect(union([notch])).toEqual(expected) + expect(area(union([notch]))).toBe(4) + expect(difference(notch, [])).toEqual(expected) + expect(intersection(notch, expected)).toEqual(expected) + }) + + test('all operations reject non-finite outer and hole coordinates without throwing', () => { + const warn = spyOn(console, 'warn').mockImplementation(() => {}) + try { + for (const invalid of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) { + const ring: Ring = [ + [0, 0], + [invalid, 0], + [1, 1], + [0, 1], + ] + for (const input of [ring, { outer: square, holes: [ring] }]) { + expect(union([square, input])).toEqual([]) + expect(difference(square, input)).toEqual([]) + expect(difference(input, square)).toEqual([]) + expect(intersection(square, input)).toEqual([]) + } + } + } finally { + warn.mockRestore() + } + }) + + test('clipping exceptions return empty polygons in all operations', () => { + const warn = spyOn(console, 'warn').mockImplementation(() => {}) + const mocks = (['union', 'difference', 'intersection'] as const).map((operation) => + spyOn(clipping, operation).mockImplementation(() => { + throw new Error('clipping failed') + }), + ) + try { + expect(union([square])).toEqual([]) + expect(difference(square, square)).toEqual([]) + expect(difference(square, [])).toEqual([]) + expect(intersection(square, square)).toEqual([]) + } finally { + for (const mock of mocks) mock.mockRestore() + warn.mockRestore() + } + }) + + test('development warns once per failing caller and production stays quiet', () => { + const environment = process.env.NODE_ENV + const warn = spyOn(console, 'warn').mockImplementation(() => {}) + const invalid: Ring = [ + [0, 0], + [Number.NaN, 1], + [1, 0], + ] + try { + process.env.NODE_ENV = 'development' + for (let i = 0; i < 3; i++) expect(union([invalid])).toEqual([]) + expect(warn).toHaveBeenCalledTimes(1) + expect(union([invalid])).toEqual([]) + expect(warn).toHaveBeenCalledTimes(2) + process.env.NODE_ENV = 'production' + expect(union([invalid])).toEqual([]) + expect(warn).toHaveBeenCalledTimes(2) + } finally { + if (environment === undefined) delete process.env.NODE_ENV + else process.env.NODE_ENV = environment + warn.mockRestore() + } + }) +}) diff --git a/packages/core/src/lib/polygon-boolean.ts b/packages/core/src/lib/polygon-boolean.ts new file mode 100644 index 0000000000..9933a55924 --- /dev/null +++ b/packages/core/src/lib/polygon-boolean.ts @@ -0,0 +1,250 @@ +import clipping from 'polygon-clipping' + +export type Ring = [number, number][] +export type Polygon = { outer: Ring; holes: Ring[] } +export type MultiPolygon = Polygon[] +export type PolygonInput = Ring | Polygon | MultiPolygon + +const SCALE = 10_000 +const MIN_AREA = 1e-6 + +// Relative to the first vertex: absolute products at large coordinates (1e9 m +// offsets) cancel catastrophically and turn a zero-area sliver into square metres. +function signedArea(ring: Ring): number { + const origin = ring[0] + if (!origin) return 0 + const [ox, oz] = origin + return ( + ring.reduce((sum, p, i) => { + const q = ring[(i + 1) % ring.length]! + return sum + (p[0] - ox) * (q[1] - oz) - (q[0] - ox) * (p[1] - oz) + }, 0) / 2 + ) +} + +function comparePoints(a: [number, number], b: [number, number]) { + return a[0] - b[0] || a[1] - b[1] +} + +function dedupeRing(points: Ring): Ring { + return points.filter((p, i) => comparePoints(p, points[(i + 1) % points.length]!) !== 0) +} + +function cleanRing(points: Ring, ccw: boolean): Ring { + let ring = dedupeRing(points) + let changed = true + while (changed && ring.length >= 3) { + changed = false + ring = ring.filter((b, i) => { + const a = ring[(i + ring.length - 1) % ring.length]! + const c = ring[(i + 1) % ring.length]! + const cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) + const between = (b[0] - a[0]) * (b[0] - c[0]) + (b[1] - a[1]) * (b[1] - c[1]) < 0 + if (Math.abs(cross) > 1e-12 || !between) return true + changed = true + return false + }) + } + if (ring.length < 3) return [] + if (signedArea(ring) > 0 !== ccw) ring.reverse() + let first = 0 + for (let i = 1; i < ring.length; i++) { + if (comparePoints(ring[i]!, ring[first]!) < 0) first = i + } + return [...ring.slice(first), ...ring.slice(0, first)] +} + +function compareRings(a: Ring, b: Ring) { + for (let i = 0; i < Math.min(a.length, b.length); i++) { + const order = comparePoints(a[i]!, b[i]!) + if (order) return order + } + return a.length - b.length +} + +function polygons(input: PolygonInput): MultiPolygon { + if (!Array.isArray(input)) return [input] + if (!input.length) return [] + return Array.isArray(input[0]) ? [{ outer: input as Ring, holes: [] }] : (input as MultiPolygon) +} + +function quantised(input: PolygonInput): clipping.MultiPolygon { + return polygons(input).flatMap(({ outer, holes }) => { + const rings = [outer, ...holes].map((ring) => + dedupeRing( + ring.map(([x, z]) => { + const point: [number, number] = [ + Math.round(x * SCALE) / SCALE, + Math.round(z * SCALE) / SCALE, + ] + if (![x, z, ...point].every(Number.isFinite)) + throw new Error('Non-finite polygon coordinate') + return point.map((value) => (value === 0 ? 0 : value)) as [number, number] + }), + ), + ) + if (rings[0]!.length < 3) return [] + return [rings.filter((ring) => ring.length >= 3)] + }) +} + +function normalise(result: clipping.MultiPolygon): MultiPolygon { + return result + .flatMap(([shell, ...voids]) => { + const outer = cleanRing(shell!, true) + const holes = voids + .map((ring) => cleanRing(ring, false)) + .filter((ring) => Math.abs(signedArea(ring)) >= MIN_AREA) + .sort(compareRings) + const polygon = { outer, holes } + return area([polygon]) >= MIN_AREA ? [polygon] : [] + }) + .sort((a, b) => compareRings(a.outer, b.outer)) +} + +const warnedCallSites = new Set() + +function clip( + operation: 'union' | 'difference' | 'intersection', + inputs: readonly PolygonInput[], + run: (inputs: clipping.MultiPolygon[]) => clipping.MultiPolygon, + throwOnError = false, +): MultiPolygon { + try { + return normalise(run(inputs.map(quantised))) + } catch (error) { + if (throwOnError) throw error + if (process.env.NODE_ENV !== 'production') { + const caller = new Error('Polygon clipping caller').stack + ?.split('\n') + .slice(1) + .find( + (line) => + !(line.includes('/polygon-boolean.ts:') || line.includes('/polygon-boolean.js:')), + ) + const site = `${operation}:${caller ?? 'unknown'}` + if (!warnedCallSites.has(site)) { + warnedCallSites.add(site) + console.warn( + `[polygon-boolean] ${operation} failed at ${caller?.trim() ?? 'unknown caller'}`, + error, + ) + } + } + return [] + } +} + +export function union(inputs: readonly PolygonInput[]): MultiPolygon { + return clip('union', inputs, (polygons) => { + const valid = polygons.filter((multi) => multi.length) + return valid.length ? clipping.union(valid[0]!, ...valid.slice(1)) : [] + }) +} + +export function difference( + a: PolygonInput, + b: PolygonInput, + options: { throwOnError?: boolean } = {}, +): MultiPolygon { + return clip( + 'difference', + [a, b], + ([left, right]) => { + if (!left!.length) return [] + return right!.length ? clipping.difference(left!, right!) : clipping.union(left!) + }, + options.throwOnError, + ) +} + +export function intersection(a: PolygonInput, b: PolygonInput): MultiPolygon { + const bounds = (input: PolygonInput) => { + let minX = Infinity, + minZ = Infinity, + maxX = -Infinity, + maxZ = -Infinity + for (const { outer } of polygons(input)) + for (const [x, z] of outer) { + minX = Math.min(minX, x) + minZ = Math.min(minZ, z) + maxX = Math.max(maxX, x) + maxZ = Math.max(maxZ, z) + } + return [minX, minZ, maxX, maxZ] as const + } + const ab = bounds(a), + bb = bounds(b) + if ( + ab[2] + 1 / SCALE < bb[0] || + bb[2] + 1 / SCALE < ab[0] || + ab[3] + 1 / SCALE < bb[1] || + bb[3] + 1 / SCALE < ab[1] + ) + return [] + return clip('intersection', [a, b], ([left, right]) => + left!.length && right!.length ? clipping.intersection(left!, right!) : [], + ) +} + +export function area(multi: MultiPolygon): number { + return multi.reduce( + (sum, polygon) => + sum + + Math.abs(signedArea(polygon.outer)) - + polygon.holes.reduce((holes, ring) => holes + Math.abs(signedArea(ring)), 0), + 0, + ) +} + +function ringDistance(ring: Ring, p: [number, number]): number { + let distance = Number.POSITIVE_INFINITY + for (let i = 0; i < ring.length; i++) { + const a = ring[i]!, + b = ring[(i + 1) % ring.length]! + const dx = b[0] - a[0], + dz = b[1] - a[1] + const lengthSq = dx * dx + dz * dz + const t = lengthSq + ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / lengthSq)) + : 0 + distance = Math.min(distance, Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dz)) + } + return distance +} + +function insideRing(ring: Ring, p: [number, number]): boolean { + let inside = false + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const a = ring[i]!, + b = ring[j]! + if ( + a[1] > p[1] !== b[1] > p[1] && + p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0] + ) + inside = !inside + } + return inside +} + +/** Polygon boundaries, including hole rims, belong to the polygon. */ +export function containsPoint(multi: MultiPolygon, p: [number, number]): boolean { + for (const { outer, holes } of multi) { + if (ringDistance(outer, p) <= 1e-10) return true + let insideHole = false + for (const hole of holes) { + if (ringDistance(hole, p) <= 1e-10) return true + if (insideRing(hole, p)) insideHole = true + } + if (!insideHole && insideRing(outer, p)) return true + } + return false +} + +export function distanceToBoundary(multi: MultiPolygon, p: [number, number]): number { + return multi.reduce( + (distance, { outer, holes }) => + Math.min(distance, ...[outer, ...holes].map((ring) => ringDistance(ring, p))), + Number.POSITIVE_INFINITY, + ) +} diff --git a/packages/core/src/lib/polygon-label.ts b/packages/core/src/lib/polygon-label.ts new file mode 100644 index 0000000000..4461dc25cc --- /dev/null +++ b/packages/core/src/lib/polygon-label.ts @@ -0,0 +1,95 @@ +import { area, containsPoint, distanceToBoundary, type Polygon, type Ring } from './polygon-boolean' + +export function polygonCentroid(polygon: Polygon): [number, number] { + let weight = 0 + let x = 0 + let y = 0 + for (const [index, ring] of [polygon.outer, ...polygon.holes].entries()) { + let crossSum = 0 + let ringX = 0 + let ringY = 0 + for (let i = 0; i < ring.length; i++) { + const a = ring[i]! + const b = ring[(i + 1) % ring.length]! + const cross = a[0] * b[1] - b[0] * a[1] + crossSum += cross + ringX += (a[0] + b[0]) * cross + ringY += (a[1] + b[1]) * cross + } + if (crossSum === 0) continue + const sign = Math.sign(crossSum) * (index === 0 ? 1 : -1) + weight += sign * crossSum + x += sign * ringX + y += sign * ringY + } + return [x / (3 * weight), y / (3 * weight)] +} + +export function polygonInteriorPoint( + face: { polygon: Ring; holes?: Ring[] }, + preferCentroid = false, +): [number, number] { + const polygon = [{ outer: face.polygon, holes: face.holes ?? [] }] + if (face.polygon.length < 3 || area(polygon) <= 0) return face.polygon[0] ?? [0, 0] + const centroid = polygonCentroid(polygon[0]!) + if ( + preferCentroid && + containsPoint(polygon, centroid) && + distanceToBoundary(polygon, centroid) > 0 + ) + return centroid + + const xs = face.polygon.map(([x]) => x) + const ys = face.polygon.map(([, y]) => y) + const minX = Math.min(...xs) + const minY = Math.min(...ys) + const maxX = Math.max(...xs) + const maxY = Math.max(...ys) + const cell = (x: number, y: number, half: number) => { + const point: [number, number] = [x, y] + const distance = distanceToBoundary(polygon, point) * (containsPoint(polygon, point) ? 1 : -1) + return { point, half, distance, max: distance + half * Math.SQRT2 } + } + type Cell = ReturnType + const queue: Cell[] = [] + const push = (candidate: Cell) => { + let index = queue.length + queue.push(candidate) + while (index > 0) { + const parent = (index - 1) >> 1 + if (queue[parent]!.max >= candidate.max) break + queue[index] = queue[parent]! + index = parent + } + queue[index] = candidate + } + const pop = () => { + const first = queue[0]! + const last = queue.pop()! + if (queue.length) { + let index = 0 + while (index * 2 + 1 < queue.length) { + let child = index * 2 + 1 + if (child + 1 < queue.length && queue[child + 1]!.max > queue[child]!.max) child++ + if (last.max >= queue[child]!.max) break + queue[index] = queue[child]! + index = child + } + queue[index] = last + } + return first + } + let best = cell(face.polygon[0]![0], face.polygon[0]![1], 0) + push(cell((minX + maxX) / 2, (minY + maxY) / 2, Math.max(maxX - minX, maxY - minY) / 2)) + // Branch and bound finds the pole to 1 mm without assuming the face is convex or hole-free. + while (queue.length) { + const current = pop() + if (current.distance > best.distance) best = current + if (current.max - best.distance <= 0.001) continue + const half = current.half / 2 + for (const dx of [-half, half]) { + for (const dy of [-half, half]) push(cell(current.point[0] + dx, current.point[1] + dy, half)) + } + } + return best.point +} diff --git a/packages/core/src/lib/room-drawn-floor.test.ts b/packages/core/src/lib/room-drawn-floor.test.ts new file mode 100644 index 0000000000..bab4a52a2b --- /dev/null +++ b/packages/core/src/lib/room-drawn-floor.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, test } from 'bun:test' +import { setRoomFloorConstruction } from '../commands/structure/set-room-floor-construction' +import { setZoneIntent } from '../commands/structure/set-zone-intent' +import { type AnyNode, LevelNode, SlabNode, ZoneNode } from '../schema' +import { roomDrawnFloor } from './room-drawn-floor' + +type Ring = [number, number][] +const rect = (x0: number, z0: number, x1: number, z1: number): Ring => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], +] +const LEVEL = 'level_drawn' + +/** + * A legacy ground floor kept as drawn slabs: the old wall-generated slab (now + * a demoted manual slab at 0.05) under both rooms, the bedroom's own + * hand-drawn slab at 0.15 on top of it, and a hall floored by two drawn slabs. + */ +function scene(extra: AnyNode[] = []) { + const level = LevelNode.parse({ id: LEVEL, level: 0, height: 3 }) + const legacy = SlabNode.parse({ + id: 'slab_legacy', + name: 'Room 1 Slab', + parentId: LEVEL, + polygon: rect(0, 0, 12, 4), + elevation: 0.05, + thickness: 0.05, + metadata: { plateMigration: { demoted: 'wall-supported-floor' } }, + }) + const bedroomSlab = SlabNode.parse({ + id: 'slab_bedroom', + name: 'Slab 4', + parentId: LEVEL, + polygon: rect(0, 0, 4, 4), + elevation: 0.15, + thickness: 0.15, + }) + const hallHalf = SlabNode.parse({ + id: 'slab_hall_half', + name: 'Slab 2', + parentId: LEVEL, + polygon: rect(8, 0, 10, 4), + elevation: 0.15, + thickness: 0.15, + }) + const zone = (id: string, name: string, polygon: Ring, sourceSlabId?: `slab_${string}`) => + ZoneNode.parse({ + id, + name, + parentId: LEVEL, + spaceRole: 'room', + polygon, + floor: sourceSlabId ? { sourceSlabId, elevation: 0.05 } : undefined, + }) + const all = [ + level, + legacy, + bedroomSlab, + hallHalf, + zone('zone_bedroom', 'Master bedroom', rect(0, 0, 4, 4), 'slab_legacy'), + zone('zone_living', 'Living room', rect(4, 0, 8, 4), 'slab_legacy'), + zone('zone_hall', 'Hall', rect(8, 0, 12, 4), 'slab_legacy'), + ...extra, + ] + level.children = all.filter((node) => node.parentId === LEVEL).map((node) => node.id) as never + return Object.fromEntries(all.map((node) => [node.id, node])) as Record +} + +describe('roomDrawnFloor', () => { + test('names the drawn slab the room visibly stands on, not the hidden one it came from', () => { + const floor = roomDrawnFloor(scene(), 'zone_bedroom') + expect(floor).toEqual({ + sourceId: 'slab_legacy', + slabId: 'slab_bedroom', + sharedZoneIds: [], + ambiguous: false, + }) + }) + + test('a room on the source slab itself shares it with every room it floors', () => { + const floor = roomDrawnFloor(scene(), 'zone_living') + expect(floor?.slabId).toBe('slab_legacy') + expect(floor?.sharedZoneIds).toEqual(['zone_bedroom', 'zone_hall']) + expect(floor?.ambiguous).toBe(false) + }) + + test('two drawn slabs showing in one room make it ambiguous', () => { + const floor = roomDrawnFloor(scene(), 'zone_hall') + expect(floor?.ambiguous).toBe(true) + // Equal shares: the higher slab names the floor. + expect(floor?.slabId).toBe('slab_hall_half') + }) + + test('a drawn-slab room with its floor switched off still stands on the slab', () => { + const nodes = scene() + const bedroom = nodes.zone_bedroom as ZoneNode + nodes.zone_bedroom = { ...bedroom, hasFloor: false } + expect(roomDrawnFloor(nodes, 'zone_bedroom')?.slabId).toBe('slab_bedroom') + }) + + test('rooms on generated plates, without a source, or on a mezzanine are not drawn-slab rooms', () => { + const nodes = scene([ + ZoneNode.parse({ + id: 'zone_plain', + name: 'zone_plain', + parentId: LEVEL, + spaceRole: 'room', + polygon: rect(20, 0, 24, 4), + }), + ZoneNode.parse({ + id: 'zone_mezz', + name: 'zone_mezz', + parentId: LEVEL, + spaceRole: 'room', + polygon: rect(0, 0, 2, 2), + floor: { support: 'open', elevation: 1.5, sourceSlabId: 'slab_legacy' }, + }), + ZoneNode.parse({ + id: 'zone_far', + name: 'zone_far', + parentId: LEVEL, + spaceRole: 'room', + polygon: rect(30, 0, 34, 4), + // A source that no longer reaches the room does not keep it off plates. + floor: { sourceSlabId: 'slab_legacy' }, + }), + ]) + expect(roomDrawnFloor(nodes, 'zone_plain')).toBeNull() + expect(roomDrawnFloor(nodes, 'zone_mezz')).toBeNull() + expect(roomDrawnFloor(nodes, 'zone_far')).toBeNull() + const plated = { + ...nodes, + slab_legacy: { ...nodes.slab_legacy, plateRole: 'base', boundary: 'auto' } as AnyNode, + } + expect(roomDrawnFloor(plated, 'zone_living')).toBeNull() + }) +}) + +describe('a drawn-slab room refuses a floor height', () => { + test('setZoneIntent refuses a new elevation and names the slab to edit', () => { + const plan = setZoneIntent(scene(), { + zoneId: 'zone_bedroom', + patch: { floor: { elevation: 0.8 } }, + }) + expect(plan.changes).toEqual([]) + expect(plan.conflicts).toHaveLength(1) + expect(plan.conflicts![0]!.code).toBe('room-drawn-floor') + expect(plan.conflicts![0]!.nodeIds).toEqual(['zone_bedroom', 'slab_bedroom']) + expect(plan.conflicts![0]!.message).toContain('"Slab 4" (slab_bedroom)') + }) + + test('other floor intent, an unchanged height and clearing the height still apply', () => { + const nodes = scene() + for (const floor of [ + { finish: 'library:preset-white' }, + { elevation: 0.05 }, + { elevation: null }, + ]) { + const plan = setZoneIntent(nodes, { zoneId: 'zone_bedroom', patch: { floor } }) + expect(plan.conflicts).toBeUndefined() + } + const cleared = setZoneIntent(nodes, { + zoneId: 'zone_bedroom', + patch: { floor: { elevation: null } }, + }) + expect(cleared.changes).toEqual([ + { op: 'update', id: 'zone_bedroom', data: { floor: { sourceSlabId: 'slab_legacy' } } }, + ]) + }) + + test('a room that is not a drawn-slab room keeps its floor height', () => { + const nodes = scene([ + ZoneNode.parse({ + id: 'zone_plain', + name: 'zone_plain', + parentId: LEVEL, + spaceRole: 'room', + polygon: rect(20, 0, 24, 4), + }), + ]) + const plan = setZoneIntent(nodes, { + zoneId: 'zone_plain', + patch: { floor: { elevation: 0.3 } }, + }) + expect(plan.conflicts).toBeUndefined() + expect(plan.changes).toHaveLength(1) + }) + + test('floor construction edits the visible drawn slab by default', () => { + const plan = setRoomFloorConstruction(scene(), { + zoneId: 'zone_bedroom', + patch: { thickness: 0.2 }, + }) + expect(plan.conflicts).toBeUndefined() + expect(plan.changes).toEqual([{ op: 'update', id: 'slab_bedroom', data: { thickness: 0.2 } }]) + }) +}) diff --git a/packages/core/src/lib/room-drawn-floor.ts b/packages/core/src/lib/room-drawn-floor.ts new file mode 100644 index 0000000000..ad8ba31b55 --- /dev/null +++ b/packages/core/src/lib/room-drawn-floor.ts @@ -0,0 +1,123 @@ +import type { AnyNode, SlabNode, ZoneNode } from '../schema' +import { + area, + difference, + intersection, + type MultiPolygon, + type Polygon, + union, +} from './polygon-boolean' + +/** + * A room whose floor is a hand-drawn slab (legacy or authored), not a generated + * plate. Plate derivation skips such a room (see `buildFloorPlates`), so a + * room floor height would move nothing: the slab itself is what to edit. + */ +export type RoomDrawnFloor = { + /** The slab the room's floor was taken from (`floor.sourceSlabId`). */ + sourceId: string + /** The drawn slab the room visibly stands on: the one showing over most of its floor. */ + slabId: string + /** Other rooms that slab also floors. */ + sharedZoneIds: string[] + /** More than one drawn slab shows in the room; `slabId` is the largest. */ + ambiguous: boolean +} + +type Nodes = Readonly> + +const isDrawnSlab = (node: AnyNode | undefined): node is SlabNode => + node?.type === 'slab' && !node.plateRole && node.boundary !== 'auto' && !node.autoFromWalls + +const footprint = (node: { polygon: SlabNode['polygon']; holes?: SlabNode['holes'] }): Polygon => ({ + outer: node.polygon, + holes: node.holes ?? [], +}) + +const memo = new WeakMap>() + +export function roomDrawnFloor(nodes: Nodes, zoneId: string): RoomDrawnFloor | null { + let cache = memo.get(nodes) + if (!cache) { + cache = new Map() + memo.set(nodes, cache) + } + if (!cache.has(zoneId)) cache.set(zoneId, computeRoomDrawnFloor(nodes, zoneId)) + return cache.get(zoneId)! +} + +function computeRoomDrawnFloor(nodes: Nodes, zoneId: string): RoomDrawnFloor | null { + const zone = nodes[zoneId] + // A switched-off floor (`hasFloor: false`) still names its slab: the drawn + // slab stays visible, so the room stands on it all the same. + if ( + zone?.type !== 'zone' || + !zone.parentId || + zone.floor?.support === 'open' || + !zone.floor?.sourceSlabId + ) + return null + const source = nodes[zone.floor.sourceSlabId] + if (!isDrawnSlab(source) || source.parentId !== zone.parentId) return null + const room = footprint(zone) + // The same overlap that keeps the room out of plate derivation. + if (area(intersection(room, footprint(source))) <= 1e-4) return null + const roomArea = area([room]) + const slabs = Object.values(nodes) + .filter( + (node): node is SlabNode => + isDrawnSlab(node) && + node.parentId === zone.parentId && + node.visible !== false && + node.support !== 'open' && + !node.recessed, + ) + .sort((a, b) => b.elevation - a.elevation || a.id.localeCompare(b.id)) + // Top down: each slab shows where no higher slab already covers the room. + let covered: MultiPolygon = [] + const shown: Array<{ slab: SlabNode; visible: number }> = [] + for (const slab of slabs) { + const inRoom = intersection(footprint(slab), room) + if (area(inRoom) <= 1e-4) continue + const visible = covered.length ? area(difference(inRoom, covered)) : area(inRoom) + covered = union([...covered, ...inRoom]) + if (visible > 1e-4) shown.push({ slab, visible }) + } + shown.sort((a, b) => b.visible - a.visible || b.slab.elevation - a.slab.elevation) + const slab = shown[0]?.slab ?? source + const minor = Math.max(0.05, roomArea * 0.02) + const sharedZoneIds = Object.values(nodes) + .filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.id !== zone.id && + node.parentId === zone.parentId && + node.spaceRole === 'room' && + node.floor?.support !== 'open' && + area(intersection(footprint(node), footprint(slab))) > 0.05, + ) + .map((node) => node.id) + .sort() + return { + sourceId: source.id, + slabId: slab.id, + sharedZoneIds, + ambiguous: shown.filter((entry) => entry.visible > minor).length > 1, + } +} + +/** + * The refusal for a floor height on a drawn-slab room: the height lives on the + * slab, so the room names it instead of storing a height nothing reads. + */ +export function drawnFloorElevationConflict(nodes: Nodes, zoneId: string) { + const floor = roomDrawnFloor(nodes, zoneId) + if (!floor) return null + const slab = nodes[floor.slabId] as SlabNode + const name = slab.name?.trim() || 'a drawn slab' + return { + code: 'room-drawn-floor' as const, + nodeIds: [zoneId, floor.slabId], + message: `This room's floor is ${name === 'a drawn slab' ? name : `the drawn slab "${name}"`} (${floor.slabId}). Its height is the slab's: change that slab's elevation instead.`, + } +} diff --git a/packages/core/src/lib/room-floor-choices.ts b/packages/core/src/lib/room-floor-choices.ts new file mode 100644 index 0000000000..2c60cf08a4 --- /dev/null +++ b/packages/core/src/lib/room-floor-choices.ts @@ -0,0 +1,73 @@ +import { boundaries, roomFace } from '../commands/structure/shared' +import type { AnyNode, SlabNode } from '../schema' +import { floorFootprintName } from './floor-footprint-name' +import { floorRoomFaces } from './floor-room-faces' +import { area, intersection, union } from './polygon-boolean' +import { roomDrawnFloor } from './room-drawn-floor' + +export type RoomFloorChoice = { + key: string | null + plateId: string + name: string + current: boolean + drawn?: boolean + mezzanine?: boolean +} + +export function roomFloorChoices( + nodes: Readonly>, + zoneId: string, +): RoomFloorChoice[] { + const zone = nodes[zoneId] + if (zone?.type !== 'zone' || zone.spaceRole !== 'room' || !zone.parentId) return [] + const drawn = roomDrawnFloor(nodes, zoneId) + const faces = floorRoomFaces(boundaries(nodes, zone.parentId)) + const face = roomFace(nodes, zone, faces) + const adjacent = new Set([zoneId]) + for (const room of Object.values(nodes)) { + if (room.type !== 'zone' || room.parentId !== zone.parentId) continue + if ( + roomFace(nodes, room, faces)?.spans.some((other) => + face?.spans.some( + (span) => + span.boundaryId === other.boundaryId && + span.face !== other.face && + Math.min(span.t1, other.t1) - Math.max(span.t0, other.t0) > 1e-6, + ), + ) + ) + adjacent.add(room.id) + } + const footprint = { outer: zone.polygon, holes: zone.holes } + const plates = Object.values(nodes).filter((node): node is SlabNode => { + if (node.type !== 'slab' || node.parentId !== zone.parentId) return false + if (node.id === drawn?.slabId) return true + if (node.support === 'open') return !!node.zoneIds?.includes(zoneId) + if (node.plateRole !== 'base') return false + if (node.zoneIds?.some((id) => adjacent.has(id))) return true + const plate = { outer: node.polygon, holes: node.holes } + return area(intersection(footprint, plate)) > 1e-6 || union([footprint, plate]).length === 1 + }) + const choices = plates + .map((plate): RoomFloorChoice => { + const owner = (plate.zoneIds ?? []) + .map((id) => nodes[id]) + .find((node) => node?.type === 'zone') + return { + key: owner?.type === 'zone' ? (owner.floor?.footprint ?? null) : null, + plateId: plate.id, + name: floorFootprintName(nodes, plate), + current: drawn ? plate.id === drawn.slabId : !!plate.zoneIds?.includes(zoneId), + ...(plate.id === drawn?.slabId ? { drawn: true } : {}), + ...(plate.support === 'open' ? { mezzanine: true } : {}), + } + }) + .sort((a, b) => Number(b.current) - Number(a.current) || a.plateId.localeCompare(b.plateId)) + const seen = new Set() + return choices.filter((choice) => { + const identity = choice.key ?? choice.plateId + if (seen.has(identity)) return false + seen.add(identity) + return true + }) +} diff --git a/packages/core/src/lib/room-floor-feasibility.ts b/packages/core/src/lib/room-floor-feasibility.ts new file mode 100644 index 0000000000..aafa460527 --- /dev/null +++ b/packages/core/src/lib/room-floor-feasibility.ts @@ -0,0 +1,401 @@ +import { boundaries, roomFace } from '../commands/structure/shared' +import type { AnyNode, SlabNode, WallNode } from '../schema' +import { + DEFAULT_SLAB_ELEVATION, + MIN_GROUND_FLOOR_THICKNESS, + MIN_SLAB_THICKNESS, +} from '../schema/nodes/slab' +import { getStoredLevelHeight, getWallPlaneTop } from '../services/storey' +import { getWallCurveFrameAt, getWallCurveLength } from '../systems/wall/wall-curve' +import { MIN_WALL_HEIGHT, resolveWallTop } from '../systems/wall/wall-top' +import { floorPlateHoldsUnderside, footprintLift } from './floor-foundation-datum' +import { isFloorAnchoredOpening } from './floor-opening-footprints' +import { floorRoomFaces } from './floor-room-faces' +import { + getOpeningFloorTarget, + openingFitsAtDatum, + supportSegmentAt, + wallSupportForNodes, +} from './opening-floor-datum' +import { area, intersection, union } from './polygon-boolean' +import { autoRoomVerticalPlacements } from './room-vertical-placement' + +export const FLOOR_ELEVATION_EPSILON = 0.001 +export { MIN_GROUND_FLOOR_THICKNESS, MIN_SLAB_THICKNESS } + +export type RoomFloorConflict = { + code: + | 'floor-foundation-level' + | 'floor-foundation-shared-storey' + | 'floor-plate-thickness' + | 'floor-wall-fit' + | 'floor-headroom' + | 'floor-opening-fit' + | 'floor-window-sill' + | 'floor-sunken-depth' + | 'floor-low-headroom' + | 'floor-door-step' + | 'floor-door-swing' + nodeIds: string[] + message: string + severity: 'error' | 'warning' + excess?: number +} + +const roomBaseMemo = new WeakMap>() + +export function getRoomBaseElevation( + nodes: Readonly>, + zoneId: string, +): number { + const zone = nodes[zoneId] + const levelId = zone?.parentId + if (!levelId) return DEFAULT_SLAB_ELEVATION + const plate = Object.values(nodes).find( + (node): node is SlabNode => + node.type === 'slab' && + node.plateRole === 'base' && + !!node.zoneIds?.includes(zoneId as never), + ) + if (plate) return plate.floorHeight ?? plate.elevation + if ( + zone?.type !== 'zone' || + zone.spaceRole !== 'room' || + zone.hasFloor === false || + zone.enclosureStatus === 'open' || + zone.floor?.support === 'open' + ) + return DEFAULT_SLAB_ELEVATION + let cache = roomBaseMemo.get(nodes) + if (!cache) { + cache = new Map() + roomBaseMemo.set(nodes, cache) + } + const cached = cache.get(zoneId) + if (cached !== undefined) return cached + const face = roomFace(nodes, zone, floorRoomFaces(boundaries(nodes, levelId))) + if (!face) return DEFAULT_SLAB_ELEVATION + const polygon = { outer: face.referencePolygon, holes: face.holes } + const covered = union( + Object.values(nodes).flatMap((node) => + node.type === 'slab' && + node.parentId === levelId && + !node.autoFromWalls && + node.boundary !== 'auto' + ? intersection(polygon, { outer: node.polygon, holes: node.holes }) + : [], + ), + ) + const elevation = + area(covered) >= area([polygon]) * 0.6 + ? DEFAULT_SLAB_ELEVATION + : (autoRoomVerticalPlacements([{ ...face, zone }], nodes).get(zone.id) ?? + DEFAULT_SLAB_ELEVATION) + cache.set(zoneId, elevation) + return elevation +} + +const automaticBaseMemo = new Map>() + +export function automaticRoomBaseElevations( + nodes: Readonly>, + levelId: string, +): ReadonlyMap { + const signature = JSON.stringify([ + levelId, + Object.values(nodes) + .filter( + (node) => + node.type === 'site' || + node.type === 'building' || + node.type === 'level' || + (node.parentId === levelId && + (node.type === 'wall' || + node.type === 'separator' || + node.type === 'zone' || + (node.type === 'slab' && !node.autoFromWalls && node.boundary !== 'auto'))), + ) + .map((node) => + node.type === 'zone' + ? { + id: node.id, + type: node.type, + parentId: node.parentId, + polygon: node.polygon, + holes: node.holes, + seed: node.seed, + spaceRole: node.spaceRole, + hasFloor: node.hasFloor, + enclosureStatus: node.enclosureStatus, + support: node.floor?.support, + boundaryWallIds: node.boundaryWallIds, + boundarySeparatorIds: node.boundarySeparatorIds, + } + : node, + ), + ]) + const hit = automaticBaseMemo.get(signature) + if (hit) return hit + const faces = floorRoomFaces(boundaries(nodes, levelId)) + const manual = union( + Object.values(nodes).flatMap((node) => + node.type === 'slab' && + node.parentId === levelId && + node.boundary !== 'auto' && + !node.autoFromWalls + ? [{ outer: node.polygon, holes: node.holes }] + : [], + ), + ) + const rooms = Object.values(nodes).flatMap((zone) => { + if ( + zone.type !== 'zone' || + zone.parentId !== levelId || + zone.spaceRole !== 'room' || + zone.hasFloor === false || + zone.enclosureStatus === 'open' || + zone.floor?.support === 'open' + ) + return [] + const face = roomFace(nodes, zone, faces) + if (!face) return [] + const polygon = { outer: face.referencePolygon, holes: face.holes } + return area(intersection(polygon, manual)) >= area([polygon]) * 0.6 + ? [] + : [{ ...face, id: zone.id, polygon: face.referencePolygon, zone }] + }) + const placements = autoRoomVerticalPlacements(rooms, nodes) + if (automaticBaseMemo.size >= 32) automaticBaseMemo.delete(automaticBaseMemo.keys().next().value!) + automaticBaseMemo.set(signature, placements) + return placements +} + +const feasibilityMemo = new WeakMap>>() + +export function checkRoomFloor( + nodes: Readonly>, + zoneId: string, + proposedElevation: number, +) { + let cache = feasibilityMemo.get(nodes) + if (!cache) { + cache = new Map() + feasibilityMemo.set(nodes, cache) + } + const key = `${zoneId}:${proposedElevation}` + const hit = cache.get(key) + if (hit) return hit + const result = computeRoomFloor(nodes, zoneId, proposedElevation) + cache.set(key, result) + return result +} + +function computeRoomFloor( + nodes: Readonly>, + zoneId: string, + proposedElevation: number, +) { + const zone = nodes[zoneId] + if (zone?.type !== 'zone') throw new Error(`Room not found: ${zoneId}`) + const level = nodes[zone.parentId!] + if (level?.type !== 'level') throw new Error(`Level not found: ${zone.parentId}`) + const candidate = + (zone.floor?.elevation ?? getRoomBaseElevation(nodes, zoneId)) === proposedElevation + ? nodes + : { + ...nodes, + [zoneId]: { ...zone, floor: { ...zone.floor, elevation: proposedElevation } }, + } + const linked = zone.boundaryWallIds?.length ? new Set(zone.boundaryWallIds) : undefined + const spans = linked + ? [] + : (roomFace(nodes, zone, floorRoomFaces(boundaries(nodes, zone.parentId!)))?.spans ?? []) + const walls = Object.values(nodes).filter( + (node): node is WallNode => + node.type === 'wall' && + (linked?.has(node.id) ?? spans.some((span) => span.boundaryId === node.id)), + ) + const conflicts: RoomFloorConflict[] = [] + const hints: RoomFloorConflict[] = [] + let ceiling = getStoredLevelHeight(level) + let minElevation = Number.NEGATIVE_INFINITY + let maxElevation = getStoredLevelHeight(level) - MIN_WALL_HEIGHT + const base = Object.values(nodes).find( + (node): node is SlabNode => + node.type === 'slab' && + node.parentId === level.id && + node.plateRole === 'base' && + !!node.zoneIds?.includes(zone.id), + ) + const lift = base ? footprintLift(nodes, base) : 0 + ceiling += lift + maxElevation += lift + if (zone.floor?.support !== 'open' && base && floorPlateHoldsUnderside(nodes, base)) { + minElevation = + getRoomBaseElevation(nodes, zoneId) - (base?.thickness ?? 0.05) + MIN_SLAB_THICKNESS + if (proposedElevation < minElevation - 1e-9) + conflicts.push({ + code: 'floor-sunken-depth', + excess: minElevation - proposedElevation, + nodeIds: [zoneId, ...(base ? [base.id] : [])], + severity: 'error', + message: `Floor must be at least ${roundFloorElevation(minElevation)} m to retain the level soffit.`, + }) + } + for (const wall of walls) { + const hasOpenings = wall.children.some( + (id) => nodes[id]?.type === 'door' || nodes[id]?.type === 'window', + ) + const support = + hasOpenings || wall.height !== undefined ? wallSupportForNodes(wall, candidate) : undefined + const top = resolveWallTop( + wall, + getWallPlaneTop(wall, level.id, nodes), + support?.elevation ?? 0, + ) + const openingSpans = + hasOpenings && linked + ? (roomFace(nodes, zone, floorRoomFaces(boundaries(nodes, zone.parentId!)))?.spans ?? []) + : spans + maxElevation = Math.min(maxElevation, top - MIN_WALL_HEIGHT) + ceiling = Math.min(ceiling, top) + const length = getWallCurveLength(wall) + for (const id of wall.children) { + const opening = nodes[id] + if (opening?.type !== 'door' && opening?.type !== 'window') continue + const chord = (distance: number) => { + const point = getWallCurveFrameAt(wall, distance / length).point + const dx = wall.end[0] - wall.start[0], + dz = wall.end[1] - wall.start[1] + return ( + ((point.x - wall.start[0]) * dx + (point.y - wall.start[1]) * dz) / (dx * dx + dz * dz) + ) + } + const from = chord(opening.position[0] - opening.width / 2), + to = chord(opening.position[0] + opening.width / 2) + if ( + !openingSpans.some( + (span) => span.boundaryId === wall.id && Math.min(to, span.t1) > Math.max(from, span.t0), + ) + ) + continue + const datum = getOpeningFloorTarget(wall, opening, candidate) + const bottom = opening.position[1] - opening.height / 2 + if (isFloorAnchoredOpening(opening)) { + if (opening.type === 'door') { + const from = Math.max(0, (opening.position[0] - opening.width / 2) / length) + const to = Math.min(1, (opening.position[0] + opening.width / 2) / length) + const floors = (face: 'a' | 'b') => + support!.faceDatum[face].flatMap((run) => { + const start = Math.max(from, run.start), + end = Math.min(to, run.end) + return end > start ? [supportSegmentAt(run, start), supportSegmentAt(run, end)] : [] + }) + const lower = Math.min(datum, ...floors('a'), ...floors('b')) + if (datum - lower > 0.2 + 1e-9) + hints.push({ + code: 'floor-door-step', + nodeIds: [zoneId, id], + severity: 'warning', + message: 'The doorway step exceeds 20 cm and needs steps.', + }) + const swingsToA = + (opening.swingDirection === 'inward') === Math.cos(opening.rotation[1]) >= 0 + if ( + ['hinged', 'double', 'french'].includes(opening.doorType) && + datum - Math.min(datum, ...floors(swingsToA ? 'a' : 'b')) > 0.02 + 1e-9 + ) + hints.push({ + code: 'floor-door-swing', + nodeIds: [zoneId, id], + severity: 'warning', + message: 'The door swings toward the lower floor across a step.', + }) + } + const limit = top - opening.position[1] - opening.height / 2 + maxElevation = Math.min(maxElevation, limit) + if (!openingFitsAtDatum(wall, opening, datum, candidate, support)) + conflicts.push({ + code: 'floor-opening-fit', + excess: datum + opening.position[1] + opening.height / 2 - top, + nodeIds: [zoneId, id], + severity: 'error', + message: `Floor must be at most ${roundFloorElevation(limit)} m for ${opening.name || opening.type} to fit.`, + }) + } else if (datum + bottom < proposedElevation - FLOOR_ELEVATION_EPSILON) + conflicts.push({ + code: 'floor-window-sill', + nodeIds: [zoneId, id], + severity: 'warning', + message: 'The opening sill is below the room floor.', + }) + } + } + if ( + proposedElevation > maxElevation + 1e-9 && + !conflicts.some((c) => c.code === 'floor-opening-fit') + ) + conflicts.push({ + code: 'floor-headroom', + excess: proposedElevation - maxElevation, + nodeIds: [zoneId], + severity: 'error', + message: `Floor must be at most ${roundFloorElevation(maxElevation)} m to retain minimum headroom.`, + }) + if (ceiling - proposedElevation < 2.1 - 1e-9) + hints.push({ + code: 'floor-low-headroom', + nodeIds: [zoneId], + severity: 'warning', + message: 'Headroom is below 2.10 m.', + }) + conflicts.push(...hints) + const elevation = Math.max(minElevation, Math.min(maxElevation, proposedElevation)) + return { + conflicts, + minElevation, + maxElevation, + elevation, + clamped: elevation !== proposedElevation, + } +} + +export function roundFloorElevation(elevation: number): number { + return Math.round(elevation * 1e6) / 1e6 +} + +export function getRoomRelativeFloorElevation( + nodes: Readonly>, + zoneId: string, +): number { + const zone = nodes[zoneId] + return roundFloorElevation( + ((zone?.type === 'zone' ? zone.floor?.elevation : undefined) ?? + getRoomBaseElevation(nodes, zoneId)) - getRoomBaseElevation(nodes, zoneId), + ) +} + +export function roomFloorElevationFromRelative( + nodes: Readonly>, + zoneId: string, + height: number, +): number { + return roundFloorElevation(getRoomBaseElevation(nodes, zoneId) + height) +} + +export function clampRoomFloorHandle( + nodes: Readonly>, + zoneId: string, + proposed: number, +): number { + const check = checkRoomFloor(nodes, zoneId, proposed) + const zone = nodes[zoneId] + const current = + zone?.type === 'zone' + ? (zone.floor?.elevation ?? getRoomBaseElevation(nodes, zoneId)) + : proposed + // Existing overloads may improve incrementally without snapping to another floor. + const max = Math.max(current, Math.floor((check.maxElevation + 1e-9) / 0.05) * 0.05) + const min = Math.min(current, Math.ceil((check.minElevation - 1e-9) / 0.05) * 0.05) + return roundFloorElevation(Math.max(min, Math.min(max, proposed))) +} diff --git a/packages/core/src/lib/room-floor-plate.ts b/packages/core/src/lib/room-floor-plate.ts new file mode 100644 index 0000000000..9baaa233c7 --- /dev/null +++ b/packages/core/src/lib/room-floor-plate.ts @@ -0,0 +1,6 @@ +import type { SlabNode } from '../schema' + +export function roomFloorPlate(slabs: readonly SlabNode[], zoneId: string): SlabNode | undefined { + const owned = slabs.filter((slab) => slab.zoneIds?.includes(zoneId)) + return owned.find((slab) => slab.plateRole !== 'base') ?? owned[0] +} diff --git a/packages/core/src/lib/room-graph.ts b/packages/core/src/lib/room-graph.ts new file mode 100644 index 0000000000..465265c8e6 --- /dev/null +++ b/packages/core/src/lib/room-graph.ts @@ -0,0 +1,1294 @@ +import type { SeparatorNode, WallNode } from '../schema' +import { getWallArcData, getWallCurveFrameAt, isCurvedWall } from '../systems/wall/wall-curve' +import { getWallBodyCenterOffset, getWallFaceOffsets } from '../systems/wall/wall-frame' +import { area, difference, intersection, type Ring, union } from './polygon-boolean' +import type { BoundaryNode, BoundarySpan } from './room-topology-index' + +export type Point2D = { x: number; y: number } +type JunctionVertex = Point2D & { wallEndpoint: boolean } + +export type SpaceBoundaryFace = { + wallId: WallNode['id'] + face: 'front' | 'back' + points: Array<[number, number]> +} + +export type ExtractedRoom = { + id: string + referencePolygon: Array<[number, number]> + holes: Array> + spans: BoundarySpan[] + polygon: Point2D[] + boundaryFaces: SpaceBoundaryFace[] +} + +const ROOM_CURVE_TOLERANCE = 0.04 +const MAX_CURVE_SUBDIVISION_DEPTH = 6 +export const WALL_JUNCTION_TOLERANCE = 0.08 + +export function pointFromTuple(point: [number, number]): Point2D { + return { x: point[0], y: point[1] } +} + +export function pointToTuple(point: Point2D): [number, number] { + return [point.x, point.y] +} + +function pointKey(point: Point2D) { + return `${point.x.toFixed(3)},${point.y.toFixed(3)}` +} + +export function polygonArea(points: Point2D[]) { + let area = 0 + for (let i = 0; i < points.length; i++) { + const a = points[i] + const b = points[(i + 1) % points.length] + if (!(a && b)) continue + area += a.x * b.y - b.x * a.y + } + return area / 2 +} + +function minRotationSignature(keys: string[]) { + if (keys.length === 0) return '' + let best = '' + for (let i = 0; i < keys.length; i++) { + const rotated = [...keys.slice(i), ...keys.slice(0, i)] + const value = rotated.join('|') + if (!best || value < best) best = value + } + return best +} + +export function polygonSignature(points: Point2D[]) { + const keys = points.map(pointKey) + const forward = minRotationSignature(keys) + const reversed = minRotationSignature([...keys].reverse()) + return forward < reversed ? forward : reversed +} + +function samePointWithinTolerance(a: Point2D, b: Point2D, tolerance = 1e-4) { + return Math.hypot(a.x - b.x, a.y - b.y) <= tolerance +} + +export function dedupeSequentialPoints(points: Point2D[], tolerance = 1e-4) { + const deduped: Point2D[] = [] + + for (const point of points) { + const previous = deduped[deduped.length - 1] + if (previous && samePointWithinTolerance(previous, point, tolerance)) { + continue + } + deduped.push(point) + } + + const firstPoint = deduped[0] + const lastPoint = deduped[deduped.length - 1] + if ( + deduped.length > 2 && + firstPoint && + lastPoint && + samePointWithinTolerance(firstPoint, lastPoint, tolerance) + ) { + deduped.pop() + } + + return deduped +} + +export function bboxOf(points: Point2D[]) { + let minX = Number.POSITIVE_INFINITY + let minY = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let maxY = Number.NEGATIVE_INFINITY + + for (const point of points) { + minX = Math.min(minX, point.x) + minY = Math.min(minY, point.y) + maxX = Math.max(maxX, point.x) + maxY = Math.max(maxY, point.y) + } + + return { minX, minY, maxX, maxY } +} + +function pointLineDistance(point: Point2D, start: Point2D, end: Point2D) { + const dx = end.x - start.x + const dy = end.y - start.y + const lengthSquared = dx * dx + dy * dy + + if (lengthSquared < 1e-9) { + return Math.hypot(point.x - start.x, point.y - start.y) + } + + const cross = (point.x - start.x) * dy - (point.y - start.y) * dx + return Math.abs(cross) / Math.sqrt(lengthSquared) +} + +export function sampleWallPointsForRoomDetection( + wall: Pick, + tolerance = ROOM_CURVE_TOLERANCE, +) { + const start = { x: wall.start[0], y: wall.start[1] } + const end = { x: wall.end[0], y: wall.end[1] } + + if (!isCurvedWall(wall)) { + return [start, end] + } + + const subdivide = ( + t0: number, + p0: Point2D, + t1: number, + p1: Point2D, + depth: number, + ): Point2D[] => { + const midT = (t0 + t1) / 2 + const midPoint = getWallCurveFrameAt(wall, midT).point + const deviation = pointLineDistance(midPoint, p0, p1) + + if (depth >= MAX_CURVE_SUBDIVISION_DEPTH || deviation <= tolerance) { + return [p0, p1] + } + + const left = subdivide(t0, p0, midT, midPoint, depth + 1) + const right = subdivide(midT, midPoint, t1, p1, depth + 1) + return [...left.slice(0, -1), ...right] + } + + return subdivide(0, start, 1, end, 0) +} + +function segmentProjection(point: Point2D, start: Point2D, end: Point2D) { + const dx = end.x - start.x + const dy = end.y - start.y + const lengthSquared = dx * dx + dy * dy + if (lengthSquared < 1e-12) { + return { t: 0, distance: Math.hypot(point.x - start.x, point.y - start.y) } + } + const t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared + const clampedT = Math.max(0, Math.min(1, t)) + const projX = start.x + clampedT * dx + const projY = start.y + clampedT * dy + return { t, distance: Math.hypot(point.x - projX, point.y - projY) } +} + +// Break a straight wall at any junction vertex (another wall's endpoint) that +// lands on its interior, returning the ordered polyline [start, …splits, end]. +// Splitting at the *vertex* position (not the projection) keeps the split node's +// key identical to the touching wall's endpoint so the two share a graph node. +function splitStraightWallAtVertices( + start: Point2D, + end: Point2D, + vertices: JunctionVertex[], + separator = false, +) { + const length = Math.hypot(end.x - start.x, end.y - start.y) + if (length < 1e-9) return [start, end] + + const interior: Array<{ point: Point2D; t: number }> = [] + for (const vertex of vertices) { + // Separators have authored/snapped coordinates; proximity must not pull an + // island into a nearby wall or bend another segment of a multi-point path. + const tolerance = separator || !vertex.wallEndpoint ? 1e-6 : WALL_JUNCTION_TOLERANCE + const { t, distance } = segmentProjection(vertex, start, end) + if (distance > tolerance) continue + const along = t * length + if (along <= tolerance || along >= length - tolerance) continue + interior.push({ point: { x: vertex.x, y: vertex.y }, t }) + } + interior.sort((a, b) => a.t - b.t) + + const ordered: Point2D[] = [start] + let lastKey = pointKey(start) + for (const { point } of interior) { + const key = pointKey(point) + if (key === lastKey) continue + ordered.push(point) + lastKey = key + } + if (lastKey !== pointKey(end)) ordered.push(end) + return ordered +} + +function splitCurvedWallAtVertices( + points: Point2D[], + vertices: JunctionVertex[], + wall: BoundaryNode, +): Point2D[][] { + const arc = getWallArcData(wall) + const stations = [0] + for (let i = 1; i < points.length; i++) { + stations.push( + stations[i - 1]! + + Math.hypot(points[i]!.x - points[i - 1]!.x, points[i]!.y - points[i - 1]!.y), + ) + } + const length = stations.at(-1)! + const cuts = [ + { point: points[0]!, station: 0 }, + { point: points.at(-1)!, station: length }, + ] + for (const vertex of vertices) { + // Divide snaps to 64 chord samples; allow their sagitta, not the wall-junction radius. + const separatorTolerance = arc ? arc.radius * (1 - Math.cos(arc.delta / 128)) + 1e-6 : 1e-6 + if ( + !vertex.wallEndpoint && + arc && + Math.abs(Math.hypot(vertex.x - arc.center.x, vertex.y - arc.center.y) - arc.radius) > + separatorTolerance + ) + continue + const endpointTolerance = vertex.wallEndpoint ? WALL_JUNCTION_TOLERANCE : 1e-6 + let best = { distance: Number.POSITIVE_INFINITY, station: 0 } + for (let i = 0; i < points.length - 1; i++) { + const { t, distance } = segmentProjection(vertex, points[i]!, points[i + 1]!) + if (distance >= best.distance) continue + best = { + distance, + station: stations[i]! + Math.max(0, Math.min(1, t)) * (stations[i + 1]! - stations[i]!), + } + } + if ( + best.distance > WALL_JUNCTION_TOLERANCE || + best.station <= endpointTolerance || + best.station >= length - endpointTolerance + ) + continue + cuts.push({ point: { x: vertex.x, y: vertex.y }, station: best.station }) + } + cuts.sort((a, b) => a.station - b.station) + return cuts.slice(0, -1).flatMap((cut, i) => { + const next = cuts[i + 1]! + if (pointKey(cut.point) === pointKey(next.point)) return [] + return [ + dedupeSequentialPoints([ + cut.point, + ...points.filter( + (_, j) => stations[j]! > cut.station + 1e-8 && stations[j]! < next.station - 1e-8, + ), + next.point, + ]), + ] + }) +} + +// Reference half-edges determine connectivity; body lines keep room geometry invariant +// when a reference moves beneath an unchanged wall body. +function roomBodyPolygon(edges: Array<{ wall: BoundaryNode; points: Point2D[] }>): Point2D[] { + const shifted = edges.map(({ wall, points }) => { + const offset = wall.type === 'wall' ? getWallBodyCenterOffset(wall) : 0 + const arc = getWallArcData(wall) + const frame = getWallCurveFrameAt(wall, 0) + return points.map((point) => { + if (offset === 0) return point + if (arc) { + const scale = (arc.radius - arc.direction * offset) / arc.radius + return { + x: arc.center.x + (point.x - arc.center.x) * scale, + y: arc.center.y + (point.y - arc.center.y) * scale, + } + } + return { x: point.x + frame.normal.x * offset, y: point.y + frame.normal.y * offset } + }) + }) + const result: Point2D[] = [] + for (let i = 0; i < shifted.length; i++) { + const previous = shifted[(i + shifted.length - 1) % shifted.length]! + const current = shifted[i]! + const a = previous[previous.length - 2]! + const b = previous[previous.length - 1]! + const c = current[0]! + const d = current[1]! + const dx = b.x - a.x, + dy = b.y - a.y + const ex = d.x - c.x, + ey = d.y - c.y + const denominator = dx * ey - dy * ex + if (Math.abs(denominator) < 1e-9) { + result.push(b, c) + } else { + const t = ((c.x - a.x) * ey - (c.y - a.y) * ex) / denominator + const intersection = { x: a.x + t * dx, y: a.y + t * dy } + const limit = + 10 * + Math.max( + Math.abs(boundaryBodyOffset(edges[i]!.wall)), + Math.abs(boundaryBodyOffset(edges[(i + edges.length - 1) % edges.length]!.wall)), + 1e-6, + ) + if ( + Math.hypot(intersection.x - b.x, intersection.y - b.y) <= limit && + Math.hypot(intersection.x - c.x, intersection.y - c.y) <= limit + ) + result.push(intersection) + else result.push(b, c) + } + result.push(...current.slice(1, -1)) + } + return dedupeSequentialPoints(result) +} + +function boundaryBodyOffset(boundary: BoundaryNode) { + return boundary.type === 'wall' ? getWallBodyCenterOffset(boundary) : 0 +} + +/** Largest visible gap between two wall bodies that still reads as a joint. */ +const JOINT_GAP = 0.015 +/** Farthest a wall end may sit off another wall's reference line and still join its body. */ +export const TEE_REACH = 0.4 + +/** + * How far apart two boundaries' reference lines may be where they still join: the + * junction tolerance, or, for walls, as far as their drawn bodies can touch. + */ +export function junctionReach(a: BoundaryNode, b: BoundaryNode) { + if (a.type !== 'wall' || b.type !== 'wall') return WALL_JUNCTION_TOLERANCE + // Metre-thick "walls" are blocks or slabs drawn with the wall tool, not joints. + if (Math.max(a.thickness ?? 0.1, b.thickness ?? 0.1) > 2 * TEE_REACH) + return WALL_JUNCTION_TOLERANCE + return Math.max( + WALL_JUNCTION_TOLERANCE, + Math.min(TEE_REACH, Math.max(a.thickness ?? 0.1, b.thickness ?? 0.1) / 2 + JOINT_GAP), + ) +} +const GRID_CELL = 1 +const MAX_GRID_CELLS = 256 + +type Box = { minX: number; minY: number; maxX: number; maxY: number } +type SampledBoundary = { + boundary: BoundaryNode + points: Point2D[] + stations: number[] + length: number + box: Box + body?: Point2D[][] +} + +function sampleBoundary(boundary: BoundaryNode): SampledBoundary { + const points = sampleWallPointsForRoomDetection(boundary) + const stations = [0] + for (let i = 1; i < points.length; i++) + stations.push( + stations[i - 1]! + + Math.hypot(points[i]!.x - points[i - 1]!.x, points[i]!.y - points[i - 1]!.y), + ) + return { boundary, points, stations, length: stations.at(-1)!, box: bboxOf(points) } +} + +function gridKeys(box: Box, margin: number) { + const minX = Math.floor((box.minX - margin) / GRID_CELL) + const maxX = Math.floor((box.maxX + margin) / GRID_CELL) + const minY = Math.floor((box.minY - margin) / GRID_CELL) + const maxY = Math.floor((box.maxY + margin) / GRID_CELL) + if ( + ![minX, maxX, minY, maxY].every(Number.isSafeInteger) || + (maxX - minX + 1) * (maxY - minY + 1) > MAX_GRID_CELLS + ) + return null + const keys: string[] = [] + for (let x = minX; x <= maxX; x++) for (let y = minY; y <= maxY; y++) keys.push(`${x},${y}`) + return keys +} + +/** Items near a box, bounded by a uniform grid; huge or extreme boxes fall back to a scan. */ +function spatialIndex(items: readonly T[], boxOf: (item: T) => Box) { + const cells = new Map() + const wide: T[] = [] + for (const item of items) { + const keys = gridKeys(boxOf(item), 0) + if (!keys) { + wide.push(item) + continue + } + for (const key of keys) { + const cell = cells.get(key) + if (cell) cell.push(item) + else cells.set(key, [item]) + } + } + return (box: Box, margin: number): Iterable => { + const keys = gridKeys(box, margin) + if (!keys) return items + const found = new Set(wide) + for (const key of keys) for (const item of cells.get(key) ?? []) found.add(item) + return found + } +} + +function pointBox(point: Point2D): Box { + return { minX: point.x, minY: point.y, maxX: point.x, maxY: point.y } +} + +function joinsBoundaryInterior(point: Point2D, sampled: SampledBoundary) { + const tolerance = sampled.boundary.type === 'separator' ? 1e-6 : WALL_JUNCTION_TOLERANCE + const { points, stations, length } = sampled + for (let i = 0; i < points.length - 1; i++) { + const { t, distance } = segmentProjection(point, points[i]!, points[i + 1]!) + const along = stations[i]! + Math.max(0, Math.min(1, t)) * (stations[i + 1]! - stations[i]!) + if (distance <= tolerance && along > tolerance && along < length - tolerance) return true + } + return false +} + +function sampledCross(left: SampledBoundary, right: SampledBoundary) { + const margin = WALL_JUNCTION_TOLERANCE + for (let i = 0; i < left.points.length - 1; i++) { + const p = left.points[i]! + const r = { x: left.points[i + 1]!.x - p.x, y: left.points[i + 1]!.y - p.y } + for (let j = 0; j < right.points.length - 1; j++) { + const q = right.points[j]! + const u = { x: right.points[j + 1]!.x - q.x, y: right.points[j + 1]!.y - q.y } + const denominator = r.x * u.y - r.y * u.x + if (Math.abs(denominator) <= 1e-12) continue + const t = ((q.x - p.x) * u.y - (q.y - p.y) * u.x) / denominator + const v = ((q.x - p.x) * r.y - (q.y - p.y) * r.x) / denominator + if (t < 0 || t > 1 || v < 0 || v > 1) continue + const along = left.stations[i]! + t * (left.stations[i + 1]! - left.stations[i]!) + const otherAlong = right.stations[j]! + v * (right.stations[j + 1]! - right.stations[j]!) + if ( + along > margin && + along < left.length - margin && + otherAlong > margin && + otherAlong < right.length - margin + ) + return true + } + } + return false +} + +/** + * True when two boundaries cross away from their ends (sample vertices included). + * Room detection and the incremental topology index share this predicate. + */ +export function boundariesCross(a: BoundaryNode, b: BoundaryNode) { + return sampledCross(sampleBoundary(a), sampleBoundary(b)) +} + +/** The wall body as drawn: one quad per sampled segment, between its two faces. */ +function bodyOf(sampled: SampledBoundary) { + if (sampled.body) return sampled.body + const wall = sampled.boundary + const { a, b } = wall.type === 'wall' ? getWallFaceOffsets(wall) : { a: 0, b: 0 } + sampled.body = sampled.points.slice(0, -1).flatMap((p, i) => { + const q = sampled.points[i + 1]! + const length = Math.hypot(q.x - p.x, q.y - p.y) + if (!(length > 1e-9)) return [] + const n = { x: -(q.y - p.y) / length, y: (q.x - p.x) / length } + return [ + [ + { x: p.x + n.x * a, y: p.y + n.y * a }, + { x: q.x + n.x * a, y: q.y + n.y * a }, + { x: q.x + n.x * b, y: q.y + n.y * b }, + { x: p.x + n.x * b, y: p.y + n.y * b }, + ], + ] + }) + return sampled.body +} + +function insideQuad(point: Point2D, quad: Point2D[]) { + let inside = false + for (let i = 0, j = quad.length - 1; i < quad.length; j = i++) { + const a = quad[i]! + const b = quad[j]! + if ( + a.y > point.y !== b.y > point.y && + point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x + ) + inside = !inside + } + return inside +} + +function quadGap(left: Point2D[], right: Point2D[]) { + if (left.some((p) => insideQuad(p, right)) || right.some((p) => insideQuad(p, left))) return 0 + let gap = Number.POSITIVE_INFINITY + for (const [points, other] of [ + [left, right], + [right, left], + ] as const) + for (const p of points) + for (let i = 0; i < other.length; i++) + gap = Math.min( + gap, + segmentProjection(p, other[i]!, other[(i + 1) % other.length]!).distance, + ) + return gap +} + +/** What the user sees: the two drawn wall bodies touch, or nearly, at the joint. */ +function bodiesTouch(left: SampledBoundary, right: SampledBoundary, near: Point2D) { + if (left.boundary.type !== 'wall' || right.boundary.type !== 'wall') return false + const reach = + WALL_JUNCTION_TOLERANCE + + Math.max(left.boundary.thickness ?? 0.1, right.boundary.thickness ?? 0.1) + // Only the stretch of each body around the joint counts, never a touch elsewhere. + const local = (sampled: SampledBoundary) => + bodyOf(sampled).filter((quad) => { + const box = bboxOf(quad) + return ( + near.x >= box.minX - reach && + near.x <= box.maxX + reach && + near.y >= box.minY - reach && + near.y <= box.maxY + reach + ) + }) + const rightQuads = local(right) + return local(left).some((quad) => rightQuads.some((other) => quadGap(quad, other) <= JOINT_GAP)) +} + +function halfBody(sampled: SampledBoundary) { + return sampled.boundary.type === 'wall' ? (sampled.boundary.thickness ?? 0.1) / 2 : 0 +} + +/** Unit direction a wall arrives at one of its ends. */ +function endDirection(sampled: SampledBoundary, end: Point2D) { + const { points } = sampled + const atStart = pointKey(points[0]!) === pointKey(end) + const [from, to] = atStart ? [points[1]!, points[0]!] : [points.at(-2)!, points.at(-1)!] + const length = Math.hypot(to.x - from.x, to.y - from.y) || 1 + return { x: (to.x - from.x) / length, y: (to.y - from.y) / length } +} + +/** Nearest point of a wall's reference line to `point`, if it lies away from its ends. */ +function interiorFoot(point: Point2D, sampled: SampledBoundary) { + const { points, stations, length } = sampled + let best: { point: Point2D; distance: number; direction: Point2D } | undefined + for (let i = 0; i < points.length - 1; i++) { + const a = points[i]! + const b = points[i + 1]! + const segment = stations[i + 1]! - stations[i]! + if (!(segment > 1e-9)) continue + const { t, distance } = segmentProjection(point, a, b) + const clamped = Math.max(0, Math.min(1, t)) + const along = stations[i]! + clamped * segment + if (along <= WALL_JUNCTION_TOLERANCE || along >= length - WALL_JUNCTION_TOLERANCE) continue + if (best && distance >= best.distance) continue + best = { + point: { x: a.x + clamped * (b.x - a.x), y: a.y + clamped * (b.y - a.y) }, + distance, + direction: { x: (b.x - a.x) / segment, y: (b.y - a.y) / segment }, + } + } + return best +} + +/** Where two loose straight wall ends would meet if both ran on to their corner. */ +function cornerOf( + cluster: readonly { point: Point2D; boundaryIds: Set }[], + byId: ReadonlyMap, + reachOf: (a: BoundaryNode, b: BoundaryNode) => number, +): Point2D | undefined { + if (cluster.length !== 2) return + const [a, b] = cluster.map((group) => byId.get([...group.boundaryIds][0]!)?.boundary) + if (!(a && b) || isCurvedWall(a) || isCurvedWall(b)) return + const r = { x: a.end[0] - a.start[0], y: a.end[1] - a.start[1] } + const u = { x: b.end[0] - b.start[0], y: b.end[1] - b.start[1] } + const denominator = r.x * u.y - r.y * u.x + // Only a real corner: walls nearly in line meet where their ends already are. + if (Math.abs(denominator) < 0.5 * Math.hypot(r.x, r.y) * Math.hypot(u.x, u.y)) return + const t = ((b.start[0] - a.start[0]) * u.y - (b.start[1] - a.start[1]) * u.x) / denominator + const corner = { x: a.start[0] + t * r.x, y: a.start[1] + t * r.y } + const reach = reachOf(a, b) + return cluster.every(({ point }) => Math.hypot(point.x - corner.x, point.y - corner.y) <= reach) + ? corner + : undefined +} + +/** Distance from a wall end touching this wall's body within the tolerance of its end at `corner`. */ +function bodyReach( + point: Point2D, + corner: { point: Point2D }, + sampled: SampledBoundary, + reach = WALL_JUNCTION_TOLERANCE, +) { + if (sampled.boundary.type !== 'wall') return Number.POSITIVE_INFINITY + const { points } = sampled + const atStart = pointKey(points[0]!) === pointKey(corner.point) + const [a, b] = atStart ? [points[0]!, points[1]!] : [points.at(-1)!, points.at(-2)!] + const length = Math.hypot(b.x - a.x, b.y - a.y) + // A stub is reached through its ends only. + if (!(length > 2 * reach)) return Number.POSITIVE_INFINITY + const along = ((point.x - a.x) * (b.x - a.x) + (point.y - a.y) * (b.y - a.y)) / length + if (along < 0 || along > reach) return Number.POSITIVE_INFINITY + return Math.abs((point.x - a.x) * (b.y - a.y) - (point.y - a.y) * (b.x - a.x)) / length +} + +/** + * Walls drawn a few centimetres short of a corner read as joined when their drawn + * bodies touch there. A wall end that meets no other boundary joins the nearest + * boundary end within the junction tolerance, or a wall body that close to its end, + * whose drawn body touches its own (a visible gap, however small the walls, stays + * open). Returns exact endpoint keys mapped to their junction point. A junction only + * involves walls that touch within the tolerance, so incremental topology rebuilds of + * one component elect the same point as full ones. + */ +function nearMissJunctions(boundaries: readonly BoundaryNode[], bodyJoints: boolean) { + const reachOf = (a: BoundaryNode, b: BoundaryNode) => + bodyJoints ? junctionReach(a, b) : WALL_JUNCTION_TOLERANCE + // loose: a wall end meeting nothing. A loose end whose wall crosses another is + // blocked; that is only checked where a join is possible. + type Group = { + key: string + point: Point2D + boundaryIds: Set + state: 'joined' | 'loose' + } + const sampled = boundaries.map(sampleBoundary) + const byId = new Map(sampled.map((item) => [item.boundary.id, item])) + const near = spatialIndex(sampled, (item) => item.box) + const groups = new Map() + for (const boundary of boundaries) + for (const tuple of [boundary.start, boundary.end]) { + const point = pointFromTuple(tuple) + const key = pointKey(point) + const group = groups.get(key) ?? { key, point, boundaryIds: new Set(), state: 'joined' } + group.boundaryIds.add(boundary.id) + groups.set(key, group) + } + const ordered = [...groups.values()].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)) + const nearGroups = spatialIndex(ordered, (group) => pointBox(group.point)) + const crossing = new Map() + // The graph is planar only at junctions; connecting a wall that crosses another + // would close faces through the crossing. + const crosses = (wall: SampledBoundary) => { + let value = crossing.get(wall.boundary.id) + if (value === undefined) { + value = false + for (const other of near(wall.box, 0)) + if (other !== wall && sampledCross(wall, other)) { + value = true + break + } + crossing.set(wall.boundary.id, value) + } + return value + } + for (const group of ordered) { + const [only, ...rest] = group.boundaryIds + const wall = byId.get(only!)! + if (rest.length || wall.boundary.type !== 'wall') continue + let joined = false + for (const other of near(pointBox(group.point), WALL_JUNCTION_TOLERANCE)) + if (other !== wall && joinsBoundaryInterior(group.point, other)) { + joined = true + break + } + if (!joined) group.state = 'loose' + } + const blocked = (group: Group) => + group.state === 'loose' && crosses(byId.get([...group.boundaryIds][0]!)!) + const parent = new Map() + const find = (key: string): string => { + const next = parent.get(key) + if (!next || next === key) return key + const root = find(next) + parent.set(key, root) + return root + } + const members = new Map>() + const membersOf = (root: string) => members.get(root) ?? new Set([root]) + const ends = new Map( + boundaries.map((boundary) => [ + boundary.id, + [pointKey(pointFromTuple(boundary.start)), pointKey(pointFromTuple(boundary.end))] as const, + ]), + ) + // Joining must neither collapse a wall onto one junction nor lay a wall on top of + // another one between the same two junctions. + const neighbours = (keys: Set, joined: Set) => { + const roots = new Set() + for (const key of keys) + for (const id of groups.get(key)!.boundaryIds) { + const [start, end] = ends.get(id)! + if (start === end) continue + if (joined.has(start) && joined.has(end)) return null + roots.add(find(joined.has(start) ? end : start)) + } + return roots + } + for (const group of ordered) { + if (group.state !== 'loose') continue + const wall = byId.get([...group.boundaryIds][0]!)! + const candidates: { group: Group; distance: number }[] = [] + for (const candidate of nearGroups(pointBox(group.point), 2 * TEE_REACH)) { + if (candidate === group || candidate.boundaryIds.has(wall.boundary.id)) continue + // Thick walls are reached as far as their drawn bodies can touch the end. + const reach = Math.max( + ...[...candidate.boundaryIds].map((id) => reachOf(wall.boundary, byId.get(id)!.boundary)), + ) + const distance = Math.min( + Math.hypot(candidate.point.x - group.point.x, candidate.point.y - group.point.y), + ...[...candidate.boundaryIds].map((id) => + bodyReach(group.point, candidate, byId.get(id)!, reach), + ), + ) + if (distance <= reach) candidates.push({ group: candidate, distance }) + } + if (!candidates.length || blocked(group)) continue + candidates.sort((a, b) => a.distance - b.distance || (a.group.key < b.group.key ? -1 : 1)) + const best = candidates.find( + ({ group: candidate }) => + !blocked(candidate) && + [...candidate.boundaryIds].some((id) => bodiesTouch(wall, byId.get(id)!, group.point)), + )?.group + if (!best) continue + const left = find(group.key) + const right = find(best.key) + if (left === right) continue + const joined = new Set([...membersOf(left), ...membersOf(right)]) + const leftRoots = neighbours(membersOf(left), joined) + const rightRoots = neighbours(membersOf(right), joined) + if (!(leftRoots && rightRoots) || [...leftRoots].some((root) => rightRoots.has(root))) continue + parent.set(left, right) + members.set(right, joined) + members.delete(left) + } + // A wall end standing inside another wall's drawn body, away from its ends, joins it + // at the foot of that body's reference line even when the lines are far apart. + const tees = new Map() + for (const group of bodyJoints ? ordered : []) { + if (group.state !== 'loose' || membersOf(find(group.key)).size > 1 || blocked(group)) continue + const wall = byId.get([...group.boundaryIds][0]!)! + const approach = endDirection(wall, group.point) + let best: { point: Point2D; distance: number } | undefined + for (const other of near(pointBox(group.point), TEE_REACH)) { + if (other === wall || other.boundary.type !== 'wall') continue + const foot = interiorFoot(group.point, other) + if (!foot || foot.distance > junctionReach(wall.boundary, other.boundary)) continue + // Walls running alongside each other are stacked, not joined. + if (Math.abs(approach.x * foot.direction.y - approach.y * foot.direction.x) < 0.5) continue + // A stub drawn entirely inside the other wall's body shows nothing to join. + const start = + wall.points[pointKey(wall.points[0]!) === group.key ? wall.points.length - 1 : 0]! + if ((interiorFoot(start, other)?.distance ?? Number.POSITIVE_INFINITY) <= halfBody(other)) + continue + if (best && foot.distance >= best.distance) continue + if (bodiesTouch(wall, other, group.point)) best = foot + } + if (best) tees.set(group.key, best.point) + } + const junctions = new Map(tees) + for (const keys of members.values()) { + const cluster = [...keys].map((key) => groups.get(key)!) + const junction = + cluster.find((group) => group.state === 'joined')?.point ?? + cornerOf(cluster, byId, reachOf) ?? + cluster.sort((a, b) => (a.key < b.key ? -1 : 1))[0]!.point + for (const group of cluster) + if (pointKey(group.point) !== pointKey(junction)) junctions.set(group.key, junction) + } + return junctions +} + +/** + * Rooms enclosed by walls and separators. Joints where drawn wall bodies touch (thick + * walls, ends inside another wall's body) only ever add or split rooms: wherever they + * would lose room area the plain junction rules drew, that structure keeps the plain + * result, so no scene loses a room it had. + */ +export function extractRooms( + boundaries: BoundaryNode[], + options: { includeHoles?: boolean } = {}, +): ExtractedRoom[] { + const joined = extractRoomGraph(boundaries, options, true) + if (!joined.bodyJoints) return joined.rooms + const plain = extractRoomGraph(boundaries, options, false).rooms + return keepPlainRoomsWhereLost(plain, joined.rooms) +} + +function roomArea(rooms: readonly ExtractedRoom[]) { + return rooms.map((room) => ({ outer: room.referencePolygon, holes: room.holes })) +} + +/** Joints may split rooms or close new ones, never shrink or merge the plain ones. */ +function losesRooms(group: { plain: ExtractedRoom[]; joined: ExtractedRoom[] }) { + try { + const plain = roomArea(group.plain) + const joined = roomArea(group.joined) + if (area(difference(union(plain), union(joined))) > 0.01) return true + return joined.some( + (room) => plain.filter((other) => area(intersection(room, other)) > 0.2).length > 1, + ) + } catch { + return true + } +} + +function keepPlainRoomsWhereLost(plain: ExtractedRoom[], joined: ExtractedRoom[]) { + // Structures: rooms of either result that share a boundary. + const all = [...plain, ...joined] + const parent = all.map((_, i) => i) + const find = (i: number): number => { + while (parent[i] !== i) i = parent[i]! + return i + } + const owner = new Map() + all.forEach((room, i) => { + for (const span of room.spans) { + const other = owner.get(span.boundaryId) + if (other === undefined) owner.set(span.boundaryId, i) + else parent[find(i)] = find(other) + } + }) + const groups = new Map() + all.forEach((room, i) => { + const group = groups.get(find(i)) ?? { plain: [], joined: [] } + ;(i < plain.length ? group.plain : group.joined).push(room) + groups.set(find(i), group) + }) + const rooms: ExtractedRoom[] = [] + for (const group of groups.values()) { + const same = + group.plain.length === group.joined.length && + group.plain.every((room, i) => room.id === group.joined[i]!.id) + rooms.push(...(!same && group.plain.length && losesRooms(group) ? group.plain : group.joined)) + } + rooms.sort((a, b) => Math.abs(polygonArea(b.polygon)) - Math.abs(polygonArea(a.polygon))) + return rooms +} + +function extractRoomGraph( + boundaries: BoundaryNode[], + { includeHoles = true }: { includeHoles?: boolean }, + bodyJoints: boolean, +): { rooms: ExtractedRoom[]; bodyJoints: boolean } { + if (boundaries.length < 3) return { rooms: [], bodyJoints: false } + // Snapped junctions must elect the same representative in migrations, + // full index rebuilds and incremental edits, independent of map insertion order. + const walls = [...boundaries].sort((a, b) => a.id.localeCompare(b.id)) + + type HalfEdge = { + id: string + reverseId: string + fromKey: string + toKey: string + angle: number + points: Point2D[] + wallId: BoundaryNode['id'] + face: 'front' | 'back' + } + type Node = { point: Point2D; outgoing: string[] } + + const wallById = new Map(walls.map((wall) => [wall.id, wall])) + const graph = new Map() + const halfEdges = new Map() + + const upsertNode = (point: Point2D) => { + const key = pointKey(point) + if (!graph.has(key)) { + graph.set(key, { point: { ...point }, outgoing: [] }) + } + return key + } + + // Planarize first: collect every wall endpoint as a candidate graph vertex so + // straight walls can be split at T-junctions where another wall ends mid-span. + // Without this the touching wall's endpoint is a dangling degree-1 node and the + // enclosed area (e.g. a room added against the middle of an existing wall) + // never forms a cycle. + const junctions = nearMissJunctions(walls, bodyJoints) + // Whether the body joints change the graph at all: new junctions, or doubled spans + // dropped where joints connect walls. + let changed = false + if (bodyJoints) { + const plain = nearMissJunctions(walls, false) + changed = + plain.size !== junctions.size || + [...junctions].some(([key, point]) => { + const other = plain.get(key) + return !other || pointKey(other) !== pointKey(point) + }) + } + const junction = (tuple: [number, number]) => { + const point = pointFromTuple(tuple) + return junctions.get(pointKey(point)) ?? point + } + const vertexByKey = new Map() + for (const wall of walls) { + for (const tuple of [wall.start, wall.end]) { + const point = junction(tuple) + const key = pointKey(point) + const existing = vertexByKey.get(key) + if (!existing) vertexByKey.set(key, { ...point, wallEndpoint: wall.type === 'wall' }) + else if (wall.type === 'wall') existing.wallEndpoint = true + } + } + const vertices = [...vertexByKey.values()] + + const parts: { wall: BoundaryNode; points: Point2D[]; subIndex: number; snapped: boolean }[] = [] + for (const wall of walls) { + const start = pointFromTuple(wall.start) + const end = pointFromTuple(wall.end) + if (samePointWithinTolerance(start, end)) continue + + const subPolylines: Point2D[][] = isCurvedWall(wall) + ? splitCurvedWallAtVertices(sampleWallPointsForRoomDetection(wall), vertices, wall) + : (() => { + const ordered = splitStraightWallAtVertices( + start, + end, + vertices, + wall.type === 'separator', + ) + const parts: Point2D[][] = [] + for (let index = 0; index < ordered.length - 1; index += 1) { + parts.push([ordered[index]!, ordered[index + 1]!]) + } + return parts + })() + // A near-miss end moves onto its junction only after the body is split, so every + // T-junction found along the wall as drawn stays connected. + const startJunction = junctions.get(pointKey(start)) + const endJunction = junctions.get(pointKey(end)) + const snapped = new Set() + if (startJunction && subPolylines.length) { + subPolylines[0] = [startJunction, ...subPolylines[0]!.slice(1)] + snapped.add(0) + } + if (endJunction && subPolylines.length) { + subPolylines[subPolylines.length - 1] = [...subPolylines.at(-1)!.slice(0, -1), endJunction] + snapped.add(subPolylines.length - 1) + } + for (const [subIndex, points] of subPolylines.entries()) + parts.push({ wall, points, subIndex, snapped: snapped.has(subIndex) }) + } + // A moved end never doubles a span another boundary already draws between the same + // two nodes (e.g. parallel walls a few centimetres apart). + const pairKey = (points: Point2D[]) => { + const keys = points.map(pointKey) + const reversed = [...keys].reverse() + return (keys.join('|') < reversed.join('|') ? keys : reversed).join('|') + } + const drawnPairs = new Set( + parts.filter((part) => !part.snapped).map((part) => pairKey(part.points)), + ) + // Where joints connect walls, a span drawn twice (walls stacked on each other) would + // give two edges with the same angle at a node, and the face walk could cut through + // rooms: keep one per span there. Elsewhere the graph stays exactly as drawn. + const componentOf = new Map() + const root = (key: string): string => { + const next = componentOf.get(key) + if (!next || next === key) return key + const found = root(next) + componentOf.set(key, found) + return found + } + for (const { points } of parts) { + const a = root(pointKey(points[0]!)) + const b = root(pointKey(points.at(-1)!)) + if (a !== b) componentOf.set(a, b) + } + const joined = new Set( + bodyJoints ? [...junctions.values()].map((point) => root(pointKey(point))) : [], + ) + const seenPairs = new Set() + for (const { wall, points, subIndex, snapped } of parts) { + const pair = pairKey(points) + if (snapped && drawnPairs.has(pair)) continue + if (joined.has(root(pointKey(points[0]!)))) { + if (seenPairs.has(pair)) { + changed = true + continue + } + seenPairs.add(pair) + } + const from = points[0]! + const to = points[points.length - 1]! + const fromKey = upsertNode(from) + const toKey = upsertNode(to) + if (fromKey === toKey) continue + + const reversePoints = [...points].reverse() + const forwardId = `${wall.id}#${subIndex}:f` + const reverseId = `${wall.id}#${subIndex}:r` + + halfEdges.set(forwardId, { + id: forwardId, + reverseId, + fromKey, + toKey, + angle: Math.atan2(points[1]!.y - from.y, points[1]!.x - from.x), + points, + wallId: wall.id, + face: 'front', + }) + halfEdges.set(reverseId, { + id: reverseId, + reverseId: forwardId, + fromKey: toKey, + toKey: fromKey, + angle: Math.atan2(reversePoints[1]!.y - to.y, reversePoints[1]!.x - to.x), + points: reversePoints, + wallId: wall.id, + face: 'back', + }) + + graph.get(fromKey)?.outgoing.push(forwardId) + graph.get(toKey)?.outgoing.push(reverseId) + } + + const sortedOutgoing = new Map() + for (const [key, node] of graph.entries()) { + const outgoing = [...node.outgoing] + outgoing.sort((a, b) => (halfEdges.get(a)?.angle ?? 0) - (halfEdges.get(b)?.angle ?? 0)) + sortedOutgoing.set(key, outgoing) + } + + const nextEdge = (edgeId: string) => { + const edge = halfEdges.get(edgeId) + if (!edge) return null + + const outgoing = sortedOutgoing.get(edge.toKey) + if (!outgoing || outgoing.length === 0) return null + + const idx = outgoing.indexOf(edge.reverseId) + if (idx === -1) return null + + const nextIdx = (idx - 1 + outgoing.length) % outgoing.length + return outgoing[nextIdx] ?? null + } + + const splitIntoSimpleCycles = (walkEdgeIds: string[]) => { + const cycles: string[][] = [] + const firstEdge = halfEdges.get(walkEdgeIds[0] ?? '') + if (!firstEdge) return cycles + + const pathEdges: string[] = [] + const pathVertices = [firstEdge.fromKey] + const vertexIndex = new Map([[firstEdge.fromKey, 0]]) + + for (const edgeId of walkEdgeIds) { + const edge = halfEdges.get(edgeId) + if (!edge || edge.fromKey !== pathVertices[pathVertices.length - 1]) return [] + + pathEdges.push(edgeId) + const repeatedIndex = vertexIndex.get(edge.toKey) + if (repeatedIndex === undefined) { + pathVertices.push(edge.toKey) + vertexIndex.set(edge.toKey, pathVertices.length - 1) + continue + } + + const cycle = pathEdges.slice(repeatedIndex) + if (cycle.length >= 3) cycles.push(cycle) + + for (let index = repeatedIndex + 1; index < pathVertices.length; index += 1) { + vertexIndex.delete(pathVertices[index]!) + } + pathVertices.length = repeatedIndex + 1 + pathEdges.length = repeatedIndex + } + + return pathEdges.length === 0 && pathVertices.length === 1 ? cycles : [] + } + + const visitedDirected = new Set() + const rooms: ExtractedRoom[] = [] + const innerCycles: ExtractedRoom[] = [] + // A face walk cannot revisit a half-edge, so the half-edge count bounds its + // length. It can revisit a vertex when dangling walls or other graph bridges + // are traced out and back; those excursions are removed below. + const maxSteps = Math.min(2000, halfEdges.size + 10) + + for (const edgeId of halfEdges.keys()) { + if (visitedDirected.has(edgeId)) continue + + const cycleEdgeIds: string[] = [] + let currentEdgeId = edgeId + let valid = true + let closed = false + + for (let step = 0; step < maxSteps; step += 1) { + const currentEdge = halfEdges.get(currentEdgeId) + if (!currentEdge) { + valid = false + break + } + + visitedDirected.add(currentEdgeId) + cycleEdgeIds.push(currentEdgeId) + + const next = nextEdge(currentEdgeId) + if (!next) { + valid = false + break + } + + currentEdgeId = next + if (currentEdgeId === edgeId) { + closed = true + break + } + } + + if (!(valid && closed) || cycleEdgeIds.length < 3) continue + + for (const simpleCycleEdgeIds of splitIntoSimpleCycles(cycleEdgeIds)) { + const bodyEdges = simpleCycleEdgeIds.map((id) => { + const edge = halfEdges.get(id)! + return { wall: wallById.get(edge.wallId)!, points: edge.points } + }) + const polygon = bodyEdges.some( + ({ wall }) => wall.type === 'wall' && wall.justification !== undefined, + ) + ? roomBodyPolygon(bodyEdges) + : dedupeSequentialPoints( + simpleCycleEdgeIds.flatMap((id, index) => { + const points = halfEdges.get(id)?.points ?? [] + return index === simpleCycleEdgeIds.length - 1 ? points : points.slice(0, -1) + }), + ) + + if (polygon.length < 3) continue + + const referencePoints = dedupeSequentialPoints( + simpleCycleEdgeIds.flatMap((id) => halfEdges.get(id)!.points.slice(0, -1)), + ).map(pointToTuple) + + // Room identity must not change when wall thickness or justification changes. + const signedArea = polygonArea(referencePoints.map(pointFromTuple)) + if (signedArea <= 0 && !includeHoles) continue + const minArea = bodyEdges.every(({ wall }) => wall.type === 'separator') ? 0.25 : 0.5 + if (Math.abs(signedArea) < minArea - 1e-9 || Math.abs(signedArea) > 10_000) continue + + const cycles = signedArea > 0 ? rooms : innerCycles + const signature = polygonSignature(polygon) + if (cycles.some((room) => polygonSignature(room.polygon) === signature)) continue + + let first = 0 + for (let i = 1; i < referencePoints.length; i++) { + const p = referencePoints[i]!, + q = referencePoints[first]! + if (p[0] < q[0] || (p[0] === q[0] && p[1] < q[1])) first = i + } + const referencePolygon = [...referencePoints.slice(first), ...referencePoints.slice(0, first)] + const roomId = `room-${polygonSignature(referencePolygon.map(pointFromTuple))}` + const spans: BoundarySpan[] = simpleCycleEdgeIds.map((id) => { + const edge = halfEdges.get(id)! + const boundary = wallById.get(edge.wallId)! + const start = pointFromTuple(boundary.start) + const end = pointFromTuple(boundary.end) + const from = segmentProjection(edge.points[0]!, start, end).t + const to = segmentProjection(edge.points.at(-1)!, start, end).t + return { + roomId, + boundaryId: boundary.id, + kind: boundary.type, + face: edge.face === 'front' ? 'a' : 'b', + t0: Math.max(0, Math.min(1, Math.min(from, to))), + t1: Math.max(0, Math.min(1, Math.max(from, to))), + } + }) + spans.sort( + (a, b) => + a.boundaryId.localeCompare(b.boundaryId) || a.face.localeCompare(b.face) || a.t0 - b.t0, + ) + cycles.push({ + id: roomId, + referencePolygon, + holes: [], + spans, + polygon, + boundaryFaces: simpleCycleEdgeIds.flatMap((id) => { + const edge = halfEdges.get(id) + if (!edge || wallById.get(edge.wallId)?.type !== 'wall') return [] + return [ + { + wallId: edge.wallId as WallNode['id'], + face: edge.face, + points: edge.points.map(pointToTuple), + }, + ] + }), + }) + } + } + + const shells = rooms + .map((room) => ({ + room, + area: Math.abs(polygonArea(room.referencePolygon.map(pointFromTuple))), + bbox: bboxOf(room.referencePolygon.map(pointFromTuple)), + })) + .sort((a, b) => a.area - b.area || a.room.id.localeCompare(b.room.id)) + for (const cycle of innerCycles) { + const ring = cycle.referencePolygon + const cycleArea = Math.abs(polygonArea(ring.map(pointFromTuple))) + const bounds = bboxOf(ring.map(pointFromTuple)) + const containing = shells.find( + (shell) => + shell.area > cycleArea + 1e-6 && + // The reverse walk of the same boundary is the exterior, even when + // snapped endpoints give it a slightly smaller numerical area. + !shell.room.spans.some((outer) => + cycle.spans.some( + (inner) => + outer.boundaryId === inner.boundaryId && + Math.min(outer.t1, inner.t1) - Math.max(outer.t0, inner.t0) > 1e-8, + ), + ) && + shell.bbox.minX <= bounds.minX && + shell.bbox.minY <= bounds.minY && + shell.bbox.maxX >= bounds.maxX && + shell.bbox.maxY >= bounds.maxY && + area(difference(ring, shell.room.referencePolygon)) < 1e-6, + )?.room + if (!containing) continue + containing.holes.push(ring) + containing.boundaryFaces.push(...cycle.boundaryFaces) + containing.spans.push(...cycle.spans.map((span) => ({ ...span, roomId: containing.id }))) + } + for (const room of rooms) { + room.holes.sort((a, b) => + polygonSignature(a.map(pointFromTuple)).localeCompare( + polygonSignature(b.map(pointFromTuple)), + ), + ) + room.spans.sort( + (a, b) => + a.boundaryId.localeCompare(b.boundaryId) || a.face.localeCompare(b.face) || a.t0 - b.t0, + ) + } + + rooms.sort((a, b) => Math.abs(polygonArea(b.polygon)) - Math.abs(polygonArea(a.polygon))) + return { rooms, bodyJoints: changed } +} + +export type RoomFace = { + /** Canonical face id (the extracted room id), stable across callers' face order. */ + key: string + polygon: Ring + holes: Ring[] + boundaryWallIds: WallNode['id'][] + boundarySeparatorIds: SeparatorNode['id'][] +} + +export function detectRoomFaces( + levelWalls: WallNode[], + levelSeparators: SeparatorNode[] = [], +): RoomFace[] { + return extractRooms( + [...levelWalls, ...levelSeparators].sort((a, b) => a.id.localeCompare(b.id)), + ).map((room) => ({ + key: room.id, + polygon: room.referencePolygon, + holes: room.holes, + boundaryWallIds: [ + ...new Set( + room.spans + .filter((span) => span.kind === 'wall') + .map((span) => span.boundaryId as WallNode['id']), + ), + ].sort(), + boundarySeparatorIds: [ + ...new Set( + room.spans + .filter((span) => span.kind === 'separator') + .map((span) => span.boundaryId as SeparatorNode['id']), + ), + ].sort(), + })) +} diff --git a/packages/core/src/lib/room-holes.test.ts b/packages/core/src/lib/room-holes.test.ts new file mode 100644 index 0000000000..17a1c87836 --- /dev/null +++ b/packages/core/src/lib/room-holes.test.ts @@ -0,0 +1,91 @@ +import { expect, test } from 'bun:test' +import { CeilingNode, LevelNode, SlabNode, UnitNode, WallNode, ZoneNode } from '../schema' +import { containsPoint, distanceToBoundary, type Ring } from './polygon-boolean' +import { polygonInteriorPoint } from './polygon-label' +import { reconcileSceneStructure } from './structure-reconcile' +import { buildUnitReport } from './unit-report' +import { deriveZoneQuantityReport } from './zone-quantities' + +const polygon: Ring = [ + [0, 0], + [10, 0], + [10, 10], + [0, 10], +] +const hole: Ring = [ + [3, 3], + [7, 3], + [7, 7], + [3, 7], +] +const level = LevelNode.parse({ id: 'level_holes', height: 3 }) +const walls = [polygon, hole].flatMap((ring, loop) => + ring.map((start, i) => + WallNode.parse({ + id: `wall_${loop}_${i}`, + parentId: level.id, + start, + end: ring[(i + 1) % ring.length], + thickness: 0.2, + }), + ), +) +const zone = ZoneNode.parse({ + id: 'zone_ring', + name: 'Hall', + polygon, + holes: [hole], + parentId: level.id, +}) +const nodes = Object.fromEntries([level, ...walls, zone].map((node) => [node.id, node])) + +test('zone quantities exclude the hole, include its wall perimeter, and ignore surfaces inside it', () => { + const surfaces = [ + SlabNode.parse({ parentId: level.id, polygon, holes: [hole], elevation: 0 }), + CeilingNode.parse({ parentId: level.id, polygon, holes: [hole], height: 3 }), + SlabNode.parse({ parentId: level.id, polygon: hole, elevation: 1 }), + CeilingNode.parse({ parentId: level.id, polygon: hole, height: 2 }), + ] + const report = deriveZoneQuantityReport(zone, { + ...nodes, + ...Object.fromEntries(surfaces.map((n) => [n.id, n])), + }) + expect(report.footprintArea).toBe(84) + expect(report.perimeter).toBe(56) + expect(report.classification).toBe('enclosed-room') + expect(report.floorSurface).toMatchObject({ status: 'available', value: 84 }) + expect(report.volume).toMatchObject({ status: 'available', value: 252 }) + expect(report.boundaryWallIds).toHaveLength(8) +}) + +test('unit reports sum usable footprints including holes', () => { + const unit = UnitNode.parse({ name: 'Suite', members: [zone.id] }) + expect(buildUnitReport(unit, nodes)).toMatchObject({ grossAreaM2: 84, members: [{ areaM2: 84 }] }) +}) + +test('label pole is in the outer minus holes even when its centroid is in the hole', () => { + const footprint = [{ outer: polygon, holes: [hole] }] + const point = polygonInteriorPoint({ polygon, holes: [hole] }) + expect(containsPoint(footprint, point)).toBe(true) + expect(distanceToBoundary(footprint, point)).toBeGreaterThan(1.75) +}) + +test('nested room floors merge into one plate; opting out the inner room restores the managed hole', () => { + let sequence = 0 + const mintId = (kind: string) => `${kind}_${sequence++}` + const initial = reconcileSceneStructure({ nodes, mintId }).nodes + const slabs = Object.values(initial).filter((node): node is SlabNode => node.type === 'slab') + expect(slabs).toHaveLength(1) + expect(slabs[0]!.holes).toEqual([]) + const inner = Object.values(initial).find( + (node): node is ZoneNode => node.type === 'zone' && node.holes.length === 0, + )! + const result = reconcileSceneStructure({ + nodes: { ...initial, [inner.id]: { ...inner, hasFloor: false } }, + mintId, + }).nodes + const plate = result[slabs[0]!.id] as SlabNode + expect(plate.holeMetadata).toEqual([{ source: 'room' }]) + expect(containsPoint([{ outer: plate.polygon, holes: plate.holes }], [5, 5])).toBe(false) + expect(reconcileSceneStructure({ nodes: result, mintId }).patches).toEqual([]) +}) diff --git a/packages/core/src/lib/room-name.ts b/packages/core/src/lib/room-name.ts new file mode 100644 index 0000000000..2b3aef8d21 --- /dev/null +++ b/packages/core/src/lib/room-name.ts @@ -0,0 +1,21 @@ +const NUMBERED_ROOM = /^Room (\d+)$/ + +/** + * Names rooms nobody named: "Room N" with the lowest number no zone on the level + * uses yet. Only exact "Room N" names count. Called once per level, in a + * deterministic room order, and only when a room zone is created, so an existing + * room is never renamed and a name the user cleared stays cleared. + */ +export function roomNameAllocator(levelZones: Iterable<{ name?: string }>) { + const used = new Set() + for (const zone of levelZones) { + const match = NUMBERED_ROOM.exec(zone.name ?? '') + if (match) used.add(Number(match[1])) + } + let next = 1 + return () => { + while (used.has(next)) next++ + used.add(next) + return `Room ${next}` + } +} diff --git a/packages/core/src/lib/room-topology-index.test.ts b/packages/core/src/lib/room-topology-index.test.ts new file mode 100644 index 0000000000..bf7f6b0c7c --- /dev/null +++ b/packages/core/src/lib/room-topology-index.test.ts @@ -0,0 +1,218 @@ +import { describe, expect, test } from 'bun:test' +import { LevelNode, WallNode } from '../schema' +import { sampleWallPointsForRoomDetection } from './room-graph' +import { RoomTopologyIndex } from './room-topology-index' +import { createRoomTopologyIndex } from './space-detection' + +const levelId = 'level_grid' as const + +function wall(id: string, start: [number, number], end: [number, number]) { + return WallNode.parse({ id: `wall_${id}`, parentId: levelId, start, end }) +} + +function scene(walls: WallNode[]) { + const level = LevelNode.parse({ id: levelId, children: walls.map((node) => node.id) }) + return Object.fromEntries([level, ...walls].map((node) => [node.id, node])) +} + +function gridIndex() { + return new RoomTopologyIndex({ + detectRooms: () => [], + sampleWall: (node) => [node.start, node.end], + junctionTolerance: 0.1, + }) +} + +describe('bounded topology grid', () => { + test.each([ + { start: [0, 0], end: [1e6, 1e6] }, + { start: [0, 0], end: [6.635e287, 6.635e287] }, + { start: [1e100, 1e100], end: [1e100, 1e100] }, + { start: [-1e308, -1e308], end: [1e308, 1e308] }, + ])('falls back before enumerating extreme bounds: %j', ({ start, end }) => { + const index = gridIndex() + const extreme = wall('extreme', start as [number, number], end as [number, number]) + const nodes = scene([extreme]) + const level = index.rebuildLevel(levelId, nodes) + expect(level.flat).toBe(true) + expect(level.wallIdsByCell.size).toBe(0) + expect(level.cellKeysByWallId.size).toBe(0) + expect(level.cellEntries).toBe(0) + const delta = index.applyWallDelta(levelId, new Set([extreme.id]), nodes, nodes) + expect(delta.examinedWallIds).toEqual([extreme.id]) + }) + + test('bounds total cell entries even when individual wall bounds are small', () => { + const walls = Array.from({ length: 1100 }, (_, i) => wall(`${i}`, [0, 0], [1, 0])) + const index = gridIndex() + const level = index.rebuildLevel(levelId, scene(walls.slice(0, 1024))) + expect(level.flat).toBe(false) + expect(level.cellEntries).toBe(4096) + index.applyWallDelta( + levelId, + new Set([walls[1024]!.id]), + scene(walls.slice(0, 1024)), + scene(walls.slice(0, 1025)), + ) + expect(level.flat).toBe(true) + expect(level.wallIdsByCell.size).toBe(0) + expect(level.cellKeysByWallId.size).toBe(0) + expect(level.cellEntries).toBe(0) + }) + + test('counts removals and finds connected walls across grid-to-flat transitions', () => { + const first = wall('first', [0, 0], [1, 0]) + const neighbor = wall('neighbor', [1, 0], [1, 1]) + const remote = wall('remote', [20, 20], [21, 20]) + const before = scene([first, neighbor, remote]) + const index = gridIndex() + const level = index.rebuildLevel(levelId, before) + expect(level.flat).toBe(false) + const oldEntries = level.cellEntries + const unchanged = index.applyWallDelta(levelId, new Set([first.id]), before, before) + expect(unchanged.examinedWallIds).toEqual([first.id, neighbor.id]) + expect(level.cellEntries).toBe(oldEntries) + + const long = { ...first, end: [100_000, 100_000] as [number, number] } + const after = scene([long, neighbor, remote]) + const delta = index.applyWallDelta(levelId, new Set([first.id]), before, after) + expect(level.flat).toBe(true) + expect(delta.examinedWallIds).toEqual([first.id, neighbor.id, remote.id]) + index.applyWallDelta(levelId, new Set([first.id]), after, before) + expect(level.cellEntries).toBe(0) + const restored = index.applyWallDelta(levelId, new Set([first.id]), before, before) + expect(restored.examinedWallIds).toEqual(unchanged.examinedWallIds) + + const rebuilt = index.rebuildLevel(levelId, before) + expect(rebuilt.flat).toBe(false) + index.applyWallDelta(levelId, new Set([remote.id]), before, scene([first, neighbor])) + expect(rebuilt.cellEntries).toBeLessThan(oldEntries) + }) + + test.each([false, true])('ordinary room deltas match a full rebuild (flat=%s)', (flat) => { + const enclosure = [ + wall('bottom', [0, 0], [4, 0]), + wall('right', [4, 0], [4, 3]), + wall('top', [4, 3], [0, 3]), + wall('left', [0, 3], [0, 0]), + ] + const remote = flat ? [wall('remote', [100, 100], [100_000, 100_000])] : [] + const divider = wall('divider', [2, 0], [2, 3]) + const before = scene([...enclosure, ...remote]) + const after = scene([...enclosure, ...remote, divider]) + const index = createRoomTopologyIndex() + const level = index.rebuildLevel(levelId, before) + expect(level.flat).toBe(flat) + const delta = index.applyWallDelta(levelId, new Set([divider.id]), before, after) + expect(delta.currentRooms).toHaveLength(2) + expect(delta.examinedWallIds).not.toContain('wall_remote') + const rebuilt = createRoomTopologyIndex() + rebuilt.rebuild(after) + const snapshot = (source: typeof index) => + source.getLevelTopology(levelId)!.rooms.map(({ id, polygon, holes, spans }) => ({ + id, + polygon, + holes, + spans, + })) + expect(snapshot(index)).toEqual(snapshot(rebuilt)) + }) +}) + +describe('near-miss corners through incremental edits', () => { + test('closing a room a few centimetres short of its corner matches a full rebuild', () => { + const walls = [ + wall('south', [0, 0], [4, 0]), + wall('east', [4, 0], [4, 3]), + wall('north', [4, 3], [0, 3]), + wall('west', [0, 3], [0, 1]), + // A free wall across the west wall: it touches no end, yet the edit must see it. + wall('cross', [-1, 2], [1, 2]), + ] + const index = createRoomTopologyIndex() + const before = scene(walls) + index.rebuildLevel(levelId, before) + expect(index.getLevelTopology(levelId)!.rooms).toHaveLength(0) + const closed = { ...walls[3]!, end: [0, 0.05] as [number, number] } + const after = scene([...walls.slice(0, 3), closed, walls[4]!]) + index.applyWallDelta(levelId, new Set([closed.id]), before, after) + const full = createRoomTopologyIndex() + full.rebuildLevel(levelId, after) + const rooms = (topology: typeof index) => + topology + .getLevelTopology(levelId)! + .rooms.map((room) => room.id) + .sort() + expect(rooms(index)).toEqual(rooms(full)) + // Detection declines a near-miss join on a wall another wall crosses. + expect(rooms(full)).toHaveLength(0) + const clear = scene([...walls.slice(0, 3), closed]) + full.rebuildLevel(levelId, clear) + expect(rooms(full)).toHaveLength(1) + }) +}) + +test('a curve crossing a wall exactly at one of its samples joins that wall’s component', () => { + const arc = WallNode.parse({ + id: 'wall_arc', + parentId: levelId, + start: [-1, 1.5], + end: [1, 1.5], + curveOffset: 0.5, + }) + // The west wall runs exactly through the arc's middle sample vertex. + const x = sampleWallPointsForRoomDetection(arc)[2]!.x + const walls = [ + wall('south', [0, 0], [4, 0]), + wall('east', [4, 0], [4, 3]), + wall('north', [4, 3], [x, 3]), + wall('west', [x, 3], [x, 0.04]), + arc, + ] + const before = scene(walls) + const index = createRoomTopologyIndex() + index.rebuildLevel(levelId, before) + const thicker = { ...walls[3]!, thickness: 0.2 } + const after = scene([...walls.slice(0, 3), thicker, walls[4]!]) + index.applyWallDelta(levelId, new Set([thicker.id]), before, after) + const full = createRoomTopologyIndex() + full.rebuildLevel(levelId, after) + const rooms = (topology: typeof index) => + topology + .getLevelTopology(levelId)! + .rooms.map((room) => room.id) + .sort() + expect(rooms(index)).toEqual(rooms(full)) +}) + +test('a wall end moved inside a thick wall body rebuilds like a full detection', () => { + const walls = [ + wall('south', [0, 0], [4, 0]), + wall('east', [4, 0], [4, 2]), + WallNode.parse({ + id: 'wall_thick', + parentId: levelId, + start: [5, 3], + end: [-1, 3], + thickness: 0.3, + }), + wall('west', [0, 3], [0, 0]), + ] + const before = scene(walls) + const index = createRoomTopologyIndex() + index.rebuildLevel(levelId, before) + expect(index.getLevelTopology(levelId)!.rooms).toHaveLength(0) + // 10 cm off the thick wall's line: beyond the junction tolerance, inside its body. + const reaching = { ...walls[1]!, end: [4, 2.9] as [number, number] } + const after = scene([walls[0]!, reaching, walls[2]!, walls[3]!]) + index.applyWallDelta(levelId, new Set([reaching.id]), before, after) + const full = createRoomTopologyIndex() + full.rebuildLevel(levelId, after) + const rooms = (topology: typeof index) => + topology + .getLevelTopology(levelId)! + .rooms.map((room) => room.id) + .sort() + expect(rooms(full)).toHaveLength(1) + expect(rooms(index)).toEqual(rooms(full)) +}) diff --git a/packages/core/src/lib/room-topology-index.ts b/packages/core/src/lib/room-topology-index.ts index 4296fcd023..5e7638ead8 100644 --- a/packages/core/src/lib/room-topology-index.ts +++ b/packages/core/src/lib/room-topology-index.ts @@ -1,18 +1,59 @@ -import type { WallNode } from '../schema' +import type { SeparatorNode, WallNode } from '../schema' import { getClampedWallCurveOffset } from '../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { containsPoint, type Ring } from './polygon-boolean' +import { boundariesCross, junctionReach, TEE_REACH } from './room-graph' + +export type BoundaryNode = WallNode | SeparatorNode +export type BoundarySpan = { + roomId: string + boundaryId: string + kind: 'wall' | 'separator' + face: 'a' | 'b' + t0: number + t1: number +} +export type ExteriorBoundarySpan = Omit & { roomId: null } +export type LevelFootprintContext = { + revision: number + walls: ReadonlyMap + wallFootprints: ReadonlyMap +} +export type TopologyRoom = { + id: string + polygon: Ring + holes: Ring[] + spans: BoundarySpan[] + context: LevelFootprintContext +} +export type LevelTopology = { + revision: number + rooms: TopologyRoom[] + exteriorSpans: ExteriorBoundarySpan[] + spansByBoundary: ReadonlyMap +} + type SceneNodes = Record type Point = [number, number] type IndexedRoom = { + id: string + referencePolygon: Ring + holes: Ring[] + spans: BoundarySpan[] boundaryFaces: Array<{ wallId: WallNode['id'] }> } type IndexedLevelTopology = { - walls: Map + revision: number + topology?: LevelTopology + walls: Map rooms: TRoom[] wallIdsByCell: Map> cellKeysByWallId: Map + cellEntries: number + flat: boolean } export type IndexedTopologyDelta = { @@ -26,12 +67,15 @@ export type IndexedTopologyDelta = { } type RoomTopologyIndexOptions = { - detectRooms: (walls: WallNode[]) => TRoom[] - sampleWall: (wall: WallNode) => Point[] + includeSeparators?: boolean + includeHoles?: boolean + detectRooms: (walls: BoundaryNode[]) => TRoom[] + sampleWall: (wall: BoundaryNode) => Point[] junctionTolerance: number } const CELL_SIZE = 2 +const MAX_CELL_ENTRIES = 4096 function bboxOf(points: Point[]) { let minX = Number.POSITIVE_INFINITY @@ -57,9 +101,19 @@ function expandedBbox(box: ReturnType, margin: number) { } function cellKeysForBbox(box: ReturnType) { + const minX = Math.floor(box.minX / CELL_SIZE) + const maxX = Math.floor(box.maxX / CELL_SIZE) + const minY = Math.floor(box.minY / CELL_SIZE) + const maxY = Math.floor(box.maxY / CELL_SIZE) + // Unsafe integer coordinates can make x += 1 stall even for a tiny bbox. + if ( + ![minX, maxX, minY, maxY].every(Number.isSafeInteger) || + (maxX - minX + 1) * (maxY - minY + 1) > MAX_CELL_ENTRIES + ) + return null const keys: string[] = [] - for (let x = Math.floor(box.minX / CELL_SIZE); x <= Math.floor(box.maxX / CELL_SIZE); x += 1) { - for (let y = Math.floor(box.minY / CELL_SIZE); y <= Math.floor(box.maxY / CELL_SIZE); y += 1) { + for (let x = minX; x <= maxX; x += 1) { + for (let y = minY; y <= maxY; y += 1) { keys.push(`${x},${y}`) } } @@ -81,34 +135,42 @@ export function distanceToSegment(point: Point, segStart: Point, segEnd: Point) } function roomUsesAnyWall(room: IndexedRoom, wallIds: ReadonlySet) { - return room.boundaryFaces.some((boundary) => wallIds.has(boundary.wallId)) + return room.spans.some((span) => wallIds.has(span.boundaryId)) } -function sameIndexedWall(left: WallNode | undefined, right: WallNode | undefined) { +function sameIndexedWall(left: BoundaryNode | undefined, right: BoundaryNode | undefined) { if (!(left && right)) return left === right return ( + left.type === right.type && left.parentId === right.parentId && left.start[0] === right.start[0] && left.start[1] === right.start[1] && left.end[0] === right.end[0] && left.end[1] === right.end[1] && - getClampedWallCurveOffset(left) === getClampedWallCurveOffset(right) + getClampedWallCurveOffset(left) === getClampedWallCurveOffset(right) && + (left.type === 'separator' || + (right.type === 'wall' && + left.thickness === right.thickness && + left.justification === right.justification)) ) } export class RoomTopologyIndex { private readonly levels = new Map>() private readonly queryMargin: number + private readonly options: RoomTopologyIndexOptions + private revision = 0 - constructor(private readonly options: RoomTopologyIndexOptions) { - this.queryMargin = options.junctionTolerance + 0.02 + constructor(options: RoomTopologyIndexOptions) { + this.options = options + this.queryMargin = Math.max(options.junctionTolerance, TEE_REACH) + 0.02 } rebuild(nodes: SceneNodes) { this.levels.clear() - const wallsByLevel = new Map() + const wallsByLevel = new Map() for (const node of Object.values(nodes)) { - if (node?.type !== 'wall' || !node.parentId) continue + if (!(this.isBoundary(node) && node.parentId)) continue const walls = wallsByLevel.get(node.parentId) ?? [] walls.push(node) wallsByLevel.set(node.parentId, walls) @@ -140,7 +202,7 @@ export class RoomTopologyIndex { const cached = level.walls.get(wallId) const previous = beforeNodes[wallId] const previousWall = - previous?.type === 'wall' && previous.parentId === levelId ? previous : undefined + this.isBoundary(previous) && previous.parentId === levelId ? previous : undefined if (!sameIndexedWall(cached, previousWall)) { level = this.rebuildLevel(levelId, beforeNodes) strategy = 'fallback' @@ -151,7 +213,7 @@ export class RoomTopologyIndex { const beforeComponentIds = this.connectedWallIds(level, changedWallIds) for (const wallId of changedWallIds) { const current = currentNodes[wallId] - if (current?.type === 'wall' && current.parentId === levelId) { + if (this.isBoundary(current) && current.parentId === levelId) { this.setWall(level, current) } else { this.removeWall(level, wallId) @@ -166,12 +228,19 @@ export class RoomTopologyIndex { const beforeRooms = level.rooms.filter((room) => roomUsesAnyWall(room, examinedIds)) const previousWalls = this.wallsFromNodes(beforeNodes, levelId, examinedIds) const currentWalls = this.wallsFromNodes(currentNodes, levelId, examinedIds) - const currentRooms = this.options.detectRooms(currentWalls) + const currentRooms = this.options.detectRooms( + [...examinedIds].flatMap((id) => { + const boundary = level.walls.get(id) + return boundary ? [boundary] : [] + }), + ) const allCurrentRooms = [ ...level.rooms.filter((room) => !roomUsesAnyWall(room, examinedIds)), ...currentRooms, ] level.rooms = allCurrentRooms + level.revision = ++this.revision + level.topology = undefined return { strategy, @@ -184,12 +253,112 @@ export class RoomTopologyIndex { } } + private isBoundary(node: any): node is BoundaryNode { + return ( + node?.type === 'wall' || + (this.options.includeSeparators !== false && node?.type === 'separator') + ) + } + + getLevelTopology(levelId: string): LevelTopology | undefined { + const level = this.levels.get(levelId) + if (!level) return + if (level.topology) return level.topology + const walls = [...level.walls.values()].filter((node): node is WallNode => node.type === 'wall') + const miters = calculateLevelMiters(walls) + const context: LevelFootprintContext = { + revision: level.revision, + walls: new Map(walls.map((wall) => [wall.id, wall])), + wallFootprints: new Map( + walls.map((wall) => [ + wall.id, + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ]), + ), + } + const rooms = level.rooms + .map( + (room): TopologyRoom => ({ + id: room.id, + polygon: room.referencePolygon, + holes: room.holes, + spans: room.spans, + context, + }), + ) + .sort((a, b) => a.id.localeCompare(b.id)) + const spansByBoundary = new Map() + for (const room of rooms) { + for (const span of room.spans) { + const spans = spansByBoundary.get(span.boundaryId) ?? [] + spans.push(span) + spansByBoundary.set(span.boundaryId, spans) + } + } + const exteriorSpans: ExteriorBoundarySpan[] = [] + for (const boundary of [...level.walls.values()].sort((a, b) => a.id.localeCompare(b.id))) { + if (boundary.start[0] === boundary.end[0] && boundary.start[1] === boundary.end[1]) continue + const spans = spansByBoundary.get(boundary.id) ?? [] + spans.sort( + (a, b) => a.face.localeCompare(b.face) || a.t0 - b.t0 || a.roomId.localeCompare(b.roomId), + ) + const cuts = [...new Set([0, 1, ...spans.flatMap((span) => [span.t0, span.t1])])].sort( + (a, b) => a - b, + ) + for (const face of ['a', 'b'] as const) { + for (let i = 0; i < cuts.length - 1; i++) { + const t0 = cuts[i]!, + t1 = cuts[i + 1]! + const mid = (t0 + t1) / 2 + if (!spans.some((span) => span.face === face && span.t0 <= mid && mid < span.t1)) { + exteriorSpans.push({ + roomId: null, + boundaryId: boundary.id, + kind: boundary.type, + face, + t0, + t1, + }) + } + } + } + } + level.topology = { revision: level.revision, rooms, exteriorSpans, spansByBoundary } + return level.topology + } + + spansForWall(levelId: string, wallId: string): readonly BoundarySpan[] { + return this.getLevelTopology(levelId)?.spansByBoundary.get(wallId) ?? [] + } + + roomAtPoint(levelId: string, point: Point): TopologyRoom | null { + return ( + this.getLevelTopology(levelId)?.rooms.find((room) => + containsPoint([{ outer: room.polygon, holes: room.holes }], point), + ) ?? null + ) + } + + /** At a junction, intervals own their start; the final interval also owns t=1. */ + roomForWallHit(levelId: string, wallId: string, face: 'a' | 'b', t: number): TopologyRoom | null { + const topology = this.getLevelTopology(levelId) + const span = topology?.spansByBoundary + .get(wallId) + ?.find( + (candidate) => + candidate.face === face && + t >= candidate.t0 && + (t < candidate.t1 || (t === 1 && candidate.t1 === 1)), + ) + return topology?.rooms.find((room) => room.id === span?.roomId) ?? null + } + private wallsForLevel(nodes: SceneNodes, levelId: string) { const level = nodes[levelId] if (level?.type !== 'level') return [] return level.children.flatMap((id: string) => { const node = nodes[id] - return node?.type === 'wall' && node.parentId === levelId ? [node as WallNode] : [] + return this.isBoundary(node) && node.parentId === levelId ? [node] : [] }) } @@ -200,26 +369,30 @@ export class RoomTopologyIndex { }) } - private createLevel(walls: WallNode[]): IndexedLevelTopology { + private createLevel(walls: BoundaryNode[]): IndexedLevelTopology { const level: IndexedLevelTopology = { + revision: ++this.revision, walls: new Map(), rooms: this.options.detectRooms(walls), wallIdsByCell: new Map(), cellKeysByWallId: new Map(), + cellEntries: 0, + flat: false, } for (const wall of walls) this.setWall(level, wall) return level } - private wallBbox(wall: WallNode) { + private wallBbox(wall: BoundaryNode) { return bboxOf(this.options.sampleWall(wall)) } - private cellKeysForWall(wall: WallNode) { + private cellKeysForWall(wall: BoundaryNode) { return cellKeysForBbox(expandedBbox(this.wallBbox(wall), this.queryMargin)) } private removeWall(level: IndexedLevelTopology, wallId: string) { + level.cellEntries -= level.cellKeysByWallId.get(wallId)?.length ?? 0 for (const key of level.cellKeysByWallId.get(wallId) ?? []) { const ids = level.wallIdsByCell.get(key) ids?.delete(wallId) @@ -229,10 +402,19 @@ export class RoomTopologyIndex { level.walls.delete(wallId) } - private setWall(level: IndexedLevelTopology, wall: WallNode) { + private setWall(level: IndexedLevelTopology, wall: BoundaryNode) { this.removeWall(level, wall.id) level.walls.set(wall.id, wall) + if (level.flat) return const keys = this.cellKeysForWall(wall) + if (!keys || level.cellEntries + keys.length > MAX_CELL_ENTRIES) { + level.flat = true + level.wallIdsByCell.clear() + level.cellKeysByWallId.clear() + level.cellEntries = 0 + return + } + level.cellEntries += keys.length level.cellKeysByWallId.set(wall.id, keys) for (const key of keys) { const ids = level.wallIdsByCell.get(key) ?? new Set() @@ -241,49 +423,79 @@ export class RoomTopologyIndex { } } - private queryWalls(level: IndexedLevelTopology, wall: WallNode) { + private queryWalls(level: IndexedLevelTopology, wall: BoundaryNode) { + if (level.flat) return new Set(level.walls.keys()) + const keys = this.cellKeysForWall(wall) + if (!keys) return new Set(level.walls.keys()) const ids = new Set() - for (const key of this.cellKeysForWall(wall)) { + for (const key of keys) { for (const id of level.wallIdsByCell.get(key) ?? []) ids.add(id) } return ids } - private wallsTouch(left: WallNode, right: WallNode) { + private wallsTouch(left: BoundaryNode, right: BoundaryNode) { const leftPoints = this.options.sampleWall(left) const rightPoints = this.options.sampleWall(right) + // Detection joins a wall end to another wall's body as far as the bodies can touch. + const reach = Math.max(this.options.junctionTolerance, junctionReach(left, right)) const touchesPolyline = (points: Point[], other: Point[]) => { const endpoints = [points[0], points.at(-1)].filter((point): point is Point => Boolean(point)) for (const endpoint of endpoints) { for (let index = 0; index < other.length - 1; index += 1) { - if ( - distanceToSegment(endpoint, other[index]!, other[index + 1]!) <= - this.options.junctionTolerance - ) { + if (distanceToSegment(endpoint, other[index]!, other[index + 1]!) <= reach) { return true } } } return false } - return touchesPolyline(leftPoints, rightPoints) || touchesPolyline(rightPoints, leftPoints) + // Crossing walls share a component too: detection declines near-miss joins on a + // wall that crosses another, so an incremental rebuild must see the same crossing. + return ( + touchesPolyline(leftPoints, rightPoints) || + touchesPolyline(rightPoints, leftPoints) || + boundariesCross(left, right) + ) } private connectedWallIds(level: IndexedLevelTopology, seedIds: Iterable) { const connected = new Set() const queue = [...seedIds] - while (queue.length > 0) { - const wallId = queue.pop()! - if (connected.has(wallId)) continue - const wall = level.walls.get(wallId) - if (!wall) continue - connected.add(wallId) - for (const neighborId of this.queryWalls(level, wall)) { - if (connected.has(neighborId)) continue - const neighbor = level.walls.get(neighborId) - if (neighbor && this.wallsTouch(wall, neighbor)) queue.push(neighborId) + do { + while (queue.length > 0) { + const wallId = queue.pop()! + if (connected.has(wallId)) continue + const wall = level.walls.get(wallId) + if (!wall) continue + connected.add(wallId) + for (const neighborId of this.queryWalls(level, wall)) { + if (connected.has(neighborId)) continue + const neighbor = level.walls.get(neighborId) + if (neighbor && this.wallsTouch(wall, neighbor)) queue.push(neighborId) + } } - } + if (this.options.includeHoles === false || !connected.size) break + // Disconnected enclosures still share a face. Bounds conservatively expand + // the affected component; extraction decides actual containment by booleans. + const bounds = bboxOf( + [...connected].flatMap((id) => this.options.sampleWall(level.walls.get(id)!)), + ) + for (const room of level.rooms) { + const box = bboxOf(room.referencePolygon) + if ( + box.minX > bounds.maxX || + box.maxX < bounds.minX || + box.minY > bounds.maxY || + box.maxY < bounds.minY + ) + continue + for (const span of room.spans) { + if (!connected.has(span.boundaryId) && level.walls.has(span.boundaryId)) + queue.push(span.boundaryId) + } + } + } while (queue.length > 0) return connected } } diff --git a/packages/core/src/lib/room-vertical-placement.ts b/packages/core/src/lib/room-vertical-placement.ts new file mode 100644 index 0000000000..3298b31680 --- /dev/null +++ b/packages/core/src/lib/room-vertical-placement.ts @@ -0,0 +1,38 @@ +import type { AnyNode, WallNode } from '../schema' +import { DEFAULT_SLAB_ELEVATION } from '../schema/nodes/slab' +import type { PlateRoom } from './floor-plates' +import { levelBaseElevationAt } from './terrain-support-query' + +/** + * Automatic floor datum per room: 0.05 m above the highest ground (terrain + + * `supportOffset`) under its boundary walls. + * + * Manual slabs are deliberately not supports here. Load migration explicitly + * associates a retained authored floor with its room. Other manual slabs are + * separate terraces, pads or platforms and must not elect the house datum. + */ +export function autoRoomVerticalPlacements( + rooms: Pick[], + nodes: Readonly>, +) { + const boundaryIds = new Set(rooms.flatMap((room) => room.spans.map((span) => span.boundaryId))) + const bases = new Map() + for (const id of boundaryIds) { + const wall = nodes[id] + if (wall?.type !== 'wall' || wall.parentId !== rooms[0]?.zone.parentId) continue + bases.set( + wall.id, + levelBaseElevationAt(nodes, wall.parentId!, wall.start[0], wall.start[1]) + + (wall.supportOffset ?? 0), + ) + } + return new Map( + rooms.map((room) => { + const heights = room.spans.flatMap((span) => { + const base = bases.get(span.boundaryId as WallNode['id']) + return base === undefined ? [] : [base] + }) + return [room.zone.id, (heights.length ? Math.max(...heights) : 0) + DEFAULT_SLAB_ELEVATION] + }), + ) +} diff --git a/packages/core/src/lib/room-zone-adoption.test.ts b/packages/core/src/lib/room-zone-adoption.test.ts new file mode 100644 index 0000000000..1b5198b0ff --- /dev/null +++ b/packages/core/src/lib/room-zone-adoption.test.ts @@ -0,0 +1,47 @@ +import { expect, test } from 'bun:test' +import type { Ring } from './polygon-boolean' +import { + adoptableFace, + existingRoomFace, + type IdentityFace, + zoneFaceFits, +} from './room-zone-adoption' + +const rectangle = (x: number, y: number, width: number, height: number): Ring => [ + [x, y], + [x + width, y], + [x + width, y + height], + [x, y + height], +] +const face = (key: string, outer: Ring, walls: string[]): IdentityFace => ({ + key, + polygon: { outer, holes: [] }, + clear: { outer, holes: [] }, + boundaryWallIds: walls, + boundarySeparatorIds: [], +}) + +test('an unchanged room keeps the face with its own boundaries, even where faces overlap', () => { + // Degenerate detection (crossing walls) can report overlapping faces; the seed + // and the overlap then point at the bigger one. + const big = face('room-b', rectangle(0, 0, 10, 10), ['wall_1', 'wall_2', 'wall_3', 'wall_4']) + const small = face('room-a', rectangle(0, 0, 4, 4), ['wall_1', 'wall_4', 'wall_5', 'wall_6']) + const room = { + id: 'zone_small', + polygon: rectangle(0, 0, 4, 4), + seed: [2, 2] as [number, number], + boundaryWallIds: ['wall_6', 'wall_5', 'wall_4', 'wall_1'], + } + expect(existingRoomFace(room, [big, small])).toBe(1) + expect(existingRoomFace({ ...room, boundaryWallIds: ['wall_gone'] }, [big, small])).toBe(1) + expect(existingRoomFace({ ...room, seed: [8, 8] }, [big, small])).toBe(1) + expect(existingRoomFace({ ...room, seed: [8, 8], boundaryWallIds: [] }, [big, small])).toBe(0) +}) + +test('an even split breaks the tie on the canonical face key, not on face order', () => { + const left = face('room-left', rectangle(0, 0, 4, 4), []) + const right = face('room-right', rectangle(4, 0, 4, 4), []) + const zone = { id: 'zone_even', polygon: rectangle(2, 0, 4, 4) } + expect(adoptableFace(zoneFaceFits(zone, [left, right]))?.key).toBe('room-left') + expect(adoptableFace(zoneFaceFits(zone, [right, left]))?.key).toBe('room-left') +}) diff --git a/packages/core/src/lib/room-zone-adoption.ts b/packages/core/src/lib/room-zone-adoption.ts new file mode 100644 index 0000000000..022722ec81 --- /dev/null +++ b/packages/core/src/lib/room-zone-adoption.ts @@ -0,0 +1,208 @@ +import { area, containsPoint, intersection, type Polygon, type Ring } from './polygon-boolean' + +/** + * Which existing zone becomes the room of an enclosed face. Shared by the M3 load + * migration and the structure kernel so both load paths and live edits agree. + * + * Hand-drawn zones are loose: drawn to wall centre lines, inner or outer faces, + * tens of centimetres off, sometimes spanning a closet or a second space behind a + * wall. A zone is its face's room when the face holds most of the zone and the zone + * covers most of the face's clear floor, or when the two simply match (IoU). + */ +export const ROOM_MATCH_IOU = 0.9 +/** Part of the face's clear floor the zone must cover. */ +export const ROOM_ADOPT_COVER = 0.5 +/** Part of the zone that must lie in the face (its dominant face). */ +export const ROOM_ADOPT_SHARE = 0.5 + +/** `key` is the face's canonical id (its room id), so ties never depend on face order. */ +export type AdoptionFace = { key: string; polygon: Polygon; clear: Polygon } +export type IdentityFace = AdoptionFace & { + boundaryWallIds: readonly string[] + boundarySeparatorIds: readonly string[] +} +export type ExistingRoom = { + id: string + polygon: Ring + holes?: Ring[] + seed?: [number, number] + boundaryWallIds?: readonly string[] + boundarySeparatorIds?: readonly string[] +} +export type AdoptionZone = { id: string; polygon: Ring; holes?: Ring[] } +export type ZoneFaceFit = { + face: number + key: string + /** Zone area inside the face reference polygon / zone area. */ + share: number + /** Zone area inside the face clear polygon / clear area. */ + cover: number + /** Best IoU against the reference or the clear polygon. */ + iou: number +} + +const EPSILON = 1e-9 + +function bounds(rings: Ring[]) { + let minX = Number.POSITIVE_INFINITY + let minY = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let maxY = Number.NEGATIVE_INFINITY + for (const ring of rings) + for (const [x, y] of ring) { + minX = Math.min(minX, x) + minY = Math.min(minY, y) + maxX = Math.max(maxX, x) + maxY = Math.max(maxY, y) + } + return { minX, minY, maxX, maxY } +} + +function overlaps(a: ReturnType, b: ReturnType) { + return a.minX < b.maxX && b.minX < a.maxX && a.minY < b.maxY && b.minY < a.maxY +} + +/** Every face the zone overlaps, with its fit numbers, in face order. */ +export function zoneFaceFits(zone: AdoptionZone, faces: readonly AdoptionFace[]): ZoneFaceFit[] { + const polygon: Polygon = { outer: zone.polygon, holes: zone.holes ?? [] } + const zoneArea = area([polygon]) + if (!(zoneArea > EPSILON)) return [] + const box = bounds([zone.polygon]) + const fits: ZoneFaceFit[] = [] + faces.forEach((face, index) => { + if (!overlaps(box, bounds([face.polygon.outer]))) return + const overlap = area(intersection(polygon, face.polygon)) + if (!(overlap > EPSILON)) return + const faceArea = area([face.polygon]) + const clearArea = face.clear.outer.length >= 3 ? area([face.clear]) : 0 + const clearOverlap = clearArea > EPSILON ? area(intersection(polygon, face.clear)) : overlap + fits.push({ + face: index, + key: face.key, + share: overlap / zoneArea, + cover: clearOverlap / (clearArea > EPSILON ? clearArea : faceArea), + iou: Math.max( + overlap / (zoneArea + faceArea - overlap), + clearArea > EPSILON ? clearOverlap / (zoneArea + clearArea - clearOverlap) : 0, + ), + }) + }) + return fits +} + +/** The face holding most of the zone, when the zone is that face's room. */ +export function adoptableFace(fits: readonly ZoneFaceFit[]): ZoneFaceFit | undefined { + let best: ZoneFaceFit | undefined + for (const fit of fits) + if ( + !best || + fit.share > best.share + EPSILON || + (Math.abs(fit.share - best.share) <= EPSILON && + (fit.cover > best.cover + EPSILON || + (Math.abs(fit.cover - best.cover) <= EPSILON && fit.key < best.key))) + ) + best = fit + if (!best) return + return best.iou >= ROOM_MATCH_IOU || + (best.cover >= ROOM_ADOPT_COVER && best.share >= ROOM_ADOPT_SHARE) + ? best + : undefined +} + +/** Orders two candidates for one face: the zone covering more of it wins. */ +export function compareAdoptionFits( + a: { id: string; fit: ZoneFaceFit }, + b: { id: string; fit: ZoneFaceFit }, +) { + return ( + b.fit.cover - a.fit.cover || b.fit.iou - a.fit.iou || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) + ) +} + +/** Face index → adopted zone id; at most one zone per face, one face per zone. */ +export function electAdoptedZones( + faces: readonly AdoptionFace[], + zones: readonly AdoptionZone[], +): Map { + const candidates = new Map() + for (const zone of zones) { + const fit = adoptableFace(zoneFaceFits(zone, faces)) + if (!fit) continue + const list = candidates.get(fit.face) ?? [] + list.push({ id: zone.id, fit }) + candidates.set(fit.face, list) + } + const elected = new Map() + for (const [face, list] of candidates) elected.set(face, list.sort(compareAdoptionFits)[0]!.id) + return elected +} + +function iou(a: Polygon, b: Polygon) { + const overlap = area(intersection(a, b)) + const combined = area([a]) + area([b]) - overlap + return combined > 0 ? overlap / combined : 0 +} + +const boundaryKey = (walls: readonly string[] = [], separators: readonly string[] = []) => + JSON.stringify([[...walls].sort(), [...separators].sort()]) + +/** + * The face an existing room keeps: the face with exactly its boundaries (nothing + * about it changed, even where degenerate faces overlap), then the outer face when + * its separators just carved an island, then the face holding its seed, then the + * largest overlap. + * Shared by the load migration and the structure kernel, so a reload never trades an + * existing room for a newly created one. + */ +export function existingRoomFace( + room: ExistingRoom, + faces: readonly IdentityFace[], + overlaps: readonly number[] = faces.map((face) => + iou({ outer: room.polygon, holes: room.holes ?? [] }, face.polygon), + ), +): number | undefined { + const holes = room.holes ?? [] + const separators = room.boundarySeparatorIds ?? [] + const own = boundaryKey(room.boundaryWallIds, separators) + return faces + .map((face, index) => ({ + index, + key: face.key, + exact: + own !== boundaryKey() && + boundaryKey(face.boundaryWallIds, face.boundarySeparatorIds) === own, + overlap: overlaps[index]!, + seed: !!room.seed && containsPoint([face.polygon], room.seed), + // A new separator island takes area from the room, never its identity, + // even when the old seed lies inside the new island. + islandOuter: + face.polygon.holes.length > holes.length && + face.boundarySeparatorIds.some((id) => !separators.includes(id)) && + iou({ outer: room.polygon, holes: [] }, { outer: face.polygon.outer, holes: [] }) > + 1 - 1e-6, + })) + .filter(({ overlap, seed }) => seed || overlap > 0) + .sort( + (a, b) => + Number(b.exact) - Number(a.exact) || + Number(b.islandOuter) - Number(a.islandOuter) || + Number(b.seed) - Number(a.seed) || + b.overlap - a.overlap || + (a.key < b.key ? -1 : a.key > b.key ? 1 : 0), + )[0]?.index +} + +/** Among existing rooms keeping one face, the one covering most of it survives. */ +export function compareExistingRooms(face: IdentityFace) { + const covered = new Map() + const cover = (room: ExistingRoom) => { + let value = covered.get(room.id) + if (value === undefined) { + value = area(intersection({ outer: room.polygon, holes: room.holes ?? [] }, face.polygon)) + covered.set(room.id, value) + } + return value + } + return (a: ExistingRoom, b: ExistingRoom) => + cover(b) - cover(a) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) +} diff --git a/packages/core/src/lib/slab-polygon.ts b/packages/core/src/lib/slab-polygon.ts index 3aa8ffc894..634c268995 100644 --- a/packages/core/src/lib/slab-polygon.ts +++ b/packages/core/src/lib/slab-polygon.ts @@ -1,13 +1,18 @@ import type { GeometryContext } from '../registry/types' import type { AnyNode, AnyNodeId, SlabNode, WallNode } from '../schema' -import { isCurvedWall, sampleWallCenterline } from '../systems/wall/wall-curve' -import { getWallThickness } from '../systems/wall/wall-footprint' +import { DEFAULT_SLAB_ELEVATION } from '../schema/nodes/slab' +import { getWallCurveFrameAt, isCurvedWall, sampleWallCenterline } from '../systems/wall/wall-curve' +import { + getWallBodyCenterOffset, + getWallBodyLine, + getWallFaceOffsets, +} from '../systems/wall/wall-frame' /** * Render-time slab polygon rules. * - * Slab nodes store the wall-centerline polygon (auto slabs) or the drawn - * polygon (manual slabs) — render offsets are NEVER stored in node data. + * Auto plates store their full footprint and render unchanged. Manual slabs + * keep the drawn polygon and adopt wall faces at render time. * At geometry build time each polygon edge is SPLIT at the clipped span * boundaries of every overlapping candidate (sibling slab edges and wall * centerlines in the adoption band) and each sub-edge is classified @@ -80,7 +85,6 @@ const MIN_SUBEDGE_LENGTH = 0.05 const WALL_LATERAL_TIE_EPSILON = 0.02 const CURVED_WALL_SAMPLE_SEGMENTS = 32 const SLAB_SEAM_ELEVATION_EPSILON = 1e-4 -const DEFAULT_SLAB_ELEVATION = 0.05 const DEFAULT_SLAB_THICKNESS = 0.05 /** * A non-recessed slab whose underside (`elevation − thickness`) rises @@ -173,6 +177,7 @@ export function getRenderableSlabPolygon( context: SlabPolygonContext | PreparedSlabPolygonContext, ): Array<[number, number]> { const polygon = slabNode.polygon + if (slabNode.boundary === 'auto') return polygon if (polygon.length < 3 || isFloatingSlab(slabNode)) { return polygon.map(([x, z]) => [x, z] as [number, number]) } @@ -249,10 +254,16 @@ function clipCollinearSegment( function wallCenterlineSegments(wall: WallNode): Segment[] { if (!isCurvedWall(wall)) { - return [[wall.start[0], wall.start[1], wall.end[0], wall.end[1]]] + const { start, end } = getWallBodyLine(wall) + return [[start.x, start.y, end.x, end.y]] } - const points = sampleWallCenterline(wall, CURVED_WALL_SAMPLE_SEGMENTS) + const centerOffset = getWallBodyCenterOffset(wall) + const points = sampleWallCenterline(wall, CURVED_WALL_SAMPLE_SEGMENTS).map((point, index) => { + if (centerOffset === 0) return point + const { normal } = getWallCurveFrameAt(wall, index / CURVED_WALL_SAMPLE_SEGMENTS) + return { x: point.x + normal.x * centerOffset, y: point.y + normal.y * centerOffset } + }) const segments: Segment[] = [] for (let index = 0; index < points.length - 1; index += 1) { const from = points[index]! @@ -354,15 +365,23 @@ export function snapSlabEdgeToWallBand( const candidates: WallCandidate[] = walls.map((wall) => ({ wall, segments: wallCenterlineSegments(wall), - halfThickness: getWallThickness(wall) / 2, + halfThickness: getWallFaceOffsets(wall).a - getWallBodyCenterOffset(wall), })) const match = matchEdgeWallBand(a[0], a[1], dirX, dirZ, edgeLength, requiredOverlap, candidates) if (!match) return null if (options?.maxLateral !== undefined && Math.abs(match.lateral) > options.maxLateral) return null - const nx = dirZ * match.lateral - const nz = -dirX * match.lateral + const wallDx = match.wall.end[0] - match.wall.start[0] + const wallDz = match.wall.end[1] - match.wall.start[1] + const wallLength = Math.hypot(wallDx, wallDz) + const centerOffset = getWallBodyCenterOffset(match.wall) + const lateral = + centerOffset === 0 || wallLength < 1e-9 + ? match.lateral + : match.lateral + (centerOffset * (wallDx * dirX + wallDz * dirZ)) / wallLength + const nx = dirZ * lateral + const nz = -dirX * lateral return { wallId: match.wall.id, edge: [ @@ -388,7 +407,12 @@ type EdgeSubSpan = { type Bounds = [number, number, number, number] function polygonBounds(polygon: Array<[number, number]>): Bounds { - const bounds: Bounds = [Infinity, Infinity, -Infinity, -Infinity] + const bounds: Bounds = [ + Number.POSITIVE_INFINITY, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + Number.NEGATIVE_INFINITY, + ] for (const [x, z] of polygon) { bounds[0] = Math.min(bounds[0], x) bounds[1] = Math.min(bounds[1], z) @@ -530,7 +554,7 @@ export function prepareSlabPolygonContext( const candidate: PreparedWallCandidate = { wall, segments, - halfThickness: getWallThickness(wall) / 2, + halfThickness: getWallFaceOffsets(wall).a - getWallBodyCenterOffset(wall), bounds: polygonBounds( segments.flatMap(([ax, az, bx, bz]) => [ [ax, az], diff --git a/packages/core/src/lib/slots.ts b/packages/core/src/lib/slots.ts index 3b3db329ad..f826e6dd9b 100644 --- a/packages/core/src/lib/slots.ts +++ b/packages/core/src/lib/slots.ts @@ -1,3 +1,6 @@ +import { parseMaterialRef } from '../material-library' +import type { MaterialSchema } from '../schema/material' + export const SLOT_MATERIAL_PREFIX = 'slot_' /** A glTF material name marks a paintable slot when it starts with `slot_` (case-insensitive). */ @@ -25,3 +28,29 @@ export function slotLabelFromId(slotId: string): string { if (!spaced) return spaced return spaced.charAt(0).toUpperCase() + spaced.slice(1) } + +/** + * A slot's declared `default` as a paint material: a `library:` / `scene:` ref + * stays a ref, a `#rrggbb` colour becomes a flat colour. What an unpainted slot + * draws, for the eyedropper; null for anything else. + */ +export function slotDefaultPaintMaterial( + value: string | undefined, +): { material?: MaterialSchema; materialPreset?: string } | null { + if (!value) return null + if (parseMaterialRef(value)) return { materialPreset: value } + if (!/^#[0-9a-f]{6}$/i.test(value)) return null + return { + material: { + preset: 'custom', + properties: { + color: value.toLowerCase(), + roughness: 0.9, + metalness: 0, + opacity: 1, + transparent: false, + side: 'front', + }, + }, + } +} diff --git a/packages/core/src/lib/space-detection-invariants.test.ts b/packages/core/src/lib/space-detection-invariants.test.ts new file mode 100644 index 0000000000..bf58dec58b --- /dev/null +++ b/packages/core/src/lib/space-detection-invariants.test.ts @@ -0,0 +1,385 @@ +import { describe, expect, test } from 'bun:test' +import { CeilingNode, LevelNode, SlabNode, WallNode } from '../schema' +import { computeWallSlabSupport } from '../systems/slab/slab-support' +import { migrateVerticalSceneNodes } from '../utils/vertical-scene-migration' +import { getRenderableSlabPolygon } from './slab-polygon' +import { detectSpacesForLevel } from './space-detection' +import { reconcileLevelStructure } from './structure-kernel' +import { reconcileSceneStructure } from './structure-reconcile' + +type Tuple = [number, number] + +function rectangle(x: number, y: number, width: number, height: number): Tuple[] { + return [ + [x, y], + [x + width, y], + [x + width, y + height], + [x, y + height], + ] +} + +function expectPolygonRotation(actual: Tuple[], expected: Tuple[]) { + expect(actual).toHaveLength(expected.length) + const offset = expected.findIndex( + ([x, y]) => Math.abs(x - actual[0]![0]) < 1e-9 && Math.abs(y - actual[0]![1]) < 1e-9, + ) + expect(offset).toBeGreaterThanOrEqual(0) + actual.forEach(([x, y], index) => { + const point = expected[(index + offset) % expected.length]! + expect(x).toBeCloseTo(point[0], 9) + expect(y).toBeCloseTo(point[1], 9) + }) +} + +describe('room generator invariants', () => { + test('I5: an associated authored floor replaces a connected plate, and removal restores it', () => { + const polygon = rectangle(0, 0, 8, 4) + const level = LevelNode.parse({ id: 'level_test' }) + const walls = polygon.map((start, i) => + WallNode.parse({ id: `wall_${i}`, parentId: level.id, start, end: polygon[(i + 1) % 4] }), + ) + walls.push( + WallNode.parse({ id: 'wall_divider', parentId: level.id, start: [2, 0], end: [2, 4] }), + ) + const manual = SlabNode.parse({ id: 'slab_manual', parentId: level.id, polygon }) + const nodes = Object.fromEntries([level, ...walls].map((node) => [node.id, node])) + let id = 0 + const mintId = (kind: string) => `${kind}_${id++}` + const initial = reconcileSceneStructure({ nodes, mintId }).nodes + const withOwner = Object.fromEntries( + Object.entries(initial).map(([id, node]) => [ + id, + node.type === 'zone' + ? { ...node, floor: { ...node.floor, sourceSlabId: manual.id } } + : node, + ]), + ) + const covered = reconcileSceneStructure({ + nodes: { ...withOwner, [manual.id]: manual }, + mintId, + }).nodes + expect(Object.values(covered).filter((node) => node.type === 'slab')).toEqual([manual]) + const { [manual.id]: _, ...withoutManual } = covered + const restored = reconcileSceneStructure({ nodes: withoutManual, mintId }).nodes + expect(Object.values(restored).filter((node) => node.type === 'slab')).toHaveLength(1) + const distant = { ...manual, polygon: rectangle(20, 20, 8, 4) } + const unaffected = reconcileSceneStructure({ + nodes: { ...restored, [distant.id]: distant }, + mintId, + }).nodes + expect(Object.values(unaffected).filter((node) => node.type === 'slab')).toHaveLength(2) + expect(unaffected[distant.id]).toBe(distant) + }) + + for (const kind of ['slab', 'ceiling'] as const) { + test(`I7: ${kind} orphan retirement deletes derived construction and preserves a manual cover`, () => { + const level = LevelNode.parse({ id: 'level_test' }) + const polygon = rectangle(0, 0, 4, 4) + const walls = polygon.map((start, index) => + WallNode.parse({ + id: `wall_${index}`, + parentId: level.id, + start, + end: polygon[(index + 1) % 4], + }), + ) + const schema = kind === 'slab' ? SlabNode : CeilingNode + const orphan = schema.parse({ + id: `${kind}_orphan`, + parentId: level.id, + boundary: 'auto', + polygon: rectangle(-2, -2, 8, 8), + autoFromWalls: true, + }) + const manual = schema.parse({ id: `${kind}_manual`, parentId: level.id, polygon }) + const nodes = Object.fromEntries( + [level, ...walls, orphan, manual].map((node) => [node.id, node]), + ) + const result = reconcileLevelStructure({ + levelId: level.id, + nodes, + mintId: (kind) => `${kind}_created`, + }) + expect( + result.patches.filter((patch) => patch.op === 'create' && patch.node.type === kind), + ).toEqual([]) + expect(result.patches.filter((patch) => patch.op === 'delete')).toEqual( + kind === 'slab' ? [] : [{ op: 'delete', id: orphan.id }], + ) + if (kind === 'slab') + expect(result.patches).toContainEqual( + expect.objectContaining({ + op: 'update', + id: orphan.id, + data: expect.objectContaining({ plateRole: 'base' }), + }), + ) + expect(result.patches.some((patch) => patch.op === 'update' && patch.id === manual.id)).toBe( + false, + ) + }) + } + + test('I8: span sides classify exterior, shared and reversed walls; free walls keep previous sides', () => { + const polygon = rectangle(0, 0, 4, 4) + const walls = polygon.map((start, i) => + WallNode.parse({ id: `wall_outer_${i}`, start, end: polygon[(i + 1) % 4] }), + ) + const sides = (boundaries: WallNode[], id: string) => + detectSpacesForLevel('level_test', boundaries).wallUpdates.find( + (update) => update.wallId === id, + ) + expect(sides(walls, walls[0]!.id)).toMatchObject({ + frontSide: 'interior', + backSide: 'exterior', + }) + const reversed = { ...walls[0]!, start: walls[0]!.end, end: walls[0]!.start } + expect(sides([reversed, ...walls.slice(1)], reversed.id)).toMatchObject({ + frontSide: 'exterior', + backSide: 'interior', + }) + const divider = WallNode.parse({ + id: 'wall_shared', + start: [2, 0], + end: [2, 4], + frontSide: 'exterior', + backSide: 'interior', + }) + expect(sides([...walls, divider], divider.id)).toMatchObject({ + frontSide: 'interior', + backSide: 'interior', + }) + expect(sides([divider], divider.id)).toMatchObject({ + frontSide: 'exterior', + backSide: 'interior', + }) + }) + + test('I10: stored auto plates retain majority support election and stepped base segments', () => { + const wall = WallNode.parse({ id: 'wall_support', start: [0, 0], end: [10, 0], thickness: 0.2 }) + for (const highWidth of [7, 3]) { + const high = SlabNode.parse({ + id: 'slab_high', + boundary: 'auto', + polygon: rectangle(0, -1, highWidth, 2), + elevation: 0.6, + thickness: 0.6, + }) + const low = SlabNode.parse({ + id: 'slab_low', + boundary: 'auto', + polygon: rectangle(highWidth, -1, 10 - highWidth, 2), + elevation: 0.1, + thickness: 0.1, + }) + const support = computeWallSlabSupport(wall, [low, high], [wall]) + expect(support.elevation).toBe(highWidth === 7 ? 0.6 : 0.1) + expect(support.electedSlabId).toBe(highWidth === 7 ? high.id : low.id) + expect(support.baseElevation).toBe(0.1) + expect(support.baseSegments).toHaveLength(2) + expect(support.baseSegments[0]!.start).toBe(0) + expect(support.baseSegments[0]!.end).toBeCloseTo(highWidth / 10) + expect(support.baseSegments[0]!.elevation).toBe(0.6) + expect(support.baseSegments[1]!.start).toBeCloseTo(highWidth / 10) + expect(support.baseSegments[1]!.end).toBe(1) + expect(support.baseSegments[1]!.elevation).toBe(0.1) + expect(computeWallSlabSupport(wall, [high, low], [wall])).toEqual(support) + } + }) + + test('I11: generated plates store exterior wall faces and render unchanged', () => { + const polygon = rectangle(0, 0, 4, 3) + const walls = polygon.map((start, index) => + WallNode.parse({ + id: `wall_centerline_${index}`, + parentId: 'level_centerline', + start, + end: polygon[(index + 1) % 4], + thickness: 0.2, + }), + ) + const level = LevelNode.parse({ + id: 'level_centerline', + children: walls.map((wall) => wall.id), + }) + const nodes = Object.fromEntries([level, ...walls].map((node) => [node.id, node])) + const result = reconcileSceneStructure({ nodes, mintId: (kind) => `${kind}_test` }) + const slab = Object.values(result.nodes).find((node): node is SlabNode => node.type === 'slab')! + const rendered = getRenderableSlabPolygon(slab, { walls, siblingSlabs: [] }) + expectPolygonRotation(rendered, [ + [-0.1, -0.1], + [4.1, -0.1], + [4.1, 3.1], + [-0.1, 3.1], + ]) + expect(rendered).toBe(slab.polygon) + const deck = SlabNode.parse({ + id: 'slab_floating_deck', + polygon, + elevation: 1.5, + thickness: 0.05, + }) + expect(deck.elevation - deck.thickness).toBeGreaterThan(0.01) + expect(getRenderableSlabPolygon(deck, { walls, siblingSlabs: [] })).toEqual(polygon) + }) +}) + +type RawNode = Record + +function legacyNode( + id: string, + type: string, + parentId: string | null, + extra: RawNode = {}, +): RawNode { + return { object: 'node', id, type, parentId, visible: true, metadata: {}, ...extra } +} + +const square = rectangle(0, 0, 4, 4) +const legacyWall = (id: string, height?: number, start: Tuple = [0, 0], end: Tuple = [4, 0]) => + legacyNode(id, 'wall', 'level_a', { + start, + end, + children: [], + ...(height === undefined ? {} : { height }), + }) +const legacySlab = (id: string, elevation: number | undefined) => + legacyNode(id, 'slab', 'level_a', { + polygon: square, + holes: [], + ...(elevation === undefined ? {} : { elevation }), + }) +const legacyCeiling = (height: number, extra: RawNode = {}) => + legacyNode('ceiling_a', 'ceiling', 'level_a', { polygon: square, holes: [], height, ...extra }) + +function legacyScene(children: RawNode[], levelExtra: RawNode = {}) { + const nodes = [ + legacyNode('site_test', 'site', null, { children: ['building_a'] }), + legacyNode('building_a', 'building', 'site_test', { children: ['level_a'] }), + legacyNode('level_a', 'level', 'building_a', { + level: 0, + children: children.map((node) => node.id), + ...levelExtra, + }), + ...children, + ] + return Object.fromEntries(nodes.map((node) => [String(node.id), node])) +} + +describe('I12: vertical migration byte idempotence on legacy migration fixtures', () => { + // These raw fixtures mirror use-scene-vertical-migration.test.ts; schema parsing would erase legacy absence. + const fixtures: Array<[string, Record]> = [ + [ + 'default storey', + legacyScene([ + legacySlab('slab_a', 0.05), + legacyWall('wall_a'), + legacyWall('wall_b', undefined, [4, 0], [4, 4]), + ]), + ], + ['empty level', legacyScene([])], + [ + 'near-plane walls', + legacyScene([ + legacySlab('slab_a', 0.05), + legacyWall('wall_tall', 2.65), + legacyWall('wall_a', undefined, [4, 0], [4, 4]), + legacyWall('wall_b', undefined, [0, 4], [4, 4]), + ]), + ], + [ + 'intentional short walls', + legacyScene([ + legacyCeiling(2.5), + legacyWall('wall_a', 2.3), + legacyWall('wall_b', 2.1, [4, 0], [4, 4]), + ]), + ], + ['absent short wall', legacyScene([legacyCeiling(3), legacyWall('wall_a')])], + ['near-bound ceiling', legacyScene([legacyCeiling(2.5)])], + ['clamped ceiling', legacyScene([legacyCeiling(2.49)])], + ['intentional low ceiling', legacyScene([legacyWall('wall_tall', 3), legacyCeiling(2)])], + [ + 'auto ceiling', + legacyScene([legacyWall('wall_tall', 3), legacyCeiling(2.2, { autoFromWalls: true })]), + ], + [ + 'legacy stairs', + legacyScene([ + legacyNode('stair_a', 'stair', 'level_a', { + position: [1, 0, 1], + children: [], + totalRise: 2.5, + }), + legacyNode('stair_b', 'stair', 'level_a', { + position: [1, 0, 1], + children: [], + totalRise: 3.1, + }), + ]), + ], + ['raised and zero slabs', legacyScene([legacySlab('slab_a', 0.3), legacySlab('slab_b', 0)])], + ['absent slab elevation', legacyScene([legacySlab('slab_a', undefined)])], + ['legacy pool', legacyScene([legacySlab('slab_a', -0.15)])], + [ + 'already-split below-plane solid', + legacyScene([{ ...legacySlab('slab_a', -0.15), thickness: 0.3 }]), + ], + ] + const mixed = legacyScene( + [ + legacySlab('slab_a', 0.05), + legacyWall('wall_tall', 2.65), + legacyWall('wall_a', undefined, [4, 0], [4, 4]), + legacyNode('stair_a', 'stair', 'level_a', { + position: [1, 0, 1], + children: [], + totalRise: 2.5, + }), + legacyNode('stair_b', 'stair', 'level_a', { + position: [1, 0, 1], + children: [], + totalRise: 3.1, + }), + ], + { level: 2.5 }, + ) + mixed.building_a!.children = ['level_a', 'level_b'] + mixed.level_b = legacyNode('level_b', 'level', 'building_a', { + level: 5, + children: ['ceiling_b', 'wall_b'], + }) + mixed.ceiling_b = { ...legacyCeiling(3), id: 'ceiling_b', parentId: 'level_b' } + mixed.wall_b = { ...legacyWall('wall_b'), parentId: 'level_b' } + fixtures.push(['mixed idempotence fixture', mixed]) + + const ordinals: Record = { + site_test: legacyNode('site_test', 'site', null, { children: ['building_a', 'building_b'] }), + } + for (const [building, levels] of [ + ['a', [2.5, 2.5, 5]], + ['b', [-3, -1, 0, 4]], + ] as const) { + const children = levels.map((_, index) => `level_${building}${index + 1}`) + ordinals[`building_${building}`] = legacyNode(`building_${building}`, 'building', 'site_test', { + children, + }) + levels.forEach((level, index) => { + const id = children[index]! + ordinals[id] = legacyNode(id, 'level', `building_${building}`, { level, children: [] }) + }) + } + fixtures.push(['per-building fractional and basement ordinals', ordinals]) + + test.each(fixtures)('I12: %s', (_, fixture) => { + const original = JSON.stringify(fixture) + const first = migrateVerticalSceneNodes(fixture) + expect(first.changed).toBe(true) + const bytes = JSON.stringify(first.nodes) + const second = migrateVerticalSceneNodes(JSON.parse(bytes)) + expect(second.changed).toBe(false) + expect(JSON.stringify(second.nodes)).toBe(bytes) + expect(JSON.stringify(first.nodes)).toBe(bytes) + expect(JSON.stringify(fixture)).toBe(original) + }) +}) diff --git a/packages/core/src/lib/space-detection-reconciliation.test.ts b/packages/core/src/lib/space-detection-reconciliation.test.ts index f591b20c86..5d35a6bd20 100644 --- a/packages/core/src/lib/space-detection-reconciliation.test.ts +++ b/packages/core/src/lib/space-detection-reconciliation.test.ts @@ -1,136 +1,21 @@ -import { describe, expect, test } from 'bun:test' -import { CeilingNode, SlabNode, WallNode } from '../schema' -import { - detectSpacesForLevel, - planAutoCeilingsForLevel, - planAutoSlabsForLevel, - surfaceTouchesRooms, -} from './space-detection' - -type Tuple = [number, number] - -function bounded(polygon: Tuple[]) { - return { - polygon: polygon.map(([x, y]) => ({ x, y })), - bbox: { - minX: Math.min(...polygon.map(([x]) => x)), - minY: Math.min(...polygon.map(([, y]) => y)), - maxX: Math.max(...polygon.map(([x]) => x)), - maxY: Math.max(...polygon.map(([, y]) => y)), - }, - } -} - -function rectangle(x: number, y: number, width: number, height: number): Tuple[] { - return [ - [x, y], - [x + width, y], - [x + width, y + height], - [x, y + height], - ] -} - -describe('surfaceTouchesRooms bounding-box rejection', () => { - const surface = bounded(rectangle(0, 0, 4, 4)) - const cases: Array<[string, Tuple[], boolean]> = [ - ['disjoint right', rectangle(5, 0, 4, 4), false], - ['disjoint left', rectangle(-5, 0, 4, 4), false], - ['disjoint above', rectangle(0, 5, 4, 4), false], - ['disjoint below', rectangle(0, -5, 4, 4), false], - ['touching edge', rectangle(4, 0, 4, 4), false], - ['touching corner', rectangle(4, 4, 4, 4), false], - ['overlapping', rectangle(2, 2, 4, 4), true], - ['contained room', rectangle(1, 1, 2, 2), true], - ['contained surface', rectangle(-1, -1, 6, 6), true], - ['identical', rectangle(0, 0, 4, 4), true], - [ - 'overlapping bounds without polygon coverage', - [ - [3, 6], - [6, 3], - [6, 6], - ], - false, - ], +import { expect, test } from 'bun:test' +import { SlabNode, WallNode } from '../schema' +import { getRenderableSlabPolygon } from './slab-polygon' + +test('stored plate rings are returned unchanged, including start rotation and winding', () => { + const ring: [number, number][] = [ + [-0.1, -0.1], + [4.1, -0.1], + [4.1, 3.1], + [-0.1, 3.1], ] - - for (const [name, polygon, expected] of cases) { - test(name, () => { - const room = bounded(polygon) - expect(surfaceTouchesRooms(surface, [room])).toBe(expected) - expect(surfaceTouchesRooms(room, [surface])).toBe(expected) - }) - } - - test('disjoint bounds skip coverage and touching bounds retain coverage', () => { - for (const x of [4, 5]) { - const room = bounded(rectangle(x, 0, 4, 4)) - let reads = 0 - const measuredRoom = { - bbox: room.bbox, - get polygon() { - reads += 1 - return room.polygon - }, - } - expect(surfaceTouchesRooms(surface, [measuredRoom])).toBe(false) - expect(reads > 0).toBe(x === 4) + const walls = [WallNode.parse({ start: [0, 0], end: [4, 0], thickness: 0.6 })] + for (const points of [ring, [...ring].reverse()]) + for (let i = 0; i < points.length; i++) { + const slab = SlabNode.parse({ + polygon: [...points.slice(i), ...points.slice(0, i)], + boundary: 'auto', + }) + expect(getRenderableSlabPolygon(slab, { walls, siblingSlabs: [] })).toBe(slab.polygon) } - }) - - test('continues past disjoint rooms and handles no rooms', () => { - expect(surfaceTouchesRooms(surface, [])).toBe(false) - expect(surfaceTouchesRooms(surface, [bounded(rectangle(5, 5, 1, 1)), surface])).toBe(true) - }) -}) - -describe('auto surface planner ring preservation', () => { - const vertices = rectangle(0, 0, 4, 3) - const walls = vertices.map((start, index) => - WallNode.parse({ start, end: vertices[(index + 1) % vertices.length] }), - ) - const { roomPolygons } = detectSpacesForLevel('level_rotation', walls) - const ring = roomPolygons[0]!.map(({ x, y }): Tuple => [x, y]) - - for (const kind of ['slab', 'ceiling'] as const) { - function plan(polygon: Tuple[]) { - if (kind === 'slab') { - const surface = SlabNode.parse({ polygon, autoFromWalls: true }) - return { surface, result: planAutoSlabsForLevel(roomPolygons, [surface]) } - } - const surface = CeilingNode.parse({ polygon, autoFromWalls: true }) - return { surface, result: planAutoCeilingsForLevel(roomPolygons, [surface]) } - } - - test(`${kind}: every exact start rotation preserves the existing polygon`, () => { - for (let offset = 0; offset < ring.length; offset += 1) { - const polygon = [...ring.slice(offset), ...ring.slice(0, offset)] - const { surface, result } = plan(polygon) - const existingPolygon = surface.polygon - expect(result.update).toEqual([]) - expect(result.create).toEqual([]) - expect(result.delete).toEqual([]) - expect(surface.polygon).toBe(existingPolygon) - expect(surface.polygon).toEqual(polygon) - } - }) - - test(`${kind}: changed geometry still updates even within signature rounding`, () => { - for (const delta of [0.2, 0.00001]) { - const polygon = ring.map(([x, y]): Tuple => [x, y]) - polygon[0]![0] += delta - const { surface, result } = plan(polygon) - expect(result.update).toEqual([{ id: surface.id, data: { polygon: ring } }]) - expect(result.create).toEqual([]) - expect(result.delete).toEqual([]) - } - }) - - test(`${kind}: reversed winding still updates`, () => { - const { surface, result } = plan([...ring].reverse()) - expect(result.update).toEqual([{ id: surface.id, data: { polygon: ring } }]) - expect(result.create).toEqual([]) - expect(result.delete).toEqual([]) - }) - } }) diff --git a/packages/core/src/lib/space-detection.test.ts b/packages/core/src/lib/space-detection.test.ts index def0d67ec5..e685372fc7 100644 --- a/packages/core/src/lib/space-detection.test.ts +++ b/packages/core/src/lib/space-detection.test.ts @@ -1,21 +1,19 @@ import { describe, expect, test } from 'bun:test' -import { BuildingNode, CeilingNode, LevelNode, SlabNode, WallNode, ZoneNode } from '../schema' +import { readFileSync } from 'node:fs' +import { BuildingNode, CeilingNode, LevelNode, SlabNode, WallNode } from '../schema' import type { AnyNode, AnyNodeId } from '../schema/types' -import { resolveCeilingHeight } from '../services/level-height' -import { getCeilingClampBound } from '../services/storey' import { runWithSceneCommitNodeIds, type SceneCommit, subscribeSceneCommits, } from '../store/history-control' import useScene, { clearSceneHistory } from '../store/use-scene' +import { migrateCeilingRoomLinks, migrateRoomZones } from '../utils/room-zone-migration' +import { area } from './polygon-boolean' +import { extractRooms } from './room-graph' import { detectSpacesForLevel, initSpaceDetectionSync, - planAutoCeilingsForLevel, - planAutoSlabsForLevel, - planAutoZonesForLevel, - resolveAutoZonePolygon, type SpaceTopologyReconcileEvent, wallClosesRoom, } from './space-detection' @@ -39,10 +37,6 @@ const square: Array<[number, number]> = [ [0, 3], ] -function roomPolygon() { - return square.map(([x, y]) => ({ x, y })) -} - function squareWalls(height = 2.5) { return [ WallNode.parse({ start: [0, 0], end: [4, 0], height }), @@ -52,14 +46,6 @@ function squareWalls(height = 2.5) { ] } -function slab(elevation: number) { - return SlabNode.parse({ - polygon: square, - elevation, - autoFromWalls: true, - }) -} - describe('space detection scene commit boundary', () => { test('includes room reconciliation in the closing wall commit and undo step', () => { const buildingId = 'building_space_commit' as AnyNodeId @@ -168,549 +154,30 @@ describe('space detection scene commit boundary', () => { }) }) -describe('planAutoCeilingsForLevel', () => { - test('creates auto ceilings height-less so they follow the level top', () => { - const created = planAutoCeilingsForLevel([roomPolygon()], [], { - storeyHeight: 2.7, - }).create[0] - - expect(created).toBeDefined() - // Follows-mode: no stored height — the effective height derives from - // the clamp bound at read time via resolveCeilingHeight. - expect('height' in created!).toBe(false) - expect(created?.autoFromWalls).toBe(true) - }) - - test('never writes a height onto a matched auto ceiling', () => { - const ceiling = CeilingNode.parse({ - polygon: square, - autoFromWalls: true, - }) - - const plan = planAutoCeilingsForLevel([roomPolygon()], [ceiling], { - storeyHeight: 3, - }) - - // Same polygon, follows-mode height — nothing to update. - expect(plan.create).toHaveLength(0) - expect(plan.update).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - }) - - test('creates and reconciles an auto ceiling at the enclosing wall top', () => { - const context = { - heightForRoom: () => 3.09, - } - const created = planAutoCeilingsForLevel([roomPolygon()], [], context).create[0] - - expect(created?.height).toBeCloseTo(3.09) - - const existing = CeilingNode.parse({ - polygon: square, - height: 2.49, - autoFromWalls: true, - }) - const update = planAutoCeilingsForLevel([roomPolygon()], [existing], context).update[0] - - expect(update?.id).toBe(existing.id) - expect(update?.data.height).toBeCloseTo(3.09) - }) - - test('a leftover explicit height on a matched auto ceiling is not rewritten', () => { - const ceiling = CeilingNode.parse({ - polygon: square, - height: 2.55, - autoFromWalls: true, - }) - - const plan = planAutoCeilingsForLevel([roomPolygon()], [ceiling], { - storeyHeight: 3, - }) - - // The sync no longer re-derives auto heights; a user-set explicit - // height survives (still under the bound, so no clamp either). - expect(plan.update).toHaveLength(0) - }) - - test('does not replace a manual ceiling with an auto ceiling', () => { - const manualCeiling = CeilingNode.parse({ - polygon: square, - height: 2.5, - autoFromWalls: false, - }) - - // Storey plane above the stored 2.5 so the stage 3-B manual re-clamp - // stays out of this test's scope (suppression only). - const plan = planAutoCeilingsForLevel([roomPolygon()], [manualCeiling], { - storeyHeight: 2.7, - }) - - expect(plan.create).toHaveLength(0) - expect(plan.update).toHaveLength(0) - }) - - test('demotes an orphaned auto ceiling to manual with its polygon untouched', () => { - const ceiling = CeilingNode.parse({ - polygon: square, - height: 2.55, - autoFromWalls: true, - }) - - const plan = planAutoCeilingsForLevel([], [ceiling]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - expect(plan.update).toHaveLength(1) - expect(plan.update[0]?.id).toBe(ceiling.id) - // Ceilings render the stored polygon in both modes, so no polygon bake. - expect(plan.update[0]?.data).toEqual({ autoFromWalls: false }) - }) - - test('deletes an unmatched auto ceiling absorbed by a room merge', () => { - const leftCeiling = CeilingNode.parse({ - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - autoFromWalls: true, - }) - const rightCeiling = CeilingNode.parse({ - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoCeilingsForLevel([mergedRoom], [leftCeiling, rightCeiling]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(1) - const survivorId = plan.update[0]?.id - expect([leftCeiling.id, rightCeiling.id]).toContain(plan.delete[0]!) - expect(plan.delete[0]).not.toBe(survivorId) - }) - - test('preserves incompatible merged ceilings as separate manual surfaces', () => { - const leftCeiling = CeilingNode.parse({ - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - height: 2.4, - slots: { surface: 'library:red' }, - autoFromWalls: true, - }) - const rightCeiling = CeilingNode.parse({ - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - slots: { surface: 'library:blue' }, - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoCeilingsForLevel([mergedRoom], [leftCeiling, rightCeiling]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - expect(plan.update).toEqual( - expect.arrayContaining([ - { id: leftCeiling.id, data: { autoFromWalls: false } }, - { id: rightCeiling.id, data: { autoFromWalls: false } }, - ]), - ) - }) - - test('keeps and reparents hosted children when compatible ceilings merge', () => { - const leftCeiling = CeilingNode.parse({ - id: 'ceiling_host_left', - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - children: ['item_left'], - autoFromWalls: true, - }) - const rightCeiling = CeilingNode.parse({ - id: 'ceiling_host_right', - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - children: ['item_right'], - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoCeilingsForLevel([mergedRoom], [leftCeiling, rightCeiling]) - const deletedId = plan.delete[0] - const survivor = [leftCeiling, rightCeiling].find((ceiling) => ceiling.id !== deletedId) - const survivorUpdate = plan.update.find((update) => update.id === survivor?.id) - const deletedChild = deletedId === leftCeiling.id ? 'item_left' : 'item_right' - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(1) - expect(survivorUpdate?.data.children).toEqual( - expect.arrayContaining(['item_left', 'item_right']), - ) - expect(plan.reparent).toEqual([{ id: deletedChild, parentId: survivor?.id }]) - }) - - test('unions openings when compatible ceilings merge', () => { - const leftHole: Array<[number, number]> = [ - [1, 1], - [2, 1], - [2, 2], - [1, 2], - ] - const rightHole: Array<[number, number]> = [ - [6, 1], - [7, 1], - [7, 2], - [6, 2], - ] - const leftCeiling = CeilingNode.parse({ - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - holes: [leftHole], - holeMetadata: [{ source: 'manual' }], - autoFromWalls: true, - }) - const rightCeiling = CeilingNode.parse({ - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - holes: [rightHole], - holeMetadata: [{ source: 'stair', stairId: 'stair_right' }], - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoCeilingsForLevel([mergedRoom], [leftCeiling, rightCeiling]) - const survivor = [leftCeiling, rightCeiling].find( - (ceiling) => ceiling.id === plan.update[0]?.id, - ) - const merged = CeilingNode.parse({ ...survivor, ...plan.update[0]?.data }) - - expect(plan.delete).toHaveLength(1) - expect(merged.holes).toEqual(expect.arrayContaining([leftHole, rightHole])) - expect(merged.holeMetadata).toEqual( - expect.arrayContaining([{ source: 'manual' }, { source: 'stair', stairId: 'stair_right' }]), - ) - }) - - test('a split ceiling inherits customization and assigns each opening to its room', () => { - const leftHole: Array<[number, number]> = [ - [0.5, 0.5], - [1, 0.5], - [1, 1], - [0.5, 1], - ] - const rightHole: Array<[number, number]> = [ - [3, 0.5], - [3.5, 0.5], - [3.5, 1], - [3, 1], - ] - const ceiling = CeilingNode.parse({ - polygon: square, - height: 2.2, - materialPreset: 'custom-ceiling', - slots: { surface: 'library:blue' }, - holes: [leftHole, rightHole], - holeMetadata: [{ source: 'manual' }, { source: 'stair', stairId: 'stair_right' }], - autoFromWalls: true, - }) - const rooms = [ - [ - { x: 0, y: 0 }, - { x: 2, y: 0 }, - { x: 2, y: 3 }, - { x: 0, y: 3 }, - ], - [ - { x: 2, y: 0 }, - { x: 4, y: 0 }, - { x: 4, y: 3 }, - { x: 2, y: 3 }, - ], - ] - - const plan = planAutoCeilingsForLevel(rooms, [ceiling], { storeyHeight: 2.5 }) - const updated = CeilingNode.parse({ ...ceiling, ...plan.update[0]?.data }) - const surfaces = [updated, ...plan.create] - const left = surfaces.find((surface) => surface.polygon.some(([x]) => x === 0)) - const right = surfaces.find((surface) => surface.polygon.some(([x]) => x === 4)) - - expect(plan.create).toHaveLength(1) - expect(plan.update).toHaveLength(1) - expect(surfaces.every((surface) => surface.height === 2.2)).toBe(true) - expect(surfaces.every((surface) => surface.materialPreset === 'custom-ceiling')).toBe(true) - expect(surfaces.every((surface) => surface.slots?.surface === 'library:blue')).toBe(true) - expect(left?.holes).toEqual([leftHole]) - expect(left?.holeMetadata).toEqual([{ source: 'manual' }]) - expect(right?.holes).toEqual([rightHole]) - expect(right?.holeMetadata).toEqual([{ source: 'stair', stairId: 'stair_right' }]) - }) - - test('a split ceiling reparents hosted items to the ceiling that contains them', () => { - const ceiling = CeilingNode.parse({ - id: 'ceiling_with_items', - polygon: square, - children: ['item_left', 'item_right', 'item_on_divider'], - autoFromWalls: true, - }) - const rooms = [ - [ - { x: 0, y: 0 }, - { x: 2, y: 0 }, - { x: 2, y: 3 }, - { x: 0, y: 3 }, - ], - [ - { x: 2, y: 0 }, - { x: 4, y: 0 }, - { x: 4, y: 3 }, - { x: 2, y: 3 }, - ], - ] - const positions: Record = { - item_left: [1, 1], - item_right: [3, 1], - item_on_divider: [2, 1], - } - - const plan = planAutoCeilingsForLevel(rooms, [ceiling], { - childPosition: (id) => positions[id], - }) - const sourceUpdate = plan.update.find((update) => update.id === ceiling.id) - const created = plan.create[0] - - expect(sourceUpdate?.data.children).toEqual(['item_left', 'item_on_divider']) - expect(created?.children).toEqual(['item_right']) - expect(plan.reparent).toEqual([{ id: 'item_right', parentId: created?.id }]) - }) - - test('clips a stair opening across both sides of a ceiling split', () => { - const crossingHole: Array<[number, number]> = [ - [1.5, 1], - [2.5, 1], - [2.5, 2], - [1.5, 2], - ] - const ceiling = CeilingNode.parse({ - polygon: square, - holes: [crossingHole], - holeMetadata: [{ source: 'stair', stairId: 'stair_crossing' }], - autoFromWalls: true, - }) - const rooms = [ - [ - { x: 0, y: 0 }, - { x: 2, y: 0 }, - { x: 2, y: 3 }, - { x: 0, y: 3 }, - ], - [ - { x: 2, y: 0 }, - { x: 4, y: 0 }, - { x: 4, y: 3 }, - { x: 2, y: 3 }, - ], - ] - - const plan = planAutoCeilingsForLevel(rooms, [ceiling]) - const surfaces = [CeilingNode.parse({ ...ceiling, ...plan.update[0]?.data }), ...plan.create] - const holes = surfaces.flatMap((surface) => surface.holes) - - expect(holes).toHaveLength(2) - expect(holes).toEqual( - expect.arrayContaining([ - expect.arrayContaining([ - [1.5, 1], - [2, 1], - [2, 2], - [1.5, 2], - ]), - expect.arrayContaining([ - [2, 1], - [2.5, 1], - [2.5, 2], - [2, 2], - ]), - ]), - ) - expect( - surfaces.every( - (surface) => - surface.holeMetadata.length === 1 && - surface.holeMetadata[0]?.source === 'stair' && - surface.holeMetadata[0]?.stairId === 'stair_crossing', - ), - ).toBe(true) - }) - - test('a demoted ceiling suppresses re-creating an auto ceiling when the room re-forms', () => { - const ceiling = CeilingNode.parse({ - polygon: square, - height: 2.55, - autoFromWalls: true, - }) - - const demotion = planAutoCeilingsForLevel([], [ceiling]).update[0] - const demoted = CeilingNode.parse({ ...ceiling, ...demotion?.data }) - expect(demoted.autoFromWalls).toBe(false) - - // Storey plane above the stored 2.55 so the stage 3-B manual re-clamp - // stays out of this test's scope (suppression only). - const plan = planAutoCeilingsForLevel([roomPolygon()], [demoted], { - storeyHeight: 2.7, - }) - - expect(plan.create).toHaveLength(0) - expect(plan.update).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - }) -}) - -// Two stacked levels; the deck slab (occupying [-0.3, 0] over the upper -// level's plane) covers the queried level below, so the clamp bound is -// 2.5 - 0.3 - 0.01 = 2.19 (scenario gate 11's flush deck). -function stackedDeckNodes(): Record { - const deck = SlabNode.parse({ - id: 'slab_deck', - parentId: 'level_1', - polygon: square, - elevation: 0, - thickness: 0.3, - }) - const list: AnyNode[] = [ - BuildingNode.parse({ id: 'building_a', children: ['level_0', 'level_1'] }), - LevelNode.parse({ id: 'level_0', level: 0, height: 2.5, parentId: 'building_a' }), - LevelNode.parse({ - id: 'level_1', - level: 1, - height: 2.5, - parentId: 'building_a', - children: ['slab_deck'], - }), - deck, - ] - return Object.fromEntries(list.map((node) => [node.id, node])) as Record -} - -describe('stage 3-B ceiling clamp bound', () => { - test('height-less auto ceilings resolve under the covering-slab bound at read time', () => { - const nodes = stackedDeckNodes() - const created = planAutoCeilingsForLevel([roomPolygon()], [], { - storeyHeight: 2.5, - ceilingClampBound: (polygon) => getCeilingClampBound('level_0', nodes, polygon), - }).create[0] - - expect(created).toBeDefined() - expect('height' in created!).toBe(false) - // Follows-mode: the effective height is the deck-limited bound. - expect(resolveCeilingHeight({ ...created!, parentId: 'level_0' }, nodes)).toBeCloseTo(2.19) - }) - - test('clamps a manual ceiling above the bound down to it (plane-only degradation)', () => { - const manual = CeilingNode.parse({ polygon: square, height: 2.6, autoFromWalls: false }) - - const plan = planAutoCeilingsForLevel([roomPolygon()], [manual], { storeyHeight: 2.5 }) - - expect(plan.update).toHaveLength(1) - expect(plan.update[0]?.id).toBe(manual.id) - expect(plan.update[0]?.data.polygon).toBeUndefined() - expect(plan.update[0]?.data.height).toBeCloseTo(2.49) - }) - - test('never raises a manual ceiling sitting below the bound', () => { - const manual = CeilingNode.parse({ polygon: square, height: 2.0, autoFromWalls: false }) - - const plan = planAutoCeilingsForLevel([roomPolygon()], [manual], { storeyHeight: 2.5 }) - - expect(plan.update).toHaveLength(0) - }) - - test('skips follows-mode manual ceilings (never converts them to explicit)', () => { - const nodes = stackedDeckNodes() - const manual = CeilingNode.parse({ polygon: square, autoFromWalls: false }) - - const plan = planAutoCeilingsForLevel([roomPolygon()], [manual], { - storeyHeight: 2.5, - ceilingClampBound: (polygon) => getCeilingClampBound('level_0', nodes, polygon), - }) - - expect(plan.update).toHaveLength(0) - }) - - test('a flush deck above clamps a manual ceiling at the plane margin to its underside', () => { - // Scenario gate 11: manual ceiling at storeyHeight - 0.01 (the no-deck - // bound) → deck occupying [-0.3, 0] above → clamps to 2.5 - 0.3 - 0.01. - const nodes = stackedDeckNodes() - const manual = CeilingNode.parse({ polygon: square, height: 2.49, autoFromWalls: false }) - - const plan = planAutoCeilingsForLevel([roomPolygon()], [manual], { - storeyHeight: 2.5, - ceilingClampBound: (polygon) => getCeilingClampBound('level_0', nodes, polygon), - }) - - expect(plan.create).toHaveLength(0) - expect(plan.update).toHaveLength(1) - expect(plan.update[0]?.id).toBe(manual.id) - expect(plan.update[0]?.data.height).toBeCloseTo(2.19) - }) -}) - // Minimal store stand-ins for initSpaceDetectionSync: a zustand-shaped // scene store (getState/subscribe/temporal) whose write methods mutate the // nodes record and re-notify, and an editor store carrying `spaces`. function createSceneStoreStub(initialNodes: Record) { const listeners = new Set<(state: unknown) => void>() const state: Record & { nodes: Record } = { - nodes: initialNodes, + nodes: migrateCeilingRoomLinks(migrateRoomZones(initialNodes).nodes).nodes as Record< + string, + AnyNode + >, + } + for (const node of Object.values(state.nodes)) { + if (node.type !== 'slab' || node.boundary !== 'auto') continue + state.nodes[node.id] = { + ...node, + zoneIds: Object.values(state.nodes) + .filter( + (zone) => + zone.type === 'zone' && + zone.parentId === node.parentId && + JSON.stringify(zone.polygon) === JSON.stringify(node.polygon), + ) + .map((zone) => zone.id), + } } const notify = () => { for (const listener of [...listeners]) listener(state) @@ -719,7 +186,11 @@ function createSceneStoreStub(initialNodes: Record) { const next: Record = { ...state.nodes } for (const { id, data } of updates) { const existing = next[id] - if (existing) next[id] = { ...existing, ...data } as AnyNode + if (existing) { + next[id] = { ...existing, ...data } as AnyNode + for (const key of Object.keys(data)) + if (data[key] === undefined) delete (next[id] as unknown as Record)[key] + } } state.nodes = next notify() @@ -880,6 +351,7 @@ describe('live room topology reconciliation', () => { polygon: square, elevation: 0.05, autoFromWalls: true, + boundary: 'auto', }) const autoCeiling = CeilingNode.parse({ id: 'ceiling_custom_split', @@ -887,6 +359,7 @@ describe('live room topology reconciliation', () => { polygon: square, height: 2.49, autoFromWalls: true, + boundary: 'auto', }) const level = LevelNode.parse({ id: 'level_custom_split', @@ -905,8 +378,10 @@ describe('live room topology reconciliation', () => { }) try { + const room = Object.values(sceneStore.getState().nodes).find((node) => node.type === 'zone')! sceneStore.setNodes({ ...sceneStore.getState().nodes, + [room.id]: { ...room, floor: { elevation: 0.42 } } as AnyNode, [autoSlab.id]: { ...autoSlab, elevation: 0.42, @@ -955,22 +430,24 @@ describe('live room topology reconciliation', () => { ) expect(Object.values(editorStore.getState().spaces)).toHaveLength(2) - expect(slabs).toHaveLength(2) + expect(slabs).toHaveLength(3) expect(ceilings).toHaveLength(2) expect( slabs.every( (slab) => - slab.elevation === 0.42 && - slab.thickness === 0.18 && + slab.elevation === (slab.plateRole === 'base' ? 0.05 : 0.42) && + Math.abs(slab.thickness - (slab.plateRole === 'base' ? 0.18 : 0.37)) < 1e-6 && slab.materialPreset === 'custom-floor' && - slab.slots?.surface === 'library:oak' && + (slab.plateRole !== 'base' || slab.slots?.surface === 'library:oak') && slab.visible === false, ), ).toBe(true) expect( ceilings.every( (ceiling) => - ceiling.height === 2.1 && + (ceiling.id === autoCeiling.id + ? ceiling.height === 2.1 + : ceiling.height === undefined) && ceiling.materialPreset === 'custom-ceiling' && ceiling.slots?.surface === 'library:blue' && ceiling.visible === false, @@ -997,17 +474,16 @@ describe('live room topology reconciliation', () => { (node): node is CeilingNode => node.type === 'ceiling' && node.autoFromWalls, ) expect(Object.values(editorStore.getState().spaces)).toHaveLength(1) - expect(mergedSlabs).toHaveLength(1) + expect(mergedSlabs).toHaveLength(2) expect(mergedCeilings).toHaveLength(1) - expect(mergedSlabs[0]).toMatchObject({ + expect(mergedSlabs.find((slab) => slab.plateRole === 'platform')).toMatchObject({ elevation: 0.42, - thickness: 0.18, + thickness: 0.37, materialPreset: 'custom-floor', - slots: { surface: 'library:oak' }, visible: false, }) + expect(mergedSlabs.find((slab) => slab.plateRole === 'platform')!.slots).toBeUndefined() expect(mergedCeilings[0]).toMatchObject({ - height: 2.1, materialPreset: 'custom-ceiling', slots: { surface: 'library:blue' }, visible: false, @@ -1029,7 +505,7 @@ describe('live room topology reconciliation', () => { expect(Object.values(editorStore.getState().spaces)).toHaveLength(2) expect( resplitNodes.filter((node) => node.type === 'slab' && node.autoFromWalls), - ).toHaveLength(2) + ).toHaveLength(3) expect( resplitNodes.filter((node) => node.type === 'ceiling' && node.autoFromWalls), ).toHaveLength(2) @@ -1071,12 +547,14 @@ describe('live room topology reconciliation', () => { parentId: levelId, polygon: leftPolygon, autoFromWalls: true, + boundary: 'auto', }), SlabNode.parse({ id: 'slab_b', parentId: levelId, polygon: rightPolygon, autoFromWalls: true, + boundary: 'auto', }), CeilingNode.parse({ id: 'ceiling_a', @@ -1130,7 +608,7 @@ describe('live room topology reconciliation', () => { const nodes = Object.values(indexedStore.getState().nodes) expect(Object.values(indexedEditor.getState().spaces)).toHaveLength(3) - expect(nodes.filter((node) => node.type === 'slab' && node.autoFromWalls)).toHaveLength(3) + expect(nodes.filter((node) => node.type === 'slab' && node.autoFromWalls)).toHaveLength(1) expect(nodes.filter((node) => node.type === 'ceiling' && node.autoFromWalls)).toHaveLength(3) expect( topologyOutcome(indexedStore.getState().nodes, indexedEditor.getState().spaces), @@ -1175,6 +653,7 @@ describe('live room topology reconciliation', () => { thickness: 0.12, slots: { surface: 'library:wood-floorplank1' }, autoFromWalls: true, + boundary: 'auto', }) const autoCeiling = CeilingNode.parse({ id: 'ceiling_compound', @@ -1183,6 +662,7 @@ describe('live room topology reconciliation', () => { height: 2.55, slots: { surface: 'library:concrete-polished' }, autoFromWalls: true, + boundary: 'auto', }) const level = LevelNode.parse({ id: levelId, @@ -1283,7 +763,7 @@ describe('live room topology reconciliation', () => { const reconciled = Object.values(sceneStore.getState().nodes) expect(Object.values(editorStore.getState().spaces)).toHaveLength(4) expect(reconciled.filter((node) => node.type === 'slab' && node.autoFromWalls)).toHaveLength( - 4, + 1, ) expect( reconciled.filter((node) => node.type === 'ceiling' && node.autoFromWalls), @@ -1383,6 +863,7 @@ describe('live room topology reconciliation', () => { thickness: 0.18, slots: { surface: 'library:wood-floorplank1' }, autoFromWalls: true, + boundary: 'auto', }) const leftCeiling = CeilingNode.parse({ id: 'ceiling_sequence_left', @@ -1399,6 +880,7 @@ describe('live room topology reconciliation', () => { polygon: rightPolygon, elevation: 0.1, autoFromWalls: true, + boundary: 'auto', }) const rightCeiling = CeilingNode.parse({ id: 'ceiling_sequence_right', @@ -1515,6 +997,7 @@ describe('live room topology reconciliation', () => { polygon: initialRoom!.polygon, elevation: 0.3, autoFromWalls: true, + boundary: 'auto', }) const ceiling = CeilingNode.parse({ id: 'ceiling_curve', @@ -1522,6 +1005,7 @@ describe('live room topology reconciliation', () => { polygon: initialRoom!.polygon, height: 2.2, autoFromWalls: true, + boundary: 'auto', }) const level = LevelNode.parse({ id: levelId, @@ -1666,6 +1150,7 @@ describe('live room topology reconciliation', () => { parentId: 'level_restore', polygon: square, autoFromWalls: true, + boundary: 'auto', }) const level = LevelNode.parse({ id: 'level_restore', @@ -1700,8 +1185,8 @@ describe('live room topology reconciliation', () => { }) }) -describe('reactive ceiling re-clamp through the detection sync', () => { - test('a flush deck created on the level above clamps the existing manual ceiling below', () => { +describe('manual ceilings through the detection sync', () => { + test('a flush deck clamps explicit manual ceiling height downward', () => { const walls = [ WallNode.parse({ start: [0, 0], end: [4, 0], parentId: 'level_0' }), WallNode.parse({ start: [4, 0], end: [4, 3], parentId: 'level_0' }), @@ -1755,7 +1240,7 @@ describe('reactive ceiling re-clamp through the detection sync', () => { }) const ceiling = sceneStore.getState().nodes.ceiling_main as CeilingNode - expect(ceiling.height).toBeCloseTo(2.5 - 0.3 - 0.01) + expect(ceiling.height).toBeCloseTo(2.19) } finally { unsubscribe() } @@ -1763,7 +1248,7 @@ describe('reactive ceiling re-clamp through the detection sync', () => { }) describe('raised auto-room surfaces', () => { - test('inherits the enclosing walls construction plane when the room closes', () => { + test('follows boundary wall bases when the room has no floor elevation intent', () => { const wallData = [ { id: 'wall_bottom', start: [0, 0], end: [4, 0] }, { id: 'wall_right', start: [4, 0], end: [4, 3] }, @@ -1822,7 +1307,7 @@ describe('raised auto-room surfaces', () => { expect(autoSlab?.elevation).toBeCloseTo(0.65) expect(autoSlab?.thickness).toBeCloseTo(0.05) - expect(autoCeiling?.height).toBeCloseTo(3.09) + expect(autoCeiling?.height).toBeUndefined() const raisedAgain = { ...sceneStore.getState().nodes } for (const wall of walls) { @@ -1841,7 +1326,7 @@ describe('raised auto-room surfaces', () => { (node): node is CeilingNode => node.type === 'ceiling' && node.autoFromWalls, ) expect(reconciledSlab?.elevation).toBeCloseTo(0.85) - expect(reconciledCeiling?.height).toBeCloseTo(3.29) + expect(reconciledCeiling?.height).toBeUndefined() } finally { unsubscribe() } @@ -1864,6 +1349,8 @@ describe('generated surface deletion memory', () => { [level, ...walls].map((node) => [node.id, node]), ) as Record const sceneStore = createSceneStoreStub(initialNodes) + for (const node of Object.values(sceneStore.getState().nodes)) + if (node.type === 'zone') sceneStore.getState().nodes[node.id] = { ...node, hasFloor: false } const editorStore = createEditorStoreStub() const unsubscribe = initSpaceDetectionSync(sceneStore, editorStore) @@ -1882,7 +1369,7 @@ describe('generated surface deletion memory', () => { expect( Object.values(sceneStore.getState().nodes).filter( - (node) => (node.type === 'slab' || node.type === 'ceiling') && node.autoFromWalls, + (node) => node.type === 'slab' && node.autoFromWalls && !!node.zoneIds?.length, ), ).toHaveLength(0) expect(Object.values(editorStore.getState().spaces)).toHaveLength(1) @@ -1902,12 +1389,14 @@ describe('generated surface deletion memory', () => { parentId: 'level_delete_memory', polygon: square, autoFromWalls: true, + boundary: 'auto', }) const autoCeiling = CeilingNode.parse({ id: 'ceiling_delete_memory', parentId: 'level_delete_memory', polygon: square, autoFromWalls: true, + boundary: 'auto', }) const level = LevelNode.parse({ id: 'level_delete_memory', @@ -1932,7 +1421,9 @@ describe('generated surface deletion memory', () => { const afterDelete = sceneStore.getState().nodes expect( - Object.values(afterDelete).filter((node) => node.type === 'slab' && node.autoFromWalls), + Object.values(afterDelete).filter( + (node) => node.type === 'slab' && node.autoFromWalls && !!node.zoneIds?.length, + ), ).toHaveLength(0) sceneStore.setNodes({ @@ -1948,11 +1439,14 @@ describe('generated surface deletion memory', () => { const afterReshape = Object.values(sceneStore.getState().nodes) expect( - afterReshape.filter((node) => node.type === 'slab' && node.autoFromWalls), + afterReshape.filter( + (node) => node.type === 'slab' && node.autoFromWalls && !!node.zoneIds?.length, + ), ).toHaveLength(0) const ceiling = afterReshape.find( (node): node is CeilingNode => node.type === 'ceiling' && node.autoFromWalls, ) + // Explicit-height walls may not reach the ceiling, so it spans them to the reference line. expect(ceiling?.polygon).toContainEqual([5, 0]) expect(ceiling?.polygon).toContainEqual([5, 3]) } finally { @@ -1960,7 +1454,7 @@ describe('generated surface deletion memory', () => { } }) - test('a deleted generated ceiling stays absent while the slab follows a later room reshape', () => { + test('deleting a generated ceiling records a persistent zone opt-out', () => { const walls = squareWalls().map((wall, index) => ({ ...wall, id: `wall_ceiling_memory_${index}`, @@ -1971,12 +1465,14 @@ describe('generated surface deletion memory', () => { parentId: 'level_ceiling_memory', polygon: square, autoFromWalls: true, + boundary: 'auto', }) const autoCeiling = CeilingNode.parse({ id: 'ceiling_ceiling_memory', parentId: 'level_ceiling_memory', polygon: square, autoFromWalls: true, + boundary: 'auto', }) const level = LevelNode.parse({ id: 'level_ceiling_memory', @@ -2019,11 +1515,12 @@ describe('generated surface deletion memory', () => { expect( afterReshape.filter((node) => node.type === 'ceiling' && node.autoFromWalls), ).toHaveLength(0) + expect(afterReshape.find((node) => node.type === 'zone')).toMatchObject({ hasCeiling: false }) const slab = afterReshape.find( (node): node is SlabNode => node.type === 'slab' && node.autoFromWalls, ) - expect(slab?.polygon).toContainEqual([5, 0]) - expect(slab?.polygon).toContainEqual([5, 3]) + expect(Math.max(...slab!.polygon.map(([x]) => x))).toBeCloseTo(5.05) + expect(slab?.polygon).toContainEqual([5.05, 3.05]) } finally { unsubscribe() } @@ -2159,7 +1656,7 @@ function autoSurfacesOf(sceneStore: ReturnType) { } describe('auto-room surfaces over terrain', () => { - test('a room on a slope takes its floor from the HIGHEST wall base', () => { + test('a room on a slope follows the highest boundary wall base', () => { // Walls on bare terrain: no `supportSlabId`, no `supportOffset` — exactly // what a stamped room preset or a 3D draw over untouched ground produces. // Bases run 0 → 1 across the ramp, so a floor at the lowest base would @@ -2178,7 +1675,7 @@ describe('auto-room surfaces over terrain', () => { // Lowest wall top = the LOWEST base + 2.5 (explicit-height walls ride // their own base), −the 1 cm clamp margin. Bottom/left walls start at // x = 0, i.e. ground 0. - expect(ceiling?.height).toBeCloseTo(2.49) + expect(ceiling?.height).toBeUndefined() } finally { unsubscribe() } @@ -2193,13 +1690,13 @@ describe('auto-room surfaces over terrain', () => { closeRoom(sceneStore, closingWall) const { slab, ceiling } = autoSurfacesOf(sceneStore) expect(slab?.elevation).toBeCloseTo(0.05) - expect(ceiling?.height).toBeCloseTo(2.49) + expect(ceiling?.height).toBeUndefined() } finally { unsubscribe() } }) - test('sculpting under an existing room re-derives its floor and ceiling', () => { + test('sculpting under an existing room re-derives an unauthored floor', () => { // The trigger half of the bug: a sculpt writes only `site.terrain`, so // without a terrain term in the structure signature every level hashes // identically and the sync early-exits. @@ -2229,7 +1726,7 @@ describe('auto-room surfaces over terrain', () => { const { slab, ceiling } = autoSurfacesOf(sceneStore) expect(slab?.elevation).toBeCloseTo(2.05) - expect(ceiling?.height).toBeCloseTo(4.49) + expect(ceiling?.height).toBeUndefined() } finally { unsubscribe() } @@ -2340,102 +1837,202 @@ describe('detectSpacesForLevel', () => { expect(roomPolygons).toHaveLength(2) expect(roomPolygons.map(areaOf).sort((a, b) => a - b)).toEqual([12, 12]) }) -}) -describe('procedural zones', () => { - test('adopts an exact room footprint and records its enclosing walls', () => { - const walls = squareWalls() - const { spaces } = detectSpacesForLevel('level-1', walls) - const zone = ZoneNode.parse({ name: 'Kitchen', polygon: square }) - - const plan = planAutoZonesForLevel(spaces, [zone]) - - expect(plan.update).toHaveLength(1) - expect(plan.update[0]?.data.autoFromWalls).toBe(true) - expect(new Set(plan.update[0]?.data.boundaryWallIds)).toEqual( - new Set(walls.map((wall) => wall.id)), - ) + // Prod "Wawa House": walls drawn a few centimetres short of their corner read as + // joined (their bodies overlap) but left Living Room and Master Bedroom undetected. + test('joins a corner whose wall ends stop a few centimetres apart', () => { + const walls = [ + WallNode.parse({ start: [0, 0], end: [4, 0] }), + WallNode.parse({ start: [4.0091, 0.0012], end: [4, 3] }), + WallNode.parse({ start: [4, 3], end: [0, 3] }), + WallNode.parse({ start: [0, 3], end: [0, 0.0384] }), + ] + const { roomPolygons, spaces } = detectSpacesForLevel('level-1', walls) + expect(roomPolygons).toHaveLength(1) + expect(areaOf(roomPolygons[0]!)).toBeCloseTo(12, 1) + expect(new Set(spaces[0]?.wallIds)).toEqual(new Set(walls.map((wall) => wall.id))) }) - test('derives the live polygon from effective wall endpoints', () => { - const walls = squareWalls() - const zone = ZoneNode.parse({ - name: 'Kitchen', - polygon: square, - autoFromWalls: true, - boundaryWallIds: walls.map((wall) => wall.id), - }) - const movedWalls = [ - { ...walls[0]!, end: [5, 0] as [number, number] }, - { ...walls[1]!, start: [5, 0] as [number, number], end: [5, 3] as [number, number] }, - { ...walls[2]!, start: [5, 3] as [number, number] }, - walls[3]!, + test('joins a wall end that lands on another wall close to its end', () => { + // The right wall stops 1 mm off the top wall, 3 cm from the top wall's end. + const walls = [ + WallNode.parse({ start: [0, 0], end: [4, 0] }), + WallNode.parse({ start: [4, 0], end: [4, 2.999] }), + WallNode.parse({ start: [4.03, 3], end: [0, 3] }), + WallNode.parse({ start: [0, 3], end: [0, 0] }), ] - const byId = new Map(movedWalls.map((wall) => [wall.id, wall])) - - const polygon = resolveAutoZonePolygon(zone, (id) => - byId.get(id as (typeof walls)[number]['id']), - ) - const plan = planAutoZonesForLevel(detectSpacesForLevel('level-1', movedWalls).spaces, [zone]) - - expect(polygon).toContainEqual([5, 0]) - expect(polygon).toContainEqual([5, 3]) - expect(polygon).not.toContainEqual([4, 0]) - expect(plan.update[0]?.data.polygon).toContainEqual([5, 0]) + const { roomPolygons } = detectSpacesForLevel('level-1', walls) + expect(roomPolygons).toHaveLength(1) + expect(areaOf(roomPolygons[0]!)).toBeCloseTo(12, 1) }) - test('follows its room when a wall move bridges a junction into its boundary', () => { - const walls = squareWalls() - const zone = ZoneNode.parse({ - name: 'Kitchen', - polygon: square, - autoFromWalls: true, - boundaryWallIds: walls.map((wall) => wall.id), - }) - // The east wall moved out to x = 5; a new bridge wall closes the corner it left. - const bridge = WallNode.parse({ start: [4, 0], end: [5, 0] }) - const movedWalls = [ - walls[0]!, - { ...walls[1]!, start: [5, 0] as [number, number], end: [5, 3] as [number, number] }, - { ...walls[2]!, start: [5, 3] as [number, number] }, - walls[3]!, - bridge, + test('keeps a short jog wall and distinct junctions beyond the tolerance', () => { + // A 5 cm jog joins two walls; both of its ends are real junctions. + const walls = [ + WallNode.parse({ start: [0, 0], end: [2, 0] }), + WallNode.parse({ start: [2, 0], end: [2, 0.05] }), + WallNode.parse({ start: [2, 0.05], end: [4, 0.05] }), + WallNode.parse({ start: [4, 0.05], end: [4, 3] }), + WallNode.parse({ start: [4, 3], end: [0, 3] }), + WallNode.parse({ start: [0, 3], end: [0, 0] }), + ] + const { spaces } = detectSpacesForLevel('level-1', walls) + expect(spaces).toHaveLength(1) + expect(new Set(spaces[0]?.wallIds)).toEqual(new Set(walls.map((wall) => wall.id))) + // A 10 cm gap stays open. + const open = [ + WallNode.parse({ start: [0, 0], end: [4, 0] }), + WallNode.parse({ start: [4, 0.1], end: [4, 3] }), + WallNode.parse({ start: [4, 3], end: [0, 3] }), + WallNode.parse({ start: [0, 3], end: [0, 0] }), ] - const plan = planAutoZonesForLevel(detectSpacesForLevel('level-1', movedWalls).spaces, [zone]) + expect(detectSpacesForLevel('level-1', open).roomPolygons).toHaveLength(0) + }) +}) - expect(plan.update).toHaveLength(1) - expect(plan.update[0]?.data.polygon).toContainEqual([5, 0]) - expect(plan.update[0]?.data.boundaryWallIds).toContain(bridge.id) +describe('near-miss joints follow the drawn wall bodies', () => { + const rectangleWith = (gapWall: WallNode) => [ + WallNode.parse({ start: [0, 0], end: [4, 0], thickness: gapWall.thickness }), + WallNode.parse({ start: [4, 0], end: [4, 3], thickness: gapWall.thickness }), + WallNode.parse({ start: [4, 3], end: [0, 3], thickness: gapWall.thickness }), + gapWall, + ] + test.each([ + ['a 5 cm gap between 1 cm walls', 0.01, 0.05], + ['a 5 cm gap between 10 cm walls', 0.1, 0.05], + ['an 80 cm doorway', 0.1, 0.8], + ])('%s along one side stays open', (_label, thickness, gap) => { + const walls = [ + WallNode.parse({ start: [0, 0], end: [2, 0], thickness }), + WallNode.parse({ start: [2 + gap, 0], end: [4, 0], thickness }), + WallNode.parse({ start: [4, 0], end: [4, 3], thickness }), + WallNode.parse({ start: [4, 3], end: [0, 3], thickness }), + WallNode.parse({ start: [0, 3], end: [0, 0], thickness }), + ] + expect(detectSpacesForLevel('level-1', walls).roomPolygons).toHaveLength(0) + // A 5 mm hairline between 10 cm walls reads as one wall. + if (thickness === 0.1 && gap < 0.1) { + const hairline = walls.map((wall, i) => + i === 1 ? { ...wall, start: [2.005, 0] as [number, number] } : wall, + ) + expect(detectSpacesForLevel('level-1', hairline).roomPolygons).toHaveLength(1) + } + }) + test('a corner a few centimetres short closes when the bodies overlap', () => { + const walls = rectangleWith(WallNode.parse({ start: [0, 3], end: [0, 0.04], thickness: 0.1 })) + expect(detectSpacesForLevel('level-1', walls).roomPolygons).toHaveLength(1) + const thin = rectangleWith(WallNode.parse({ start: [0, 3], end: [0, 0.04], thickness: 0.01 })) + expect(detectSpacesForLevel('level-1', thin).roomPolygons).toHaveLength(0) + }) + test('stays near-linear on 2,000 isolated walls', () => { + const walls = Array.from({ length: 2000 }, (_, i) => + WallNode.parse({ + start: [(i % 50) * 3, Math.floor(i / 50) * 3], + end: [(i % 50) * 3 + 2, Math.floor(i / 50) * 3 + 1], + }), + ) + const started = performance.now() + expect(extractRooms(walls)).toHaveLength(0) + // HEAD took ~75 ms; the unbounded scan took 7.8 s. + expect(performance.now() - started).toBeLessThan(1500) }) +}) - test('keeps a stored ring that only starts at another vertex', () => { - const walls = squareWalls() - const { spaces } = detectSpacesForLevel('level-1', walls) - const detected = spaces[0]!.polygon - const rotated = [...detected.slice(1), detected[0]!] - const zone = ZoneNode.parse({ - name: 'Kitchen', - polygon: rotated, - autoFromWalls: true, - boundaryWallIds: walls.map((wall) => wall.id), - }) +describe('wall ends that stand inside another wall body', () => { + // A 4 × 3 room whose right wall stops inside a 30 cm wall, 10 cm off its line. + const room = (thickness: number, end: [number, number] = [4, 2.9]) => [ + WallNode.parse({ id: 'wall_a', start: [0, 0], end: [4, 0], thickness: 0.1 }), + WallNode.parse({ id: 'wall_b', start: [4, 0], end, thickness: 0.1 }), + WallNode.parse({ id: 'wall_c', start: [5, 3], end: [-1, 3], thickness }), + WallNode.parse({ id: 'wall_d', start: [0, 3], end: [0, 0], thickness: 0.1 }), + ] - expect(planAutoZonesForLevel(spaces, [zone]).update).toHaveLength(0) + test('prod "Structure test 06": the right half closes where its wall stops inside a thick wall', () => { + const walls = ( + JSON.parse( + readFileSync( + new URL('./__fixtures__/structure-test-06-walls.json', import.meta.url), + 'utf8', + ), + ) as Partial[] + ).map((wall) => WallNode.parse({ ...wall, parentId: 'level-1' })) + const areas = detectSpacesForLevel('level-1', walls) + .spaces.map((space) => area([{ outer: space.polygon, holes: space.holes }])) + .sort((a, b) => b - a) + expect(areas).toHaveLength(2) + expect(areas[0]).toBeGreaterThan(50) + }) + + test('joins at the foot of the thick wall’s line; a thin wall there leaves the gap open', () => { + const { spaces } = detectSpacesForLevel('level-1', room(0.3)) + expect(spaces).toHaveLength(1) + expect(area([{ outer: spaces[0]!.polygon, holes: [] }])).toBeCloseTo(12, 1) + // A 10 cm wall's body ends 5 cm short of the end: a visible gap. + expect(detectSpacesForLevel('level-1', room(0.1)).spaces).toHaveLength(0) + // Metre-thick "walls" are blocks, not joints. + expect(detectSpacesForLevel('level-1', room(1.2, [4, 2.6])).spaces).toHaveLength(0) + }) + + test('a thick corner a few centimetres further than the junction tolerance closes', () => { + const walls = [ + WallNode.parse({ start: [0, 0], end: [4, 0], thickness: 0.3 }), + WallNode.parse({ start: [4, 0], end: [4, 3], thickness: 0.3 }), + WallNode.parse({ start: [4, 3], end: [0.092, 3], thickness: 0.3 }), + WallNode.parse({ start: [0, 3], end: [0, 0], thickness: 0.3 }), + ] + expect(detectSpacesForLevel('level-1', walls).spaces).toHaveLength(1) }) - test('leaves an unrelated site zone manual', () => { - const { spaces } = detectSpacesForLevel('level-1', squareWalls()) - const zone = ZoneNode.parse({ - name: 'Lawn', - polygon: [ - [10, 10], - [12, 10], - [12, 12], - [10, 12], - ], - }) + test('a stub inside a body, an overshoot past a corner and nearly aligned ends change nothing', () => { + const square = [ + WallNode.parse({ id: 'wall_1', start: [0, 0], end: [4, 0], thickness: 0.3 }), + WallNode.parse({ id: 'wall_2', start: [4, 0], end: [4, 3], thickness: 0.3 }), + WallNode.parse({ id: 'wall_3', start: [4, 3], end: [0, 3], thickness: 0.3 }), + WallNode.parse({ id: 'wall_4', start: [0, 3], end: [0, 0], thickness: 0.3 }), + ] + const areaOf = (walls: WallNode[]) => + detectSpacesForLevel('level-1', walls).spaces.map((space) => + area([{ outer: space.polygon, holes: space.holes }]), + ) + expect(areaOf(square)).toEqual([12]) + // A corner filler drawn entirely inside the bodies. + const stub = WallNode.parse({ id: 'wall_5', start: [4, 0], end: [4.08, 0.12], thickness: 0.3 }) + expect(areaOf([...square, stub])).toEqual([12]) + // A thin wall running 10 cm past the corner it already crosses. + const overshoot = [ + WallNode.parse({ id: 'wall_1', start: [0, 0], end: [4, 0] }), + WallNode.parse({ id: 'wall_2', start: [4, -0.01], end: [4, 3] }), + WallNode.parse({ id: 'wall_3', start: [4.1, 3], end: [0, 3] }), + WallNode.parse({ id: 'wall_4', start: [0, 3], end: [0, 0] }), + WallNode.parse({ id: 'wall_6', start: [4, 3], end: [4, 5] }), + ] + expect(areaOf(overshoot).map((value) => Math.round(value))).toEqual([12]) + }) +}) - expect(planAutoZonesForLevel(spaces, [zone]).update).toHaveLength(0) +describe('joints never cost a room the plain rules found', () => { + const load = (file: string) => + ( + JSON.parse( + readFileSync(new URL(`./__fixtures__/${file}`, import.meta.url), 'utf8'), + ) as Partial[] + ).map((wall) => WallNode.parse({ ...wall, parentId: 'level-1' })) + const areas = (walls: WallNode[]) => + extractRooms(walls) + .map((room) => area([{ outer: room.referencePolygon, holes: room.holes }])) + .sort((a, b) => b - a) + + test('a room walled by a span drawn twice survives a joint elsewhere on it', () => { + // Wall vcums lies exactly on part of lv02j; joining 9q8u1 at the room's corner used to + // make the face walk cross the doubled span and lose the 618 m² room. + expect(areas(load('stacked-walls-doubled-span.json'))[0]).toBeCloseTo(618.52, 1) + }) + + test('a joint that would merge two rooms keeps them apart', () => { + const rooms = areas(load('joint-merge-rooms.json')) + expect(rooms).toHaveLength(20) + expect(rooms).toContainEqual(expect.closeTo(15.38, 1)) + expect(rooms).toContainEqual(expect.closeTo(4.78, 1)) }) }) @@ -2469,437 +2066,3 @@ describe('wallClosesRoom', () => { expect(wallClosesRoom([...bigRoom, bayLeft, bayBottom, bayRight], bayRight)).toBe(true) }) }) - -describe('planAutoSlabsForLevel', () => { - test('creates and reconciles an auto slab on the enclosing wall plane', () => { - const context = { - elevationForRoom: () => 0.65, - } - const created = planAutoSlabsForLevel([roomPolygon()], [], context).create[0] - - expect(created?.elevation).toBeCloseTo(0.65) - - const existing = slab(0.05) - const update = planAutoSlabsForLevel([roomPolygon()], [existing], context).update[0] - - expect(update?.id).toBe(existing.id) - expect(update?.data.elevation).toBeCloseTo(0.65) - }) - - test('matches two identical rooms to their own existing auto-slabs without churn', () => { - // Two rooms with identical polygon signatures previously collided in a - // signature-keyed Map, so one detected room never matched an existing slab - // and churned (delete + recreate) on every pass. - const slabA = slab(0.05) - const slabB = slab(0.05) - - const plan = planAutoSlabsForLevel([roomPolygon(), roomPolygon()], [slabA, slabB]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - expect(plan.update).toHaveLength(0) - }) - - test('deletes an extra auto-slab when only one identical room is detected', () => { - const plan = planAutoSlabsForLevel([roomPolygon()], [slab(0.05), slab(0.05)]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(1) - }) - - test('demotes an orphaned auto slab to manual when its room disappears', () => { - const painted = SlabNode.parse({ - polygon: square, - elevation: 0.4, - autoFromWalls: true, - }) - - const plan = planAutoSlabsForLevel([], [painted]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - expect(plan.update).toHaveLength(1) - - const update = plan.update[0] - expect(update?.id).toBe(painted.id) - // Demotion flips only the flag — the stored polygon stays untouched - // (render offsets derive from level context at geometry build time). - expect(update?.data).toEqual({ autoFromWalls: false }) - }) - - test('deletes an unmatched auto slab whose area was absorbed by a room merge', () => { - const leftSlab = SlabNode.parse({ - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - autoFromWalls: true, - }) - const rightSlab = SlabNode.parse({ - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoSlabsForLevel([mergedRoom], [leftSlab, rightSlab]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(1) - expect(plan.update).toHaveLength(1) - const survivorId = plan.update[0]?.id - expect([leftSlab.id, rightSlab.id]).toContain(plan.delete[0]!) - expect(plan.delete[0]).not.toBe(survivorId) - // The survivor stays auto — updated to the merged polygon, not demoted. - expect(plan.update[0]?.data.autoFromWalls).toBeUndefined() - }) - - test('preserves incompatible merged slabs as separate manual surfaces', () => { - const leftSlab = SlabNode.parse({ - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - elevation: 0.15, - thickness: 0.15, - slots: { surface: 'library:red' }, - autoFromWalls: true, - }) - const rightSlab = SlabNode.parse({ - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - elevation: -0.15, - thickness: 0.1, - slots: { surface: 'library:blue' }, - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoSlabsForLevel([mergedRoom], [leftSlab, rightSlab]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - expect(plan.update).toEqual( - expect.arrayContaining([ - { id: leftSlab.id, data: { autoFromWalls: false } }, - { id: rightSlab.id, data: { autoFromWalls: false } }, - ]), - ) - }) - - test('unions openings when compatible slabs merge', () => { - const leftHole: Array<[number, number]> = [ - [1, 1], - [2, 1], - [2, 2], - [1, 2], - ] - const rightHole: Array<[number, number]> = [ - [6, 1], - [7, 1], - [7, 2], - [6, 2], - ] - const leftSlab = SlabNode.parse({ - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - holes: [leftHole], - holeMetadata: [{ source: 'manual' }], - autoFromWalls: true, - }) - const rightSlab = SlabNode.parse({ - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - holes: [rightHole], - holeMetadata: [{ source: 'elevator', elevatorId: 'elevator_right' }], - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoSlabsForLevel([mergedRoom], [leftSlab, rightSlab]) - const survivor = [leftSlab, rightSlab].find((slab) => slab.id === plan.update[0]?.id) - const merged = SlabNode.parse({ ...survivor, ...plan.update[0]?.data }) - - expect(plan.delete).toHaveLength(1) - expect(merged.holes).toEqual(expect.arrayContaining([leftHole, rightHole])) - expect(merged.holeMetadata).toEqual( - expect.arrayContaining([ - { source: 'manual' }, - { source: 'elevator', elevatorId: 'elevator_right' }, - ]), - ) - }) - - test('a split slab inherits customization and assigns each opening to its room', () => { - const leftHole: Array<[number, number]> = [ - [0.5, 0.5], - [1, 0.5], - [1, 1], - [0.5, 1], - ] - const rightHole: Array<[number, number]> = [ - [3, 0.5], - [3.5, 0.5], - [3.5, 1], - [3, 1], - ] - const customized = SlabNode.parse({ - polygon: square, - elevation: 0.2, - thickness: 0.1, - fillToTerrain: true, - materialPreset: 'custom-floor', - slots: { surface: 'library:oak' }, - holes: [leftHole, rightHole], - holeMetadata: [{ source: 'manual' }, { source: 'stair', stairId: 'stair_right' }], - autoFromWalls: true, - }) - const rooms = [ - [ - { x: 0, y: 0 }, - { x: 2, y: 0 }, - { x: 2, y: 3 }, - { x: 0, y: 3 }, - ], - [ - { x: 2, y: 0 }, - { x: 4, y: 0 }, - { x: 4, y: 3 }, - { x: 2, y: 3 }, - ], - ] - - const plan = planAutoSlabsForLevel(rooms, [customized]) - const updated = SlabNode.parse({ ...customized, ...plan.update[0]?.data }) - const surfaces = [updated, ...plan.create] - const left = surfaces.find((surface) => surface.polygon.some(([x]) => x === 0)) - const right = surfaces.find((surface) => surface.polygon.some(([x]) => x === 4)) - - expect(plan.create).toHaveLength(1) - expect(plan.update).toHaveLength(1) - expect(surfaces.every((surface) => surface.elevation === 0.2)).toBe(true) - expect(surfaces.every((surface) => surface.thickness === 0.1)).toBe(true) - expect(surfaces.every((surface) => surface.fillToTerrain === true)).toBe(true) - expect(surfaces.every((surface) => surface.materialPreset === 'custom-floor')).toBe(true) - expect(surfaces.every((surface) => surface.slots?.surface === 'library:oak')).toBe(true) - expect(left?.holes).toEqual([leftHole]) - expect(left?.holeMetadata).toEqual([{ source: 'manual' }]) - expect(right?.holes).toEqual([rightHole]) - expect(right?.holeMetadata).toEqual([{ source: 'stair', stairId: 'stair_right' }]) - }) - - test('a split recessed slab preserves its rim elevation', () => { - const recessed = SlabNode.parse({ - polygon: square, - elevation: -0.2, - thickness: 0.25, - recessed: true, - recessedRimElevation: 0.15, - autoFromWalls: true, - }) - const rooms = [ - [ - { x: 0, y: 0 }, - { x: 2, y: 0 }, - { x: 2, y: 3 }, - { x: 0, y: 3 }, - ], - [ - { x: 2, y: 0 }, - { x: 4, y: 0 }, - { x: 4, y: 3 }, - { x: 2, y: 3 }, - ], - ] - - const plan = planAutoSlabsForLevel(rooms, [recessed]) - const surfaces = [SlabNode.parse({ ...recessed, ...plan.update[0]?.data }), ...plan.create] - - expect(surfaces).toHaveLength(2) - expect( - surfaces.every( - (surface) => - surface.elevation === -0.2 && - surface.thickness === 0.25 && - surface.recessed === true && - surface.recessedRimElevation === 0.15, - ), - ).toBe(true) - }) - - test('preserves slabs with conflicting terrain-fill settings instead of merging them', () => { - const leftSlab = SlabNode.parse({ - id: 'slab_fill_left', - polygon: [ - [0, 0], - [4, 0], - [4, 3], - [0, 3], - ], - fillToTerrain: true, - autoFromWalls: true, - }) - const rightSlab = SlabNode.parse({ - id: 'slab_fill_right', - polygon: [ - [4, 0], - [8, 0], - [8, 3], - [4, 3], - ], - autoFromWalls: true, - }) - const mergedRoom = [ - { x: 0, y: 0 }, - { x: 8, y: 0 }, - { x: 8, y: 3 }, - { x: 0, y: 3 }, - ] - - const plan = planAutoSlabsForLevel([mergedRoom], [leftSlab, rightSlab]) - - expect(plan.create).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - expect(plan.update).toEqual( - expect.arrayContaining([ - { id: leftSlab.id, data: { autoFromWalls: false } }, - { id: rightSlab.id, data: { autoFromWalls: false } }, - ]), - ) - }) - - test('clips an elevator opening across both sides of a slab split', () => { - const crossingHole: Array<[number, number]> = [ - [1.5, 1], - [2.5, 1], - [2.5, 2], - [1.5, 2], - ] - const auto = SlabNode.parse({ - polygon: square, - holes: [crossingHole], - holeMetadata: [{ source: 'elevator', elevatorId: 'elevator_crossing' }], - autoFromWalls: true, - }) - const rooms = [ - [ - { x: 0, y: 0 }, - { x: 2, y: 0 }, - { x: 2, y: 3 }, - { x: 0, y: 3 }, - ], - [ - { x: 2, y: 0 }, - { x: 4, y: 0 }, - { x: 4, y: 3 }, - { x: 2, y: 3 }, - ], - ] - - const plan = planAutoSlabsForLevel(rooms, [auto]) - const surfaces = [SlabNode.parse({ ...auto, ...plan.update[0]?.data }), ...plan.create] - const holes = surfaces.flatMap((surface) => surface.holes) - - expect(holes).toHaveLength(2) - expect(holes).toEqual( - expect.arrayContaining([ - expect.arrayContaining([ - [1.5, 1], - [2, 1], - [2, 2], - [1.5, 2], - ]), - expect.arrayContaining([ - [2, 1], - [2.5, 1], - [2.5, 2], - [2, 2], - ]), - ]), - ) - expect( - surfaces.every( - (surface) => - surface.holeMetadata.length === 1 && - surface.holeMetadata[0]?.source === 'elevator' && - surface.holeMetadata[0]?.elevatorId === 'elevator_crossing', - ), - ).toBe(true) - }) - - test('a demoted slab suppresses re-creating an auto slab when the room re-forms', () => { - const auto = slab(0.05) - - const demotion = planAutoSlabsForLevel([], [auto]).update[0] - const demoted = SlabNode.parse({ ...auto, ...demotion?.data }) - expect(demoted.autoFromWalls).toBe(false) - - const plan = planAutoSlabsForLevel([roomPolygon()], [demoted]) - - expect(plan.create).toHaveLength(0) - expect(plan.update).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - }) - - test('manual slabs that split one room suppress a replacement full-room slab', () => { - const left = SlabNode.parse({ - polygon: [ - [0, 0], - [2, 0], - [2, 3], - [0, 3], - ], - autoFromWalls: false, - }) - const right = SlabNode.parse({ - polygon: [ - [2, 0], - [4, 0], - [4, 3], - [2, 3], - ], - autoFromWalls: false, - }) - - const plan = planAutoSlabsForLevel([roomPolygon()], [left, right]) - - expect(plan.create).toHaveLength(0) - expect(plan.update).toHaveLength(0) - expect(plan.delete).toHaveLength(0) - }) -}) diff --git a/packages/core/src/lib/space-detection.ts b/packages/core/src/lib/space-detection.ts index 0bf48938c5..7902be6723 100644 --- a/packages/core/src/lib/space-detection.ts +++ b/packages/core/src/lib/space-detection.ts @@ -1,58 +1,52 @@ -import { GROUND_SUPPORT_ID } from '../hooks/spatial-grid/support-host-id' import { + type AnyNode, type AnyNodeId, - CeilingNode, - type CeilingNode as CeilingNodeType, - type LevelNode, - SlabNode, - type SlabNode as SlabNodeType, type WallNode, ZoneNode, type ZoneNode as ZoneNodeType, } from '../schema' -import { DEFAULT_LEVEL_HEIGHT } from '../services/level-height' -import { - CEILING_CLAMP_MARGIN, - findLevelAboveId, - getCeilingClampBound, - getLevelBelow, - getLevelElevations, - getStoredLevelHeight, -} from '../services/storey' +import { generateId } from '../schema/base' +import { findLevelAboveId, getLevelBelow, getLevelElevations } from '../services/storey' import { activeSceneCommitNodeIds, getSceneHistoryPauseDepth, + isRestoringSceneHistory, + notifySceneCommit, pauseSceneHistory, resumeSceneHistory, subscribeSceneCommits, } from '../store/history-control' -import { computeWallSlabSupport } from '../systems/slab/slab-support' -import { - getClampedWallCurveOffset, - getWallCurveFrameAt, - isCurvedWall, -} from '../systems/wall/wall-curve' -import { resolveWallTop } from '../systems/wall/wall-top' -import { simplifyClosedPolygon } from './polygon-geometry' +import { getClampedWallCurveOffset } from '../systems/wall/wall-curve' +import { changedLevelConstructionDisplacements } from './floor-foundation-stack' +import { createFloorOpeningIndex, floorOpeningTargets } from './floor-opening-intent' import { - distanceToSegment, - type IndexedTopologyDelta, - RoomTopologyIndex, -} from './room-topology-index' -import { levelBaseElevationAt } from './terrain-support' - -type Point2D = { x: number; y: number } + type ExtractedRoom, + extractRooms, + pointToTuple, + polygonSignature, + type SpaceBoundaryFace, + sampleWallPointsForRoomDetection, + WALL_JUNCTION_TOLERANCE, +} from './room-graph' +import { type BoundaryNode, distanceToSegment, RoomTopologyIndex } from './room-topology-index' +import { applyStructureReconciliation } from './structure-commit' +import { classifyWallSides } from './structure-kernel' +import type { StructureIdFactory } from './structure-reconcile' +import { levelBaseElevationAt } from './terrain-support-query' -export type SpaceBoundaryFace = { - wallId: WallNode['id'] - face: 'front' | 'back' - points: Array<[number, number]> +export function wallClosesRoom(walls: WallNode[], wall: WallNode): boolean { + return extractRooms(walls).some((room) => room.spans.some((span) => span.boundaryId === wall.id)) } +const DEFAULT_AUTO_SLAB_ELEVATION = 0.05 + +export { type ExtractedRoom, extractRooms, type SpaceBoundaryFace } from './room-graph' + export type Space = { id: string levelId: string polygon: Array<[number, number]> + holes?: Array> wallIds: Array boundaryFaces: SpaceBoundaryFace[] isExterior: boolean @@ -67,1150 +61,16 @@ export type SpaceTopologyReconcileEvent = { } export type SpaceDetectionSyncOptions = { + mintId?: StructureIdFactory onTopologyReconcile?: (event: SpaceTopologyReconcileEvent) => void } -type ExtractedRoom = { - polygon: Point2D[] - boundaryFaces: SpaceBoundaryFace[] -} - type WallSideUpdate = { wallId: string frontSide: 'interior' | 'exterior' | 'unknown' backSide: 'interior' | 'exterior' | 'unknown' } -type DetectedRoom = { - poly: Point2D[] - sig: string - centroid: Point2D - area: number - bbox: ReturnType -} - -export type AutoSlabSyncPlan = { - create: SlabNodeType[] - update: Array<{ id: SlabNodeType['id']; data: Partial }> - delete: Array -} - -export type AutoSlabPlanningContext = { - elevationForRoom?: (polygon: Array<[number, number]>) => number | undefined - previousElevationForRoom?: (polygon: Array<[number, number]>) => number | undefined -} - -export type AutoCeilingSyncPlan = { - create: CeilingNodeType[] - update: Array<{ id: CeilingNodeType['id']; data: Partial }> - delete: Array - reparent: Array<{ id: AnyNodeId; parentId: CeilingNodeType['id'] }> -} - -export type AutoZoneSyncPlan = { - update: Array<{ id: ZoneNodeType['id']; data: Partial }> -} - -const DEFAULT_AUTO_SLAB_ELEVATION = 0.05 -const CEILING_HEIGHT_EPSILON = 1e-6 -const ROOM_CURVE_TOLERANCE = 0.04 -const MAX_CURVE_SUBDIVISION_DEPTH = 6 -const AUTO_SLAB_POLYGON_SIMPLIFY_TOLERANCE = 0.08 -const WALL_ROOM_BOUNDARY_TOLERANCE = 0.08 -// A wall endpoint within this distance of another wall's interior is treated as a -// T-junction and splits that wall (see `splitStraightWallAtVertices`). -const WALL_JUNCTION_TOLERANCE = 0.08 -// An unmatched auto slab/ceiling whose polygon is still substantially covered -// by a detected room was absorbed by a room merge — the surviving auto surface -// owns that area, so keeping it would z-fight and it is deleted. Below this -// coverage the room genuinely ceased to exist (e.g. an enclosing wall was -// deleted) and the node is demoted to manual so user data survives. -const ORPHAN_MERGE_COVERAGE_THRESHOLD = 0.6 -const COVERAGE_SAMPLE_STEPS = 12 -// Rewrite deadband for an existing auto surface's elevation/height: below this -// the derived plane is the same plane and writing it would churn history. -const ROOM_VERTICAL_PLANE_EPSILON = 1e-3 - -// Pure planner callers omit `heightForRoom`, so auto ceilings keep their -// height-less level-following behavior. The live room sync supplies a height -// derived from the enclosing walls' own bases and tops. -export type AutoCeilingPlanningContext = { - /** Stored storey height of the level being planned (floor-to-floor). */ - storeyHeight?: number - /** - * Stage 3-B clamp-bound resolver for a polygon on the planned level: - * `min(storey plane, lowest covering-slab underside from the level - * above) - CEILING_CLAMP_MARGIN` (see `getCeilingClampBound`). Absent - * (pure-planner callers without a nodes record), the bound degrades to - * the plane-only `storeyHeight - CEILING_CLAMP_MARGIN`. - */ - ceilingClampBound?: (polygon: Array<[number, number]>) => number - heightForRoom?: (polygon: Array<[number, number]>) => number | undefined - previousHeightForRoom?: (polygon: Array<[number, number]>) => number | undefined - childPosition?: (childId: AnyNodeId) => [number, number] | undefined -} - -function pointFromTuple(point: [number, number]): Point2D { - return { x: point[0], y: point[1] } -} - -function pointToTuple(point: Point2D): [number, number] { - return [point.x, point.y] -} - -function pointKey(point: Point2D) { - return `${point.x.toFixed(3)},${point.y.toFixed(3)}` -} - -function polygonArea(points: Point2D[]) { - let area = 0 - for (let i = 0; i < points.length; i++) { - const a = points[i] - const b = points[(i + 1) % points.length] - if (!(a && b)) continue - area += a.x * b.y - b.x * a.y - } - return area / 2 -} - -function minRotationSignature(keys: string[]) { - if (keys.length === 0) return '' - let best = '' - for (let i = 0; i < keys.length; i++) { - const rotated = [...keys.slice(i), ...keys.slice(0, i)] - const value = rotated.join('|') - if (!best || value < best) best = value - } - return best -} - -function polygonSignature(points: Point2D[]) { - const keys = points.map(pointKey) - const forward = minRotationSignature(keys) - const reversed = minRotationSignature([...keys].reverse()) - return forward < reversed ? forward : reversed -} - -function samePointWithinTolerance(a: Point2D, b: Point2D, tolerance = 1e-4) { - return Math.hypot(a.x - b.x, a.y - b.y) <= tolerance -} - -function dedupeSequentialPoints(points: Point2D[], tolerance = 1e-4) { - const deduped: Point2D[] = [] - - for (const point of points) { - const previous = deduped[deduped.length - 1] - if (previous && samePointWithinTolerance(previous, point, tolerance)) { - continue - } - deduped.push(point) - } - - const firstPoint = deduped[0] - const lastPoint = deduped[deduped.length - 1] - if ( - deduped.length > 2 && - firstPoint && - lastPoint && - samePointWithinTolerance(firstPoint, lastPoint, tolerance) - ) { - deduped.pop() - } - - return deduped -} - -function pointInPolygon(point: Point2D, polygon: Point2D[]) { - if (polygon.length < 3) return false - - let inside = false - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i]?.x ?? 0 - const yi = polygon[i]?.y ?? 0 - const xj = polygon[j]?.x ?? 0 - const yj = polygon[j]?.y ?? 0 - - const intersect = - yi > point.y !== yj > point.y && - point.x < ((xj - xi) * (point.y - yi)) / (yj - yi + 1e-12) + xi - if (intersect) inside = !inside - } - - return inside -} - -function pointInAnyPolygon(point: Point2D, polygons: Point2D[][]) { - return polygons.some((polygon) => pointInPolygon(point, polygon)) -} - -function polygonCentroid(points: Point2D[]) { - const sum = points.reduce((acc, point) => ({ x: acc.x + point.x, y: acc.y + point.y }), { - x: 0, - y: 0, - }) - - return { - x: sum.x / Math.max(points.length, 1), - y: sum.y / Math.max(points.length, 1), - } -} - -function bboxOf(points: Point2D[]) { - let minX = Number.POSITIVE_INFINITY - let minY = Number.POSITIVE_INFINITY - let maxX = Number.NEGATIVE_INFINITY - let maxY = Number.NEGATIVE_INFINITY - - for (const point of points) { - minX = Math.min(minX, point.x) - minY = Math.min(minY, point.y) - maxX = Math.max(maxX, point.x) - maxY = Math.max(maxY, point.y) - } - - return { minX, minY, maxX, maxY } -} - -function bboxOverlapArea(a: ReturnType, b: ReturnType) { - const ix = Math.max(0, Math.min(a.maxX, b.maxX) - Math.max(a.minX, b.minX)) - const iy = Math.max(0, Math.min(a.maxY, b.maxY) - Math.max(a.minY, b.minY)) - return ix * iy -} - -// Fraction of `subject`'s area lying inside any of `covers`, estimated by -// sampling a grid of cell centers over the subject's bbox. Cheap and robust -// enough for the merge-vs-demote decision; exact polygon clipping would be a -// heavy dependency for a 60% threshold. -function polygonCoverageRatio( - subject: Point2D[], - covers: Point2D[][], - subjectBounds?: ReturnType, -) { - if (subject.length < 3 || covers.length === 0) return 0 - - const bbox = subjectBounds ?? bboxOf(subject) - const width = bbox.maxX - bbox.minX - const height = bbox.maxY - bbox.minY - - let inside = 0 - let covered = 0 - for (let i = 0; i < COVERAGE_SAMPLE_STEPS; i += 1) { - for (let j = 0; j < COVERAGE_SAMPLE_STEPS; j += 1) { - const point = { - x: bbox.minX + ((i + 0.5) / COVERAGE_SAMPLE_STEPS) * width, - y: bbox.minY + ((j + 0.5) / COVERAGE_SAMPLE_STEPS) * height, - } - if (!pointInPolygon(point, subject)) continue - inside += 1 - if (pointInAnyPolygon(point, covers)) covered += 1 - } - } - - if (inside === 0) { - return pointInAnyPolygon(polygonCentroid(subject), covers) ? 1 : 0 - } - - return covered / inside -} - -// Demoted auto surfaces keep their polygon untouched, so a re-closed room -// usually hits the exact-signature manual check. Coverage handles the rest: -// a room split across multiple manual surfaces AND a single manual surface -// spanning multiple rooms both suppress a replacement auto surface — what -// matters is that the ROOM is already substantially covered, not that any -// one manual surface belongs to it (a per-surface "mostly inside the room" -// filter dropped multi-room slabs and resurrected deleted auto slabs). -function matchesManualFootprint(roomPolygon: Point2D[], manualPolygons: Point2D[][]) { - return polygonCoverageRatio(roomPolygon, manualPolygons) >= ORPHAN_MERGE_COVERAGE_THRESHOLD -} - -function pointDistanceToPolygonBoundary(point: Point2D, polygon: Point2D[]) { - let minDistance = Number.POSITIVE_INFINITY - for (let index = 0; index < polygon.length; index += 1) { - const start = polygon[index] - const end = polygon[(index + 1) % polygon.length] - if (!(start && end)) continue - minDistance = Math.min( - minDistance, - distanceToSegment(pointToTuple(point), pointToTuple(start), pointToTuple(end)), - ) - } - return minDistance -} - -function wallBoundsRoom(wall: WallNode, roomPolygon: Point2D[]) { - const sampled = sampleWallPointsForRoomDetection(wall) - if (sampled.length === 0) return false - - const candidates = - sampled.length === 2 - ? [ - sampled[0]!, - { - x: (sampled[0]!.x + sampled[1]!.x) / 2, - y: (sampled[0]!.y + sampled[1]!.y) / 2, - }, - sampled[1]!, - ] - : sampled - - const matchingPoints = candidates.filter( - (point) => pointDistanceToPolygonBoundary(point, roomPolygon) <= WALL_ROOM_BOUNDARY_TOLERANCE, - ) - - return matchingPoints.length >= 2 -} - -/** - * The clamp bound for a ceiling polygon under this planning context — - * the context's cross-level resolver when provided, else the plane-only - * `storeyHeight - CEILING_CLAMP_MARGIN` degradation. - */ -function resolveCeilingClampBound( - polygon: Array<[number, number]>, - context: AutoCeilingPlanningContext, -) { - if (context.ceilingClampBound) return context.ceilingClampBound(polygon) - return (context.storeyHeight ?? DEFAULT_LEVEL_HEIGHT) - CEILING_CLAMP_MARGIN -} - -/** - * The base a boundary wall actually stands on, in level-local metres. - * - * Resolved the same way the wall renderer resolves it — the level base under - * the wall's own start point (sculpted ground or the flat plane), the slab - * election on top of that, plus the wall's stored `supportOffset`. Reading the - * ground for `GROUND_SUPPORT_ID` walls only is what left stamped room presets - * flat: `resolveWallSupportSlabPatch` writes no host at all for a wall on bare - * terrain, so the sentinel is a hint about pointer intent, never a precondition - * for standing on the ground. - */ -function boundaryWallBase( - wall: WallNode, - walls: WallNode[], - supportSlabs: readonly SlabNodeType[], - nodes: Record, - levelId: string, -): number { - const levelBase = levelBaseElevationAt(nodes, levelId, wall.start[0], wall.start[1]) - const offset = wall.supportOffset ?? 0 - if (wall.supportSlabId === GROUND_SUPPORT_ID) return levelBase + offset - return ( - computeWallSlabSupport(wall, supportSlabs, walls, wall.supportSlabId ?? null, null, levelBase) - .elevation + offset - ) -} - -/** - * The plane an auto floor/ceiling takes when its enclosing walls disagree. - * - * `floor` takes the HIGHEST wall base and `ceiling` the LOWEST wall top — - * the only pair that cannot open a hole: a floor at the lowest base would - * leave daylight under every wall standing higher, and a ceiling at the - * highest top would poke out through the shortest wall. Both surfaces stay - * flat (a slab is one scalar elevation by schema; see `vertical-model.md`), - * so a room on a slope is a level room cut into the hillside — the walls on - * the low side extend down to meet it, which is what their `baseSegments` - * fill-down already does. - * - * Non-finite inputs are the one abstain: a broken graph should keep the - * existing placement rather than move a surface to NaN. - */ -function roomFloorPlane(wallBases: number[]): number | undefined { - if (wallBases.length === 0 || wallBases.some((value) => !Number.isFinite(value))) return undefined - return Math.max(...wallBases) -} - -function roomCeilingPlane(wallTops: number[]): number | undefined { - if (wallTops.length === 0 || wallTops.some((value) => !Number.isFinite(value))) return undefined - return Math.min(...wallTops) -} - -function autoRoomVerticalPlacements( - spaces: readonly Space[], - walls: WallNode[], - supportSlabs: readonly SlabNodeType[], - nodes: Record, - storeyHeight: number, -) { - const wallsById = new Map(walls.map((wall) => [wall.id, wall])) - const placements = new Map() - - for (const space of spaces) { - const boundaryWalls = space.wallIds.flatMap((id) => { - const wall = wallsById.get(id) - return wall ? [wall] : [] - }) - if (boundaryWalls.length !== space.wallIds.length) continue - - const wallBases = boundaryWalls.map((wall) => - boundaryWallBase(wall, walls, supportSlabs, nodes, space.levelId), - ) - const base = roomFloorPlane(wallBases) - if (base === undefined) continue - - const wallTops = boundaryWalls.map((wall, index) => - resolveWallTop(wall, storeyHeight, wallBases[index] ?? base), - ) - const top = roomCeilingPlane(wallTops) - if (top === undefined) continue - - placements.set(polygonSignature(space.polygon.map(pointFromTuple)), { - slabElevation: base + DEFAULT_AUTO_SLAB_ELEVATION, - ceilingHeight: top - CEILING_CLAMP_MARGIN, - }) - } - - return placements -} - -function getWallDirection(wall: Pick) { - const dx = wall.end[0] - wall.start[0] - const dy = wall.end[1] - wall.start[1] - const length = Math.hypot(dx, dy) - - if (length < 1e-9) { - return { - point: pointFromTuple(wall.start), - tangent: { x: 1, y: 0 }, - normal: { x: 0, y: 1 }, - } - } - - const tangent = { x: dx / length, y: dy / length } - return { - point: { - x: (wall.start[0] + wall.end[0]) / 2, - y: (wall.start[1] + wall.end[1]) / 2, - }, - tangent, - normal: { x: -tangent.y, y: tangent.x }, - } -} - -function pointLineDistance(point: Point2D, start: Point2D, end: Point2D) { - const dx = end.x - start.x - const dy = end.y - start.y - const lengthSquared = dx * dx + dy * dy - - if (lengthSquared < 1e-9) { - return Math.hypot(point.x - start.x, point.y - start.y) - } - - const cross = (point.x - start.x) * dy - (point.y - start.y) * dx - return Math.abs(cross) / Math.sqrt(lengthSquared) -} - -function sampleWallPointsForRoomDetection( - wall: Pick, - tolerance = ROOM_CURVE_TOLERANCE, -) { - const start = { x: wall.start[0], y: wall.start[1] } - const end = { x: wall.end[0], y: wall.end[1] } - - if (!isCurvedWall(wall)) { - return [start, end] - } - - const subdivide = ( - t0: number, - p0: Point2D, - t1: number, - p1: Point2D, - depth: number, - ): Point2D[] => { - const midT = (t0 + t1) / 2 - const midPoint = getWallCurveFrameAt(wall, midT).point - const deviation = pointLineDistance(midPoint, p0, p1) - - if (depth >= MAX_CURVE_SUBDIVISION_DEPTH || deviation <= tolerance) { - return [p0, p1] - } - - const left = subdivide(t0, p0, midT, midPoint, depth + 1) - const right = subdivide(midT, midPoint, t1, p1, depth + 1) - return [...left.slice(0, -1), ...right] - } - - return subdivide(0, start, 1, end, 0) -} - -function segmentProjection(point: Point2D, start: Point2D, end: Point2D) { - const dx = end.x - start.x - const dy = end.y - start.y - const lengthSquared = dx * dx + dy * dy - if (lengthSquared < 1e-12) { - return { t: 0, distance: Math.hypot(point.x - start.x, point.y - start.y) } - } - const t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared - const clampedT = Math.max(0, Math.min(1, t)) - const projX = start.x + clampedT * dx - const projY = start.y + clampedT * dy - return { t, distance: Math.hypot(point.x - projX, point.y - projY) } -} - -// Break a straight wall at any junction vertex (another wall's endpoint) that -// lands on its interior, returning the ordered polyline [start, …splits, end]. -// Splitting at the *vertex* position (not the projection) keeps the split node's -// key identical to the touching wall's endpoint so the two share a graph node. -function splitStraightWallAtVertices(start: Point2D, end: Point2D, vertices: Point2D[]) { - const length = Math.hypot(end.x - start.x, end.y - start.y) - if (length < 1e-9) return [start, end] - - const interior: Array<{ point: Point2D; t: number }> = [] - for (const vertex of vertices) { - const { t, distance } = segmentProjection(vertex, start, end) - if (distance > WALL_JUNCTION_TOLERANCE) continue - const along = t * length - if (along <= WALL_JUNCTION_TOLERANCE || along >= length - WALL_JUNCTION_TOLERANCE) continue - interior.push({ point: vertex, t }) - } - interior.sort((a, b) => a.t - b.t) - - const ordered: Point2D[] = [start] - let lastKey = pointKey(start) - for (const { point } of interior) { - const key = pointKey(point) - if (key === lastKey) continue - ordered.push(point) - lastKey = key - } - if (lastKey !== pointKey(end)) ordered.push(end) - return ordered -} - -function extractRooms(walls: WallNode[]): ExtractedRoom[] { - if (walls.length < 3) return [] - - type HalfEdge = { - id: string - reverseId: string - fromKey: string - toKey: string - angle: number - points: Point2D[] - wallId: WallNode['id'] - face: 'front' | 'back' - } - type Node = { point: Point2D; outgoing: string[] } - - const graph = new Map() - const halfEdges = new Map() - - const upsertNode = (point: Point2D) => { - const key = pointKey(point) - if (!graph.has(key)) { - graph.set(key, { point: { ...point }, outgoing: [] }) - } - return key - } - - // Planarize first: collect every wall endpoint as a candidate graph vertex so - // straight walls can be split at T-junctions where another wall ends mid-span. - // Without this the touching wall's endpoint is a dangling degree-1 node and the - // enclosed area (e.g. a room added against the middle of an existing wall) - // never forms a cycle. - const vertexByKey = new Map() - for (const wall of walls) { - for (const tuple of [wall.start, wall.end]) { - const point = pointFromTuple(tuple) - const key = pointKey(point) - if (!vertexByKey.has(key)) vertexByKey.set(key, point) - } - } - const vertices = [...vertexByKey.values()] - - for (const wall of walls) { - const start = pointFromTuple(wall.start) - const end = pointFromTuple(wall.end) - if (samePointWithinTolerance(start, end)) continue - - // Curved walls keep their sampled polyline as one edge; straight walls split - // into consecutive sub-edges at their interior junction vertices. - const subPolylines: Point2D[][] = isCurvedWall(wall) - ? [sampleWallPointsForRoomDetection(wall)] - : (() => { - const ordered = splitStraightWallAtVertices(start, end, vertices) - const parts: Point2D[][] = [] - for (let index = 0; index < ordered.length - 1; index += 1) { - parts.push([ordered[index]!, ordered[index + 1]!]) - } - return parts - })() - - subPolylines.forEach((points, subIndex) => { - const from = points[0]! - const to = points[points.length - 1]! - const fromKey = upsertNode(from) - const toKey = upsertNode(to) - if (fromKey === toKey) return - - const reversePoints = [...points].reverse() - const forwardId = `${wall.id}#${subIndex}:f` - const reverseId = `${wall.id}#${subIndex}:r` - - halfEdges.set(forwardId, { - id: forwardId, - reverseId, - fromKey, - toKey, - angle: Math.atan2(points[1]!.y - from.y, points[1]!.x - from.x), - points, - wallId: wall.id, - face: 'front', - }) - halfEdges.set(reverseId, { - id: reverseId, - reverseId: forwardId, - fromKey: toKey, - toKey: fromKey, - angle: Math.atan2(reversePoints[1]!.y - to.y, reversePoints[1]!.x - to.x), - points: reversePoints, - wallId: wall.id, - face: 'back', - }) - - graph.get(fromKey)?.outgoing.push(forwardId) - graph.get(toKey)?.outgoing.push(reverseId) - }) - } - - const sortedOutgoing = new Map() - for (const [key, node] of graph.entries()) { - const outgoing = [...node.outgoing] - outgoing.sort((a, b) => (halfEdges.get(a)?.angle ?? 0) - (halfEdges.get(b)?.angle ?? 0)) - sortedOutgoing.set(key, outgoing) - } - - const nextEdge = (edgeId: string) => { - const edge = halfEdges.get(edgeId) - if (!edge) return null - - const outgoing = sortedOutgoing.get(edge.toKey) - if (!outgoing || outgoing.length === 0) return null - - const idx = outgoing.indexOf(edge.reverseId) - if (idx === -1) return null - - const nextIdx = (idx - 1 + outgoing.length) % outgoing.length - return outgoing[nextIdx] ?? null - } - - const splitIntoSimpleCycles = (walkEdgeIds: string[]) => { - const cycles: string[][] = [] - const firstEdge = halfEdges.get(walkEdgeIds[0] ?? '') - if (!firstEdge) return cycles - - const pathEdges: string[] = [] - const pathVertices = [firstEdge.fromKey] - const vertexIndex = new Map([[firstEdge.fromKey, 0]]) - - for (const edgeId of walkEdgeIds) { - const edge = halfEdges.get(edgeId) - if (!edge || edge.fromKey !== pathVertices[pathVertices.length - 1]) return [] - - pathEdges.push(edgeId) - const repeatedIndex = vertexIndex.get(edge.toKey) - if (repeatedIndex === undefined) { - pathVertices.push(edge.toKey) - vertexIndex.set(edge.toKey, pathVertices.length - 1) - continue - } - - const cycle = pathEdges.slice(repeatedIndex) - if (cycle.length >= 3) cycles.push(cycle) - - for (let index = repeatedIndex + 1; index < pathVertices.length; index += 1) { - vertexIndex.delete(pathVertices[index]!) - } - pathVertices.length = repeatedIndex + 1 - pathEdges.length = repeatedIndex - } - - return pathEdges.length === 0 && pathVertices.length === 1 ? cycles : [] - } - - const visitedDirected = new Set() - const rooms: ExtractedRoom[] = [] - // A face walk cannot revisit a half-edge, so the half-edge count bounds its - // length. It can revisit a vertex when dangling walls or other graph bridges - // are traced out and back; those excursions are removed below. - const maxSteps = Math.min(2000, halfEdges.size + 10) - - for (const edgeId of halfEdges.keys()) { - if (visitedDirected.has(edgeId)) continue - - const cycleEdgeIds: string[] = [] - let currentEdgeId = edgeId - let valid = true - let closed = false - - for (let step = 0; step < maxSteps; step += 1) { - const currentEdge = halfEdges.get(currentEdgeId) - if (!currentEdge) { - valid = false - break - } - - visitedDirected.add(currentEdgeId) - cycleEdgeIds.push(currentEdgeId) - - const next = nextEdge(currentEdgeId) - if (!next) { - valid = false - break - } - - currentEdgeId = next - if (currentEdgeId === edgeId) { - closed = true - break - } - } - - if (!(valid && closed) || cycleEdgeIds.length < 3) continue - - for (const simpleCycleEdgeIds of splitIntoSimpleCycles(cycleEdgeIds)) { - const polygon = dedupeSequentialPoints( - simpleCycleEdgeIds.flatMap((id, index) => { - const points = halfEdges.get(id)?.points ?? [] - return index === simpleCycleEdgeIds.length - 1 ? points : points.slice(0, -1) - }), - ) - - if (polygon.length < 3) continue - - const signedArea = polygonArea(polygon) - if (signedArea <= 0) continue - if (signedArea < 0.5 || signedArea > 10_000) continue - - const signature = polygonSignature(polygon) - if (rooms.some((room) => polygonSignature(room.polygon) === signature)) continue - - rooms.push({ - polygon, - boundaryFaces: simpleCycleEdgeIds.flatMap((id) => { - const edge = halfEdges.get(id) - if (!edge) return [] - return [ - { - wallId: edge.wallId, - face: edge.face, - points: edge.points.map(pointToTuple), - }, - ] - }), - }) - } - } - - rooms.sort((a, b) => Math.abs(polygonArea(b.polygon)) - Math.abs(polygonArea(a.polygon))) - return rooms -} - -function extractRoomPolygons(walls: WallNode[]): Point2D[][] { - return extractRooms(walls).map((room) => room.polygon) -} - -/** - * True when `wall` lies on the boundary of a room enclosed by `walls`, using the - * same planar room graph the auto slab/ceiling sync uses. The wall builder's - * "Room (auto-close)" mode calls this so drafting stops the moment a segment - * closes a room — whether the chain loops back to its own start or seals a bay - * against the middle of an existing wall (a T-junction). Sharing one graph means - * auto-close and auto-slab detection can never disagree about what is "closed". - */ -export function wallClosesRoom(walls: WallNode[], wall: WallNode): boolean { - const roomPolygons = extractRoomPolygons(walls) - if (roomPolygons.length === 0) return false - return roomPolygons.some((polygon) => wallBoundsRoom(wall, polygon)) -} - -export function resolveWallSurfaceSides( - wall: Pick, - roomPolygons: Point2D[][], -): Pick { - if (roomPolygons.length === 0) { - return { - frontSide: 'unknown' as const, - backSide: 'unknown' as const, - } - } - - const frame = getWallDirection(wall) - const normalLength = Math.hypot(frame.normal.x, frame.normal.y) - if (normalLength < 1e-9) { - return { - frontSide: wall.frontSide, - backSide: wall.backSide, - } - } - - const normalX = frame.normal.x / normalLength - const normalY = frame.normal.y / normalLength - const sampleDistance = Math.max((wall.thickness ?? 0.2) / 2 + 0.08, 0.16) - - const frontPoint = { - x: frame.point.x + normalX * sampleDistance, - y: frame.point.y + normalY * sampleDistance, - } - const backPoint = { - x: frame.point.x - normalX * sampleDistance, - y: frame.point.y - normalY * sampleDistance, - } - - const frontInside = pointInAnyPolygon(frontPoint, roomPolygons) - const backInside = pointInAnyPolygon(backPoint, roomPolygons) - - if (frontInside === backInside) { - return { - frontSide: wall.frontSide, - backSide: wall.backSide, - } - } - - return { - frontSide: frontInside ? 'interior' : 'exterior', - backSide: backInside ? 'interior' : 'exterior', - } -} - -function nextAutoRoomName( - nodes: Array<{ - name?: string - }>, - suffix: 'Slab' | 'Ceiling', -) { - let maxIndex = 0 - - for (const node of nodes) { - const match = /^Room\s+(\d+)(?:\s+(?:Slab|Ceiling))?$/i.exec((node.name ?? '').trim()) - if (!match) continue - const index = Number(match[1]) - if (Number.isFinite(index)) { - maxIndex = Math.max(maxIndex, index) - } - } - - return `Room ${maxIndex + 1} ${suffix}` -} - -function sameTuplePolygon(current: Array<[number, number]>, next: Array<[number, number]>) { - return ( - current.length === next.length && - current.every((point, index) => point[0] === next[index]?.[0] && point[1] === next[index]?.[1]) - ) -} - -function sameTuplePolygonRotation(current: Array<[number, number]>, next: Array<[number, number]>) { - if (sameTuplePolygon(current, next)) return true - if (current.length !== next.length) return false - // Preserve the stored ring when extraction only changes its starting vertex. - return next.some((_, offset) => - current.every((point, index) => { - const candidate = next[(index + offset) % next.length]! - return point[0] === candidate[0] && point[1] === candidate[1] - }), - ) -} - -function sameTuplePolygons( - current: Array>, - next: Array>, -) { - return ( - current.length === next.length && - current.every((polygon, index) => { - const nextPolygon = next[index] - return nextPolygon ? sameTuplePolygon(polygon, nextPolygon) : false - }) - ) -} - -type SurfaceWithOpenings = { - holes: Array> - holeMetadata: SlabNodeType['holeMetadata'] -} - -function crossProduct(a: Point2D, b: Point2D, c: Point2D) { - return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) -} - -function lineIntersection(start: Point2D, end: Point2D, clipStart: Point2D, clipEnd: Point2D) { - const segment = { x: end.x - start.x, y: end.y - start.y } - const clip = { x: clipEnd.x - clipStart.x, y: clipEnd.y - clipStart.y } - const denominator = segment.x * clip.y - segment.y * clip.x - if (Math.abs(denominator) < 1e-9) return end - const offset = { x: clipStart.x - start.x, y: clipStart.y - start.y } - const t = (offset.x * clip.y - offset.y * clip.x) / denominator - return { x: start.x + segment.x * t, y: start.y + segment.y * t } -} - -function clipPolygonToConvex(subject: Point2D[], clipPolygon: Point2D[]) { - if (subject.length < 3 || clipPolygon.length < 3) return [] - const orientation = polygonArea(clipPolygon) >= 0 ? 1 : -1 - let output = [...subject] - - for (let index = 0; index < clipPolygon.length; index += 1) { - const clipStart = clipPolygon[index]! - const clipEnd = clipPolygon[(index + 1) % clipPolygon.length]! - const input = output - output = [] - if (input.length === 0) break - - let previous = input[input.length - 1]! - let previousInside = orientation * crossProduct(clipStart, clipEnd, previous) >= -1e-8 - for (const current of input) { - const currentInside = orientation * crossProduct(clipStart, clipEnd, current) >= -1e-8 - if (currentInside !== previousInside) { - output.push(lineIntersection(previous, current, clipStart, clipEnd)) - } - if (currentInside) output.push(current) - previous = current - previousInside = currentInside - } - output = dedupeSequentialPoints(output, 1e-7) - } - - return output.length >= 3 && Math.abs(polygonArea(output)) > 1e-8 ? output : [] -} - -function isConvexPolygon(polygon: Point2D[]) { - let direction = 0 - for (let index = 0; index < polygon.length; index += 1) { - const cross = crossProduct( - polygon[index]!, - polygon[(index + 1) % polygon.length]!, - polygon[(index + 2) % polygon.length]!, - ) - if (Math.abs(cross) < 1e-8) continue - const nextDirection = Math.sign(cross) - if (direction !== 0 && nextDirection !== direction) return false - direction = nextDirection - } - return true -} - -function pointInTriangle(point: Point2D, a: Point2D, b: Point2D, c: Point2D) { - return ( - crossProduct(a, b, point) >= -1e-8 && - crossProduct(b, c, point) >= -1e-8 && - crossProduct(c, a, point) >= -1e-8 - ) -} - -function triangulatePolygon(polygon: Point2D[]) { - const points = polygonArea(polygon) >= 0 ? [...polygon] : [...polygon].reverse() - const indices = points.map((_, index) => index) - const triangles: Point2D[][] = [] - let attempts = 0 - - while (indices.length > 3 && attempts < points.length * points.length) { - let clippedEar = false - for (let index = 0; index < indices.length; index += 1) { - const previousIndex = indices[(index - 1 + indices.length) % indices.length]! - const currentIndex = indices[index]! - const nextIndex = indices[(index + 1) % indices.length]! - const previous = points[previousIndex]! - const current = points[currentIndex]! - const next = points[nextIndex]! - if (crossProduct(previous, current, next) <= 1e-8) continue - if ( - indices.some( - (candidateIndex) => - candidateIndex !== previousIndex && - candidateIndex !== currentIndex && - candidateIndex !== nextIndex && - pointInTriangle(points[candidateIndex]!, previous, current, next), - ) - ) { - continue - } - triangles.push([previous, current, next]) - indices.splice(index, 1) - clippedEar = true - break - } - if (!clippedEar) break - attempts += 1 - } - - if (indices.length === 3) triangles.push(indices.map((index) => points[index]!)) - return triangles -} - -function clipOpeningToRoom(opening: Point2D[], room: Point2D[]) { - const openingIsInside = opening.every( - (point) => pointInPolygon(point, room) || pointDistanceToPolygonBoundary(point, room) <= 1e-7, - ) - if (openingIsInside) return [opening] - - const clipRegions = isConvexPolygon(room) ? [room] : triangulatePolygon(room) - return clipRegions - .map((region) => clipPolygonToConvex(opening, region)) - .filter((polygon) => polygon.length >= 3) -} - -function partitionSurfaceOpenings( - surface: SurfaceWithOpenings, - roomIndices: number[], - detected: DetectedRoom[], -) { - const assignments = new Map< - number, - { holes: Array>; holeMetadata: SlabNodeType['holeMetadata'] } - >() - for (const roomIndex of roomIndices) { - assignments.set(roomIndex, { holes: [], holeMetadata: [] }) - } - - surface.holes.forEach((hole, holeIndex) => { - const holePolygon = hole.map(pointFromTuple) - for (const roomIndex of roomIndices) { - const room = detected[roomIndex] - const assignment = assignments.get(roomIndex) - if (!(room && assignment)) continue - for (const clipped of clipOpeningToRoom(holePolygon, room.poly)) { - assignment.holes.push(clipped.map(pointToTuple)) - assignment.holeMetadata.push(surface.holeMetadata[holeIndex] ?? { source: 'manual' }) - } - } - }) - - return assignments -} - -function partitionCeilingChildren( - ceiling: CeilingNodeType, - roomIndices: number[], - detected: DetectedRoom[], - fallbackRoomIndex: number | undefined, - childPosition: AutoCeilingPlanningContext['childPosition'], -) { - const assignments = new Map() - for (const roomIndex of roomIndices) assignments.set(roomIndex, []) - - for (const childId of ceiling.children) { - const tuple = childPosition?.(childId) - const point = tuple ? pointFromTuple(tuple) : undefined - const boundaryRoomIndices = point - ? roomIndices.filter((roomIndex) => { - const room = detected[roomIndex] - return room ? pointDistanceToPolygonBoundary(point, room.poly) <= 1e-7 : false - }) - : [] - const interiorRoomIndex = - point && boundaryRoomIndices.length === 0 - ? roomIndices.find((roomIndex) => { - const room = detected[roomIndex] - return room ? pointInPolygon(point, room.poly) : false - }) - : undefined - const roomIndex = - interiorRoomIndex ?? - (fallbackRoomIndex !== undefined && boundaryRoomIndices.includes(fallbackRoomIndex) - ? fallbackRoomIndex - : boundaryRoomIndices[0]) ?? - fallbackRoomIndex ?? - roomIndices[0] - if (roomIndex !== undefined) assignments.get(roomIndex)?.push(childId) - } - - return assignments -} - -function sameHoleMetadata( - current: SlabNodeType['holeMetadata'], - next: SlabNodeType['holeMetadata'], -) { - return ( - current.length === next.length && - current.every((metadata, index) => { - const candidate = next[index] - return ( - candidate?.source === metadata.source && - candidate.stairId === metadata.stairId && - candidate.elevatorId === metadata.elevatorId - ) - }) - ) -} - -function mergedSurfaceOpenings(surfaces: SurfaceWithOpenings[]) { - const holes: Array> = [] - const holeMetadata: SlabNodeType['holeMetadata'] = [] - const seen = new Set() - - for (const surface of surfaces) { - surface.holes.forEach((hole, index) => { - const metadata = surface.holeMetadata[index] ?? { source: 'manual' } - const key = JSON.stringify([hole, metadata]) - if (seen.has(key)) return - seen.add(key) - holes.push(hole) - holeMetadata.push(metadata) - }) - } - - return { holes, holeMetadata } -} - -function ceilingMergeSettingsSignature(ceiling: CeilingNodeType) { - return JSON.stringify([ - ceiling.height ?? null, - ceiling.material ?? null, - ceiling.materialPreset ?? null, - ceiling.slots ?? null, - ceiling.visible, - ]) -} - -function slabMergeSettingsSignature(slab: SlabNodeType) { - return JSON.stringify([ - slab.elevation, - slab.thickness, - slab.recessed, - slab.recessedRimElevation ?? null, - slab.fillToTerrain ?? null, - slab.material ?? null, - slab.materialPreset ?? null, - slab.slots ?? null, - slab.visible, - ]) -} - -function slabElevationForReconciledRoom( - source: SlabNodeType, - polygon: Array<[number, number]>, - context: AutoSlabPlanningContext, -) { - const currentDerived = context.elevationForRoom?.(polygon) - if (!context.previousElevationForRoom) return currentDerived ?? source.elevation - - const previousDerived = context.previousElevationForRoom(source.polygon) - const sourceWasDerived = - previousDerived !== undefined && - Math.abs(source.elevation - previousDerived) <= ROOM_VERTICAL_PLANE_EPSILON - return sourceWasDerived ? (currentDerived ?? source.elevation) : source.elevation -} - -function ceilingHeightForReconciledRoom( - source: CeilingNodeType, - polygon: Array<[number, number]>, - context: AutoCeilingPlanningContext, -) { - if (source.height === undefined) return undefined - - const currentDerived = context.heightForRoom?.(polygon) - if (!context.previousHeightForRoom) return currentDerived ?? source.height - - const previousDerived = context.previousHeightForRoom(source.polygon) - const sourceWasDerived = - previousDerived !== undefined && - Math.abs(source.height - previousDerived) <= ROOM_VERTICAL_PLANE_EPSILON - return sourceWasDerived ? (currentDerived ?? source.height) : source.height -} - function wallGeometrySignature(wall: WallNode, nodes: Record, levelId: string) { return [ wall.id, @@ -1219,6 +79,13 @@ function wallGeometrySignature(wall: WallNode, nodes: Record, level wall.end[0].toFixed(4), wall.end[1].toFixed(4), (wall.thickness ?? 0.2).toFixed(4), + wall.justification, + JSON.stringify( + (wall.children ?? []) + .map((id) => nodes[id]) + .filter((node) => node?.type === 'door' || node?.type === 'window') + .map((node) => [node.id, node.position, node.width, node.height, node.verticalAnchor]), + ), // Plane-bound (no stored height) is a distinct state, not a default // value: it resolves to the storey plane, so it must not alias an // explicit height of the same magnitude in the trigger signature. @@ -1259,48 +126,95 @@ function levelWallSnapshot(walls: WallNode[], nodes: Record, levelI } function zoneGeometrySignature(zone: ZoneNodeType) { - return [ + return JSON.stringify([ zone.id, - zone.autoFromWalls ? 'auto' : 'manual', - zone.boundaryWallIds.slice().sort().join(','), - zone.polygon.map(([x, z]) => `${x.toFixed(4)},${z.toFixed(4)}`).join(';'), - ].join('|') + zone.hasCeiling, + zone.hasFloor, + zone.floor, + zone.wallMaterial, + zone.wallOverrides, + zone.seed, + // A drawn zone's outline is intent (it may be adopted); a room's outline is + // derived, and an edit to it must be re-derived here as the hosted path does. + // The kernel's own write is not a change: the baseline is taken after it. + [zone.polygon, zone.holes], + ]) } -// Slab/ceiling POLYGONS stay out of the trigger signature: including -// generated footprints caused delete/recreate feedback. Zones are included -// only so a newly traced room footprint can adopt its enclosing walls -// without waiting for the next remodel. Slab ELEVATIONS and the level's -// stored storey height ARE included — both feed the explicit-ceiling -// re-clamp bound (the storey plane), and neither is rewritten by -// the sync, so regeneration triggers when they change without feedback. -// Stage 3-B adds the LEVEL-ABOVE's covering-slab undersides (elevation − -// thickness, recessed pools excluded): a deck created, lowered, or -// thickened above must re-run the sync below so ceilings re-clamp under -// it. Same polygon exclusion applies — the level-above's own auto sync -// rewrites its slab footprints, and hashing them here would re-trigger -// this level on every remodel above. +// Derived slab and ceiling footprints and boundary ids stay out of the trigger +// signature: hashing generated footprints caused delete/recreate feedback. Zone +// intent and outlines, separators, wall geometry and slab construction invalidate +// the kernel. function levelStructureSnapshots(nodes: Record) { + const arrivalsByLevel = new Map() + const ceilingIdsByLevel = new Map() + const separatorsByLevel = new Map() const wallsByLevel = new Map() const zonesByLevel = new Map() const slabElevationsByLevel = new Map() const coveringUndersidesByLevel = new Map() + const floorOpenings: Extract[] = [] for (const node of Object.values(nodes)) { if (!(node && typeof node === 'object' && 'parentId' in node && node.parentId)) continue const levelId = (node as any).parentId as string + if (node.type === 'stair' && nodes[node.deckSlabId]?.support === 'open') { + const target = nodes[node.deckSlabId].parentId + const arrivals = arrivalsByLevel.get(target) ?? [] + arrivals.push( + JSON.stringify([ + node.id, + node.position, + node.rotation, + node.visible, + node.stairType, + node.width, + node.innerRadius, + node.sweepAngle, + node.topLandingMode, + node.topLandingDepth, + node.children.map((id: string) => nodes[id]), + ]), + ) + arrivalsByLevel.set(target, arrivals) + } if ((node as any).type === 'wall') { const walls = wallsByLevel.get(levelId) ?? [] walls.push(node as WallNode) wallsByLevel.set(levelId, walls) + } else if (node.type === 'ceiling') { + const ids = ceilingIdsByLevel.get(levelId) ?? [] + ids.push(node.id) + ceilingIdsByLevel.set(levelId, ids) + } else if (node.type === 'separator') { + const values = separatorsByLevel.get(levelId) ?? [] + values.push(JSON.stringify([node.id, node.start, node.end])) + separatorsByLevel.set(levelId, values) } else if ((node as any).type === 'zone') { const zones = zonesByLevel.get(levelId) ?? [] zones.push(ZoneNode.parse(node)) zonesByLevel.set(levelId, zones) + } else if (node.type === 'floor-opening') { + floorOpenings.push(node) } else if ((node as any).type === 'slab') { const elevations = slabElevationsByLevel.get(levelId) ?? [] elevations.push( - `${(node as any).id}:${(((node as any).elevation as number | undefined) ?? DEFAULT_AUTO_SLAB_ELEVATION).toFixed(4)}`, + JSON.stringify([ + node.id, + node.elevation ?? DEFAULT_AUTO_SLAB_ELEVATION, + node.thickness, + node.recessed, + node.fillToTerrain, + node.floorHeight, + node.foundation, + node.boundary, + node.autoFromWalls, + node.boundary === 'auto' + ? node.holes?.filter( + (_: unknown, i: number) => node.holeMetadata?.[i]?.source !== 'room', + ) + : [node.polygon, node.holes], + ]), ) slabElevationsByLevel.set(levelId, elevations) if ((node as any).recessed !== true) { @@ -1313,15 +227,45 @@ function levelStructureSnapshots(nodes: Record) { } } + const openingsByLevel = new Map() + if (floorOpenings.length) { + const index = createFloorOpeningIndex(nodes) + for (const opening of floorOpenings) { + const signature = JSON.stringify([ + opening.id, + opening.parentId, + opening.polygon, + opening.hostZoneId, + opening.drawnOn, + opening.cutsPrimary, + opening.cutsAdjacent, + opening.source, + opening.ownerId, + opening.legacyPlateCuts, + ]) + for (const target of floorOpeningTargets(nodes, opening, index)) { + const signatures = openingsByLevel.get(target.levelId) ?? [] + signatures.push(signature) + openingsByLevel.set(target.levelId, signatures) + } + } + } + const levelElevations = getLevelElevations(nodes as Record) const snapshots = new Map() - const levelIds = new Set([...wallsByLevel.keys(), ...zonesByLevel.keys()]) + const levelIds = new Set([ + ...arrivalsByLevel.keys(), + ...ceilingIdsByLevel.keys(), + ...wallsByLevel.keys(), + ...zonesByLevel.keys(), + ...separatorsByLevel.keys(), + ...openingsByLevel.keys(), + ]) for (const levelId of levelIds) { const walls = wallsByLevel.get(levelId) ?? [] const zones = zonesByLevel.get(levelId) ?? [] const level = nodes[levelId] - const storeyKey = - level?.type === 'level' && typeof level.height === 'number' ? level.height.toFixed(4) : '' + const storeyKey = level?.type === 'level' ? JSON.stringify(level.height) : '' const slabKey = (slabElevationsByLevel.get(levelId) ?? []).sort().join(';') const aboveId = findLevelAboveId(levelId, levelElevations) const aboveSlabKey = aboveId @@ -1329,7 +273,7 @@ function levelStructureSnapshots(nodes: Record) { : '' snapshots.set( levelId, - `${storeyKey}#${levelWallSnapshot(walls, nodes, levelId)}##${zones.map(zoneGeometrySignature).sort().join('||')}##${slabKey}##${aboveSlabKey}`, + `${(arrivalsByLevel.get(levelId) ?? []).sort().join('|')}#${(separatorsByLevel.get(levelId) ?? []).sort().join('|')}#${storeyKey}#${levelWallSnapshot(walls, nodes, levelId)}##${zones.map(zoneGeometrySignature).sort().join('||')}##${slabKey}##${aboveSlabKey}##${(ceilingIdsByLevel.get(levelId) ?? []).sort().join('|')}##${(openingsByLevel.get(levelId) ?? []).sort().join('|')}`, ) } @@ -1342,82 +286,11 @@ function buildSpace(levelId: string, room: ExtractedRoom): Space { id: `space-${levelId}-${signature.slice(0, 12)}`, levelId, polygon: room.polygon.map(pointToTuple), + holes: room.holes, wallIds: [...new Set(room.boundaryFaces.map((boundary) => boundary.wallId))], boundaryFaces: room.boundaryFaces, - isExterior: false, - } -} - -type RoomSurface = SlabNodeType | CeilingNodeType - -type BoundedPolygon = { - polygon: Point2D[] - bbox: ReturnType -} - -export function surfaceTouchesRooms(surface: BoundedPolygon, rooms: BoundedPolygon[]) { - const { polygon, bbox } = surface - return rooms.some((room) => { - if ( - bbox.maxX < room.bbox.minX || - room.bbox.maxX < bbox.minX || - bbox.maxY < room.bbox.minY || - room.bbox.maxY < bbox.minY - ) { - return false - } - return ( - polygonCoverageRatio(polygon, [room.polygon], bbox) > 0 || - polygonCoverageRatio(room.polygon, [polygon], room.bbox) > 0 - ) - }) -} - -function roomsAreRelated(beforeRoom: ExtractedRoom, currentRoom: ExtractedRoom) { - const beforeIds = new Set(beforeRoom.boundaryFaces.map((boundary) => boundary.wallId)) - const currentIds = new Set(currentRoom.boundaryFaces.map((boundary) => boundary.wallId)) - const sharedWallCount = [...currentIds].filter((wallId) => beforeIds.has(wallId)).length - const smallerBoundarySize = Math.min(beforeIds.size, currentIds.size) - if (sharedWallCount >= 2 && sharedWallCount >= Math.ceil(smallerBoundarySize / 2)) return true - if (bboxOverlapArea(bboxOf(beforeRoom.polygon), bboxOf(currentRoom.polygon)) <= 1e-6) return false - return ( - polygonCoverageRatio(beforeRoom.polygon, [currentRoom.polygon]) > 0 || - polygonCoverageRatio(currentRoom.polygon, [beforeRoom.polygon]) > 0 - ) -} - -function roomHasAutoSurface(room: ExtractedRoom, surfaces: RoomSurface[]) { - return matchesManualFootprint( - room.polygon, - surfaces - .filter((surface) => surface.autoFromWalls) - .map((surface) => surface.polygon.map(pointFromTuple)), - ) -} - -function roomsEligibleForAutoSurface( - beforeRooms: ExtractedRoom[], - currentRooms: ExtractedRoom[], - currentSurfaces: RoomSurface[], -) { - return currentRooms.filter((currentRoom) => { - const related = beforeRooms.flatMap((beforeRoom) => { - if (!roomsAreRelated(beforeRoom, currentRoom)) return [] - return [ - { - room: beforeRoom, - coverage: polygonCoverageRatio(currentRoom.polygon, [beforeRoom.polygon]), - }, - ] - }) - const maxCoverage = Math.max(0, ...related.map(({ coverage }) => coverage)) - const predecessors = - currentRooms.length >= beforeRooms.length && maxCoverage > 0 - ? related.filter(({ coverage }) => coverage >= maxCoverage - 1e-6).map(({ room }) => room) - : related.map(({ room }) => room) - if (predecessors.length === 0) return true - return predecessors.every((beforeRoom) => roomHasAutoSurface(beforeRoom, currentSurfaces)) - }) + isExterior: false, + } } function detectedRoomsByLevel(nodes: Record) { @@ -1500,624 +373,86 @@ function fallbackLevelIdsForCandidates( candidateIds: ReadonlySet, ) { const levelIds = new Set() - const addLevelAndLower = (levelId: string | null | undefined, nodes: SceneNodes) => { + const addLevelAndLower = ( + levelId: string | null | undefined, + nodes: SceneNodes, + includeBelow: boolean, + ) => { if (!levelId) return levelIds.add(levelId) - const lower = getLevelBelow(levelId, nodes) - if (lower) levelIds.add(lower.id) + if (includeBelow) { + const lower = getLevelBelow(levelId, nodes) + if (lower) levelIds.add(lower.id) + } } - + let checkDisplacements = false for (const id of candidateIds) { for (const nodes of [before, current]) { const node = nodes[id] if (!node) continue if (node.type === 'level' || node.type === 'building' || node.type === 'site') { for (const levelId of descendantLevelIds(nodes, node.id)) levelIds.add(levelId) + if (node.type === 'level') { + const lower = getLevelBelow(node.id, nodes) + if (lower) levelIds.add(lower.id) + } + } else if (node.type === 'stair' || node.type === 'stair-segment') { + const stair = node.type === 'stair' ? node : nodes[node.parentId] + const deck = nodes[stair?.deckSlabId] + if (deck?.support === 'open' && deck.parentId) levelIds.add(deck.parentId) + if (node.type === 'stair') + for (const opening of Object.values(nodes)) + if (opening.type === 'floor-opening' && opening.ownerId === node.id) + for (const target of floorOpeningTargets(nodes, opening)) levelIds.add(target.levelId) + } else if (node.type === 'door' || node.type === 'window') { + const wall = nodes[node.parentId] + if (wall?.parentId) levelIds.add(wall.parentId) } else if (node.type === 'slab') { - addLevelAndLower(node.parentId, nodes) - } else if (node.type === 'zone') { + const old = before[id], + next = current[id] + const changed = + !old || + !next || + ['thickness', 'floorHeight', 'polygon', 'holes', 'elevation'].some( + (field) => + JSON.stringify((old as unknown as Record)[field]) !== + JSON.stringify((next as unknown as Record)[field]), + ) + addLevelAndLower(node.parentId, nodes, changed) + if (node.plateRole === 'base' && changed) checkDisplacements = true + } else if (node.type === 'ceiling') { + if (!(before[id] && current[id]) && node.parentId) levelIds.add(node.parentId) + } else if (node.type === 'floor-opening') { + if (node.parentId) levelIds.add(node.parentId) + for (const target of floorOpeningTargets(nodes, node)) levelIds.add(target.levelId) + } else if (node.type === 'zone' || node.type === 'separator') { + if ( + node.type === 'zone' && + before[id]?.type === 'zone' && + current[id]?.type === 'zone' && + zoneGeometrySignature(before[id]) === zoneGeometrySignature(current[id]) + ) + continue if (node.parentId) levelIds.add(node.parentId) } } } + if (checkDisplacements) + for (const levelId of changedLevelConstructionDisplacements(before, current)) + levelIds.add(levelId) return levelIds } -function sameStringSet(a: readonly string[], b: readonly string[]) { - if (a.length !== b.length) return false - const right = new Set(b) - return a.every((value) => right.has(value)) -} - -type AutoSurfaceMatch = { - detectedAll: DetectedRoom[] - detected: DetectedRoom[] - existingAuto: TSurface[] - compatibleMergesByRoomIndex: Map - matchedDetectedIndices: Set - roomIndexBySurfaceId: Map - sourceSurfaceIdByRoomIndex: Map - polygonBySurfaceId: Map> - delete: Array - demote: Array<{ id: TSurface['id']; data: Partial }> -} - -function matchAutoSurfaces( - roomPolygons: Point2D[][], - existingSurfaces: TSurface[], - mergeSettingsSignature: (surface: TSurface) => string, -): AutoSurfaceMatch { - const manualSurfaces = existingSurfaces.filter((surface) => !surface.autoFromWalls) - const manualSignatures = new Set( - manualSurfaces.map((surface) => polygonSignature(surface.polygon.map(pointFromTuple))), - ) - const manualPolygons = manualSurfaces.map((surface) => surface.polygon.map(pointFromTuple)) - const detectedAll: DetectedRoom[] = roomPolygons - .map((poly) => ({ - poly: simplifyClosedPolygon(poly.map(pointToTuple), AUTO_SLAB_POLYGON_SIMPLIFY_TOLERANCE).map( - pointFromTuple, - ), - sig: '', - centroid: { x: 0, y: 0 }, - area: 0, - bbox: bboxOf([]), - })) - .map((room) => ({ - ...room, - sig: polygonSignature(room.poly), - centroid: polygonCentroid(room.poly), - area: Math.abs(polygonArea(room.poly)), - bbox: bboxOf(room.poly), - })) - const detected = detectedAll.filter( - ({ sig, poly }) => !manualSignatures.has(sig) && !matchesManualFootprint(poly, manualPolygons), - ) - const existingAuto = existingSurfaces.filter((surface) => surface.autoFromWalls) - const metadata = existingAuto.map((surface) => { - const poly = surface.polygon.map(pointFromTuple) - return { - surface, - sig: polygonSignature(poly), - centroid: polygonCentroid(poly), - area: Math.abs(polygonArea(poly)), - bbox: bboxOf(poly), - } - }) - - const conflictingSurfaceIds = new Set() - const conflictingRoomIndices = new Set() - const compatibleMergesByRoomIndex = new Map() - detected.forEach((room, roomIndex) => { - const contributors = existingAuto.filter( - (surface) => - polygonCoverageRatio(surface.polygon.map(pointFromTuple), [room.poly]) >= - ORPHAN_MERGE_COVERAGE_THRESHOLD, - ) - if (contributors.length < 2) return - if (new Set(contributors.map(mergeSettingsSignature)).size > 1) { - conflictingRoomIndices.add(roomIndex) - for (const surface of contributors) conflictingSurfaceIds.add(surface.id) - return - } - compatibleMergesByRoomIndex.set(roomIndex, contributors) - }) - - const matchedSurfaceIds = new Set() - const matchedDetectedIndices = new Set() - const roomIndexBySurfaceId = new Map() - const sourceSurfaceIdByRoomIndex = new Map() - const polygonBySurfaceId = new Map>() - const autoBySignature = new Map>() - for (const entry of metadata) { - const bucket = autoBySignature.get(entry.sig) ?? [] - bucket.push(entry) - autoBySignature.set(entry.sig, bucket) - } - - detected.forEach((room, index) => { - if (conflictingRoomIndices.has(index)) { - matchedDetectedIndices.add(index) - return - } - const existing = autoBySignature.get(room.sig)?.shift() - if (!existing) return - matchedDetectedIndices.add(index) - matchedSurfaceIds.add(existing.surface.id) - roomIndexBySurfaceId.set(existing.surface.id, index) - sourceSurfaceIdByRoomIndex.set(index, existing.surface.id) - polygonBySurfaceId.set(existing.surface.id, room.poly.map(pointToTuple)) - }) - - const remainingDetected = detected - .map((room, index) => ({ room, index })) - .filter(({ index }) => !matchedDetectedIndices.has(index)) - .sort((left, right) => right.room.area - left.room.area) - const remainingAuto = metadata.filter((entry) => !matchedSurfaceIds.has(entry.surface.id)) - - for (const { room, index } of remainingDetected) { - let bestMatch: { entry: (typeof remainingAuto)[number]; score: number } | null = null - for (const entry of remainingAuto) { - if (matchedSurfaceIds.has(entry.surface.id)) continue - const distance = Math.hypot( - room.centroid.x - entry.centroid.x, - room.centroid.y - entry.centroid.y, - ) - const areaRatio = entry.area > 1e-6 ? room.area / entry.area : 999 - const areaPenalty = Math.abs(Math.log(Math.max(1e-6, areaRatio))) - if (bboxOverlapArea(room.bbox, entry.bbox) <= 0.0001 && distance > 1.5) continue - const score = distance + areaPenalty * 0.35 - if (!bestMatch || score < bestMatch.score) bestMatch = { entry, score } - } - if (!bestMatch) continue - matchedDetectedIndices.add(index) - matchedSurfaceIds.add(bestMatch.entry.surface.id) - roomIndexBySurfaceId.set(bestMatch.entry.surface.id, index) - sourceSurfaceIdByRoomIndex.set(index, bestMatch.entry.surface.id) - polygonBySurfaceId.set(bestMatch.entry.surface.id, room.poly.map(pointToTuple)) - } - - detected.forEach((room, index) => { - if (sourceSurfaceIdByRoomIndex.has(index)) return - let bestSource: { id: string; coverage: number } | null = null - for (const entry of metadata) { - const coverage = polygonCoverageRatio(room.poly, [entry.surface.polygon.map(pointFromTuple)]) - if (coverage <= 0 || (bestSource && coverage <= bestSource.coverage)) continue - bestSource = { id: entry.surface.id, coverage } - } - if (bestSource) sourceSurfaceIdByRoomIndex.set(index, bestSource.id) - }) - - const detectedRoomPolygons = detectedAll.map((room) => room.poly) - const deleted: Array = [] - const demote: AutoSurfaceMatch['demote'] = [] - for (const surface of existingAuto) { - if (polygonBySurfaceId.has(surface.id)) continue - if (conflictingSurfaceIds.has(surface.id)) { - demote.push({ id: surface.id, data: { autoFromWalls: false } as Partial }) - continue - } - const coverage = polygonCoverageRatio(surface.polygon.map(pointFromTuple), detectedRoomPolygons) - if (coverage >= ORPHAN_MERGE_COVERAGE_THRESHOLD) deleted.push(surface.id) - else demote.push({ id: surface.id, data: { autoFromWalls: false } as Partial }) - } - - return { - detectedAll, - detected, - existingAuto, - compatibleMergesByRoomIndex, - matchedDetectedIndices, - roomIndexBySurfaceId, - sourceSurfaceIdByRoomIndex, - polygonBySurfaceId, - delete: deleted, - demote, - } -} - -export function planAutoZonesForLevel( - spaces: readonly Space[], - existingZones: readonly ZoneNodeType[], -): AutoZoneSyncPlan { - const update: AutoZoneSyncPlan['update'] = [] - const walledZones = existingZones.filter( - (zone) => zone.autoFromWalls && zone.boundaryWallIds.length >= 3, - ) - const exactlyMatched = new Set( - spaces.filter((space) => - walledZones.some((zone) => sameStringSet(space.wallIds, zone.boundaryWallIds)), - ), - ) - // A wall edit can add a wall to a room without taking any away (a move bridging a junction): - // the zone then follows the one unclaimed room that still has all of its boundary walls. - const roomKeepingWalls = (zone: ZoneNodeType) => { - const candidates = spaces.filter( - (space) => - !exactlyMatched.has(space) && - zone.boundaryWallIds.every((wallId) => space.wallIds.includes(wallId)), - ) - return candidates.length === 1 ? candidates[0] : undefined - } - - for (const zone of existingZones) { - const storedSignature = polygonSignature(zone.polygon.map(pointFromTuple)) - const matchingSpace = - zone.autoFromWalls && zone.boundaryWallIds.length >= 3 - ? (spaces.find((space) => sameStringSet(space.wallIds, zone.boundaryWallIds)) ?? - roomKeepingWalls(zone)) - : spaces.find( - (space) => polygonSignature(space.polygon.map(pointFromTuple)) === storedSignature, - ) - if (!matchingSpace) continue - - const data: Partial = {} - if (!zone.autoFromWalls) data.autoFromWalls = true - if (!sameStringSet(zone.boundaryWallIds, matchingSpace.wallIds)) { - data.boundaryWallIds = matchingSpace.wallIds - } - if (!sameTuplePolygonRotation(zone.polygon, matchingSpace.polygon)) { - data.polygon = matchingSpace.polygon - } - if (Object.keys(data).length > 0) update.push({ id: zone.id, data }) - } - - return { update } -} - -export function resolveAutoZonePolygon( - zone: Pick, - resolve: (id: AnyNodeId) => unknown, -): ZoneNodeType['polygon'] { - if (!zone.autoFromWalls || zone.boundaryWallIds.length < 3) return zone.polygon - const walls = zone.boundaryWallIds.flatMap((id) => { - const node = resolve(id) - return node && typeof node === 'object' && 'type' in node && node.type === 'wall' - ? [node as WallNode] - : [] - }) - if (walls.length !== zone.boundaryWallIds.length) return zone.polygon - const room = extractRooms(walls).find((candidate) => - sameStringSet( - [...new Set(candidate.boundaryFaces.map((boundary) => boundary.wallId))], - zone.boundaryWallIds, - ), - ) - return room ? room.polygon.map(pointToTuple) : zone.polygon -} - -export function planAutoSlabsForLevel( - roomPolygons: Point2D[][], - existingSlabs: SlabNodeType[], - context: AutoSlabPlanningContext = {}, - namingSlabs: Array<{ name?: string }> = existingSlabs, -): AutoSlabSyncPlan { - const match = matchAutoSurfaces(roomPolygons, existingSlabs, slabMergeSettingsSignature) - const { - detected, - existingAuto, - compatibleMergesByRoomIndex: compatibleMergeSlabsByRoomIndex, - matchedDetectedIndices: matchedDetectedIdx, - roomIndexBySurfaceId: roomIndexBySlabId, - sourceSurfaceIdByRoomIndex: sourceSlabIdByRoomIndex, - delete: slabsToDelete, - demote: slabDemotions, - } = match - const updatesById = new Map< - string, - { polygon: [number, number][]; elevation: number | undefined } - >() - for (const slab of existingAuto) { - const polygon = match.polygonBySurfaceId.get(slab.id) - if (!polygon) continue - updatesById.set(slab.id, { - polygon, - elevation: slabElevationForReconciledRoom(slab, polygon, context), - }) - } - - const openingAssignmentsBySlabId = new Map>() - for (const slab of existingAuto) { - const roomIndices = [...sourceSlabIdByRoomIndex.entries()] - .filter(([, slabId]) => slabId === slab.id) - .map(([roomIndex]) => roomIndex) - if (roomIndices.length === 0) continue - openingAssignmentsBySlabId.set(slab.id, partitionSurfaceOpenings(slab, roomIndices, detected)) - } - - const slabsToUpdate = [ - ...existingAuto - .filter((slab) => updatesById.has(slab.id)) - .flatMap((slab) => { - const update = updatesById.get(slab.id) - if (!update) return [] - const roomIndex = roomIndexBySlabId.get(slab.id) - const openings = - roomIndex == null - ? { holes: slab.holes, holeMetadata: slab.holeMetadata } - : compatibleMergeSlabsByRoomIndex.has(roomIndex) - ? mergedSurfaceOpenings(compatibleMergeSlabsByRoomIndex.get(roomIndex) ?? []) - : (openingAssignmentsBySlabId.get(slab.id)?.get(roomIndex) ?? { - holes: [], - holeMetadata: [], - }) - const data: Partial = {} - if (!sameTuplePolygonRotation(slab.polygon, update.polygon)) data.polygon = update.polygon - if (!sameTuplePolygons(slab.holes, openings.holes)) data.holes = openings.holes - if (!sameHoleMetadata(slab.holeMetadata, openings.holeMetadata)) { - data.holeMetadata = openings.holeMetadata - } - if ( - update.elevation !== undefined && - Math.abs(slab.elevation - update.elevation) > ROOM_VERTICAL_PLANE_EPSILON - ) { - data.elevation = update.elevation - } - return Object.keys(data).length > 0 ? [{ id: slab.id, data }] : [] - }), - ...slabDemotions, - ] - - const plannedSlabsForNaming: Array<{ name?: string }> = [...namingSlabs] - const slabsToCreate: SlabNodeType[] = [] - for (let index = 0; index < detected.length; index += 1) { - if (matchedDetectedIdx.has(index)) continue - - const room = detected[index] - if (!room) continue - - const name = nextAutoRoomName(plannedSlabsForNaming, 'Slab') - plannedSlabsForNaming.push({ name }) - - const polygon = room.poly.map(pointToTuple) - const sourceId = sourceSlabIdByRoomIndex.get(index) - const source = sourceId ? existingAuto.find((slab) => slab.id === sourceId) : undefined - const openings = sourceId ? openingAssignmentsBySlabId.get(sourceId)?.get(index) : undefined - const elevation = source - ? slabElevationForReconciledRoom(source, polygon, context) - : context.elevationForRoom?.(polygon) - slabsToCreate.push( - SlabNode.parse({ - name, - polygon, - holes: openings?.holes ?? [], - holeMetadata: openings?.holeMetadata ?? [], - elevation: - elevation !== undefined && Number.isFinite(elevation) - ? elevation - : DEFAULT_AUTO_SLAB_ELEVATION, - thickness: source?.thickness, - recessed: source?.recessed, - recessedRimElevation: source?.recessedRimElevation, - fillToTerrain: source?.fillToTerrain, - material: source?.material, - materialPreset: source?.materialPreset, - slots: source?.slots, - visible: source?.visible, - autoFromWalls: true, - }), - ) - } - - return { - create: slabsToCreate, - update: slabsToUpdate, - delete: slabsToDelete, - } -} - -function syncAutoSlabsForLevel( - levelId: string, - roomPolygons: Point2D[][], - existingSlabs: SlabNodeType[], - sceneStore: any, - context: AutoSlabPlanningContext = {}, - namingSlabs: Array<{ name?: string }> = existingSlabs, -) { - const plan = planAutoSlabsForLevel(roomPolygons, existingSlabs, context, namingSlabs) - - if (plan.delete.length > 0) { - sceneStore.getState().deleteNodes(plan.delete) - } - - if (plan.update.length > 0) { - sceneStore.getState().updateNodes(plan.update) - } - - if (plan.create.length > 0) { - sceneStore.getState().createNodes(plan.create.map((node) => ({ node, parentId: levelId }))) - } - - return plan -} - -export function planAutoCeilingsForLevel( - roomPolygons: Point2D[][], - existingCeilings: CeilingNodeType[], - context: AutoCeilingPlanningContext = {}, - namingCeilings: Array<{ name?: string }> = existingCeilings, -): AutoCeilingSyncPlan { - const manualCeilings = existingCeilings.filter((ceiling) => !ceiling.autoFromWalls) - const match = matchAutoSurfaces(roomPolygons, existingCeilings, ceilingMergeSettingsSignature) - const { - detected, - existingAuto, - compatibleMergesByRoomIndex: compatibleMergeCeilingsByRoomIndex, - matchedDetectedIndices: matchedDetectedIdx, - roomIndexBySurfaceId: roomIndexByCeilingId, - sourceSurfaceIdByRoomIndex: sourceCeilingIdByRoomIndex, - delete: ceilingsToDelete, - demote: ceilingDemotions, - } = match - const updatesById = new Map() - for (const ceiling of existingAuto) { - const polygon = match.polygonBySurfaceId.get(ceiling.id) - if (!polygon) continue - updatesById.set(ceiling.id, { - polygon, - height: ceilingHeightForReconciledRoom(ceiling, polygon, context), - }) - } - - // Stage 3-B reactive re-clamp (clamp-never-ask): a covering slab - // created, moved, or thickened on the level above can leave an EXISTING - // manual explicit-height ceiling poking into its solid. Clamp explicit - // heights down to the bound; never raise them — a user-lowered ceiling - // is intent, only an over-bound one is a conflict. Follows-mode - // ceilings (absent height) derive under the bound by construction and - // are skipped, so the clamp can never convert one to an explicit - // height. - const manualClamps: AutoCeilingSyncPlan['update'] = manualCeilings.flatMap((ceiling) => { - if (ceiling.height == null) return [] - const bound = resolveCeilingClampBound(ceiling.polygon, context) - if (!Number.isFinite(bound)) return [] - return ceiling.height > bound + CEILING_HEIGHT_EPSILON - ? [{ id: ceiling.id, data: { height: bound } }] - : [] - }) - - const openingAssignmentsByCeilingId = new Map< - string, - ReturnType - >() - const childAssignmentsByCeilingId = new Map>() - for (const ceiling of existingAuto) { - const roomIndices = [...sourceCeilingIdByRoomIndex.entries()] - .filter(([, ceilingId]) => ceilingId === ceiling.id) - .map(([roomIndex]) => roomIndex) - if (roomIndices.length === 0) continue - openingAssignmentsByCeilingId.set( - ceiling.id, - partitionSurfaceOpenings(ceiling, roomIndices, detected), - ) - childAssignmentsByCeilingId.set( - ceiling.id, - partitionCeilingChildren( - ceiling, - roomIndices, - detected, - roomIndexByCeilingId.get(ceiling.id), - context.childPosition, - ), - ) - } - - const childReparents: AutoCeilingSyncPlan['reparent'] = [] - const ceilingsToUpdate = [ - ...existingAuto - .filter((ceiling) => updatesById.has(ceiling.id)) - .flatMap((ceiling) => { - const update = updatesById.get(ceiling.id) - if (!update) return [] - const roomIndex = roomIndexByCeilingId.get(ceiling.id) - const openings = - roomIndex == null - ? { holes: ceiling.holes, holeMetadata: ceiling.holeMetadata } - : compatibleMergeCeilingsByRoomIndex.has(roomIndex) - ? mergedSurfaceOpenings(compatibleMergeCeilingsByRoomIndex.get(roomIndex) ?? []) - : (openingAssignmentsByCeilingId.get(ceiling.id)?.get(roomIndex) ?? { - holes: [], - holeMetadata: [], - }) - const data: Partial = {} - if (!sameTuplePolygonRotation(ceiling.polygon, update.polygon)) - data.polygon = update.polygon - if (!sameTuplePolygons(ceiling.holes, openings.holes)) data.holes = openings.holes - if (!sameHoleMetadata(ceiling.holeMetadata, openings.holeMetadata)) { - data.holeMetadata = openings.holeMetadata - } - const mergeContributors = - roomIndex == null ? undefined : compatibleMergeCeilingsByRoomIndex.get(roomIndex) - const children = mergeContributors - ? ([ - ...new Set(mergeContributors.flatMap((contributor) => contributor.children)), - ] as CeilingNodeType['children']) - : roomIndex == null - ? ceiling.children - : (childAssignmentsByCeilingId.get(ceiling.id)?.get(roomIndex) ?? ceiling.children) - for (const contributor of mergeContributors ?? []) { - if (contributor.id === ceiling.id) continue - for (const childId of contributor.children) { - childReparents.push({ id: childId, parentId: ceiling.id }) - } - } - if (!sameStringSet(ceiling.children, children)) data.children = children - if ( - update.height !== undefined && - (ceiling.height === undefined || - Math.abs(ceiling.height - update.height) > ROOM_VERTICAL_PLANE_EPSILON) - ) { - data.height = update.height - } - return Object.keys(data).length > 0 ? [{ id: ceiling.id, data }] : [] - }), - ...ceilingDemotions, - ...manualClamps, - ] - - const plannedCeilingsForNaming: Array<{ name?: string }> = [...namingCeilings] - const ceilingsToCreate: CeilingNodeType[] = [] - for (let index = 0; index < detected.length; index += 1) { - if (matchedDetectedIdx.has(index)) continue - - const room = detected[index] - if (!room) continue - - const name = nextAutoRoomName(plannedCeilingsForNaming, 'Ceiling') - plannedCeilingsForNaming.push({ name }) - - const polygon = room.poly.map(pointToTuple) - const sourceId = sourceCeilingIdByRoomIndex.get(index) - const source = sourceId ? existingAuto.find((ceiling) => ceiling.id === sourceId) : undefined - const openings = sourceId ? openingAssignmentsByCeilingId.get(sourceId)?.get(index) : undefined - const children = sourceId ? childAssignmentsByCeilingId.get(sourceId)?.get(index) : undefined - const height = source - ? ceilingHeightForReconciledRoom(source, polygon, context) - : context.heightForRoom?.(polygon) - const created = CeilingNode.parse({ - name, - polygon, - children: children ?? [], - holes: openings?.holes ?? [], - holeMetadata: openings?.holeMetadata ?? [], - material: source?.material, - materialPreset: source?.materialPreset, - slots: source?.slots, - visible: source?.visible, - ...(height !== undefined && Number.isFinite(height) ? { height } : {}), - autoFromWalls: true, - }) - ceilingsToCreate.push(created) - for (const childId of children ?? []) { - childReparents.push({ id: childId, parentId: created.id }) - } - } - - return { - create: ceilingsToCreate, - update: ceilingsToUpdate, - delete: ceilingsToDelete, - reparent: childReparents, - } -} - -function syncAutoCeilingsForLevel( - levelId: string, - roomPolygons: Point2D[][], - existingCeilings: CeilingNodeType[], - sceneStore: any, - context: AutoCeilingPlanningContext = {}, - namingCeilings: Array<{ name?: string }> = existingCeilings, -) { - const plan = planAutoCeilingsForLevel(roomPolygons, existingCeilings, context, namingCeilings) - - if (plan.update.length > 0) { - sceneStore.getState().updateNodes(plan.update) - } - - if (plan.create.length > 0) { - sceneStore.getState().createNodes(plan.create.map((node) => ({ node, parentId: levelId }))) - } - - if (plan.reparent.length > 0) { - sceneStore - .getState() - .updateNodes(plan.reparent.map(({ id, parentId }) => ({ id, data: { parentId } }))) - } - - if (plan.delete.length > 0) { - sceneStore.getState().deleteNodes(plan.delete) - } -} - -function detectSpacesFromWalls(levelId: string, walls: WallNode[]) { - const rooms = extractRooms(walls) +function detectSpacesFromWalls(levelId: string, boundaries: BoundaryNode[]) { + const rooms = extractRooms(boundaries) + const walls = boundaries.filter((boundary): boundary is WallNode => boundary.type === 'wall') const roomPolygons = rooms.map((room) => room.polygon) const wallUpdates: WallSideUpdate[] = walls.map((wall) => ({ wallId: wall.id, - ...(resolveWallSurfaceSides(wall, roomPolygons) satisfies Pick< - WallSideUpdate, - 'frontSide' | 'backSide' - >), + ...classifyWallSides( + wall, + rooms.flatMap((room) => room.spans), + ), })) return { @@ -2128,554 +463,63 @@ function detectSpacesFromWalls(levelId: string, walls: WallNode[]) { } } -export function detectSpacesForLevel(levelId: string, walls: WallNode[]) { +export function detectSpacesForLevel(levelId: string, walls: BoundaryNode[]) { return detectSpacesFromWalls(levelId, walls) } -// Automatic surfaces come from centreline room detection, so their vertices sit on the walls. -const WALL_BOUND_VERTEX_TOLERANCE = 1e-3 -// Arc vertices are exact curve samples; the search polyline below is finer than this. -const CURVED_WALL_VERTEX_TOLERANCE = 5e-3 -const CURVE_SEARCH_SAMPLES = 256 - -type WallMoveSegment = Pick -type FollowedWall = WallMoveSegment & Pick - -function intersectWallLines(a: WallMoveSegment, b: WallMoveSegment): [number, number] | null { - const ax = a.end[0] - a.start[0] - const ay = a.end[1] - a.start[1] - const bx = b.end[0] - b.start[0] - const by = b.end[1] - b.start[1] - const cross = ax * by - ay * bx - if (Math.abs(cross) <= 1e-9 * Math.hypot(ax, ay) * Math.hypot(bx, by)) return null - const t = ((b.start[0] - a.start[0]) * by - (b.start[1] - a.start[1]) * bx) / cross - return [a.start[0] + ax * t, a.start[1] + ay * t] -} - -/** Keeps a vertex at the same fraction of its straight wall as the wall moves. */ -function carryAlongWall( - vertex: [number, number], - from: WallMoveSegment, - to: WallMoveSegment, -): [number, number] { - const dx = from.end[0] - from.start[0] - const dy = from.end[1] - from.start[1] - const lengthSq = dx * dx + dy * dy - if (lengthSq < 1e-12) { - return [vertex[0] + to.start[0] - from.start[0], vertex[1] + to.start[1] - from.start[1]] - } - const t = ((vertex[0] - from.start[0]) * dx + (vertex[1] - from.start[1]) * dy) / lengthSq - return [to.start[0] + (to.end[0] - to.start[0]) * t, to.start[1] + (to.end[1] - to.start[1]) * t] -} - -/** Curve parameter of a vertex on a curved wall's arc, or null when it is off the arc. */ -function curveParameterOf(vertex: [number, number], wall: FollowedWall): number | null { - let best: { distance: number; t: number } | null = null - let previous = getWallCurveFrameAt(wall, 0).point - for (let index = 1; index <= CURVE_SEARCH_SAMPLES; index += 1) { - const point = getWallCurveFrameAt(wall, index / CURVE_SEARCH_SAMPLES).point - const dx = point.x - previous.x - const dy = point.y - previous.y - const lengthSq = dx * dx + dy * dy - const local = - lengthSq > 0 - ? Math.max( - 0, - Math.min(1, ((vertex[0] - previous.x) * dx + (vertex[1] - previous.y) * dy) / lengthSq), - ) - : 0 - const distance = Math.hypot( - vertex[0] - (previous.x + dx * local), - vertex[1] - (previous.y + dy * local), - ) - if (!best || distance < best.distance) { - best = { distance, t: (index - 1 + local) / CURVE_SEARCH_SAMPLES } - } - previous = point - } - return best && best.distance <= CURVED_WALL_VERTEX_TOLERANCE ? best.t : null -} - -/** The straight wall that carries the polygon edge `from → to`, preferring a moving one. */ -function wallAlongEdge( - from: [number, number], - to: [number, number], - walls: ReadonlyMap, - movingWallIds: ReadonlySet, -): string | null { - let found: string | null = null - for (const [id, wall] of walls) { - if (isCurvedWall(wall)) continue - if (distanceToSegment(from, wall.start, wall.end) > WALL_BOUND_VERTEX_TOLERANCE) continue - // The edge lies on the wall's line (an edge may span a chain of collinear walls). - const dx = wall.end[0] - wall.start[0] - const dy = wall.end[1] - wall.start[1] - const length = Math.hypot(dx, dy) - if (length < 1e-9) continue - const offLine = Math.abs((to[0] - wall.start[0]) * dy - (to[1] - wall.start[1]) * dx) / length - if (offLine > WALL_BOUND_VERTEX_TOLERANCE) continue - const edgeX = to[0] - from[0] - const edgeY = to[1] - from[1] - const reach = Math.max( - (wall.start[0] - from[0]) * edgeX + (wall.start[1] - from[1]) * edgeY, - (wall.end[0] - from[0]) * edgeX + (wall.end[1] - from[1]) * edgeY, - ) - if (reach <= WALL_BOUND_VERTEX_TOLERANCE * Math.hypot(edgeX, edgeY)) continue - if (movingWallIds.has(id)) return id - found ??= id - } - return found -} - -type VertexBinding = - | { kind: 'fixed' } - | { kind: 'curve'; wallId: string; t: number; curveBefore: boolean } - | { kind: 'edges'; previous: string | null; next: string | null } - -/** - * Live preview of the automatic slabs and ceilings bounded by `movingWallIds`, with no room - * detection per tick. Boundary membership is read once here: each polygon vertex binds to the - * walls carrying its two edges (a corner is where they meet again), or to its place on a curved - * wall's arc. The returned function re-places the bound vertices for the moved walls; a vertex - * at a junction the move bridges (`bridges`, from `planWallMoveJunctions`: original point → - * moved endpoint) stays and gains the bridge's moved end, as the commit's rooms will. New, - * merged or split rooms appear at commit; rebuild the follower after a foreign topology change. - */ -export function createWallBoundSurfaceFollower( - levelId: string, - nodes: SceneNodes, - movingWallIds: ReadonlySet, -): ( - moved: ReadonlyMap, - bridges?: ReadonlyArray, -) => Array<[AnyNodeId, Array<[number, number]>]> { - const walls = new Map() - for (const node of Object.values(nodes)) { - if (node?.type === 'wall' && node.parentId === levelId) { - walls.set(node.id, { start: node.start, end: node.end, curveOffset: node.curveOffset }) - } - } - const movingCurves = [...movingWallIds] - .map((id) => [id, walls.get(id)] as const) - .filter((entry): entry is readonly [string, FollowedWall] => - Boolean(entry[1] && isCurvedWall(entry[1])), - ) - - const bindVertex = (polygon: Array<[number, number]>, index: number): VertexBinding => { - const vertex = polygon[index]! - for (const [wallId, wall] of movingCurves) { - const t = curveParameterOf(vertex, wall) - if (t === null) continue - // Only a polygon that runs along the arc rides it; one that just touches an arc end - // (a room beside the curved wall's junction) binds by its own edges below. - const curveBefore = - curveParameterOf(polygon[(index + polygon.length - 1) % polygon.length]!, wall) !== null - const curveAfter = curveParameterOf(polygon[(index + 1) % polygon.length]!, wall) !== null - if (curveBefore || curveAfter) return { kind: 'curve', wallId, t, curveBefore } - } - const previous = polygon[(index + polygon.length - 1) % polygon.length]! - const next = polygon[(index + 1) % polygon.length]! - const binding = { - kind: 'edges' as const, - previous: wallAlongEdge(vertex, previous, walls, movingWallIds), - next: wallAlongEdge(vertex, next, walls, movingWallIds), - } - return [binding.previous, binding.next].some((id) => id && movingWallIds.has(id)) - ? binding - : { kind: 'fixed' } - } - - const surfaces: Array<{ - id: AnyNodeId - polygon: Array<[number, number]> - bindings: VertexBinding[] - }> = [] - for (const node of Object.values(nodes)) { - if (node?.type !== 'slab' && node?.type !== 'ceiling') continue - if (node.parentId !== levelId || !node.autoFromWalls) continue - const polygon = node.polygon as Array<[number, number]> - const bindings = polygon.map((_, index) => bindVertex(polygon, index)) - if (bindings.some((binding) => binding.kind !== 'fixed')) { - surfaces.push({ id: node.id, polygon, bindings }) - } - } - - const bridgedEnd = ( - vertex: [number, number], - bridges: ReadonlyArray, - ): [number, number] | null => { - for (const bridge of bridges) { - if ( - Math.hypot(bridge.start[0] - vertex[0], bridge.start[1] - vertex[1]) <= - WALL_BOUND_VERTEX_TOLERANCE - ) { - return [bridge.end[0], bridge.end[1]] - } - } - return null - } - - const followVertex = ( - vertex: [number, number], - binding: VertexBinding, - moved: ReadonlyMap, - bridges: ReadonlyArray, - ): Array<[number, number]> => { - if (binding.kind === 'fixed') return [vertex] - const current = (id: string): FollowedWall => { - const wall = walls.get(id)! - const next = moved.get(id) - return next ? { ...wall, start: next.start, end: next.end } : wall - } - if (binding.kind === 'curve') { - // An arc end at a junction the move bridges stays, and gains the bridge's moved end. - const atEnd = binding.t <= 1e-6 || binding.t >= 1 - 1e-6 - const end = atEnd ? bridgedEnd(vertex, bridges) : null - if (end) return binding.curveBefore ? [end, vertex] : [vertex, end] - const point = getWallCurveFrameAt(current(binding.wallId), binding.t).point - return [[point.x, point.y]] - } - const { previous, next } = binding - const shifts = (id: string | null) => { - const to = id ? moved.get(id) : undefined - const from = id ? walls.get(id) : undefined - return Boolean( - to && - from && - (to.start[0] !== from.start[0] || - to.start[1] !== from.start[1] || - to.end[0] !== from.end[0] || - to.end[1] !== from.end[1]), - ) - } - const previousMoves = shifts(previous) - const nextMoves = shifts(next) - if (previousMoves !== nextMoves) { - const end = bridgedEnd(vertex, bridges) - // The stationary edge keeps the junction; the bridge joins it to the moved wall. - if (end) return previousMoves ? [end, vertex] : [vertex, end] - } - if (previous && next && previous !== next) { - const corner = intersectWallLines(current(previous), current(next)) - if (corner) return [corner] - } - const carrier = [previous, next].find((id) => id && moved.has(id)) - return [carrier ? carryAlongWall(vertex, walls.get(carrier)!, current(carrier)) : vertex] - } - - return (moved, bridges = []) => - surfaces.map(({ id, polygon, bindings }) => [ - id, - polygon.flatMap((vertex, index) => followVertex(vertex, bindings[index]!, moved, bridges)), - ]) -} - -function runSpaceDetection( +function syncSceneStructure( levelIds: string[], sceneStore: any, - editorStore: any, - nodes: any, - previousNodes: any, - previousRoomsByLevel: Map, -): void { - const { updateNodes } = sceneStore.getState() - const existingSpaces = editorStore.getState().spaces as Record - const nextSpaces: Record = {} - - for (const [spaceId, space] of Object.entries(existingSpaces)) { - if (!levelIds.includes(space.levelId)) { - nextSpaces[spaceId] = space - } - } - - for (const levelId of levelIds) { - const children = levelChildren(nodes, levelId) - const walls = children.filter( - (node: any): node is WallNode => node?.type === 'wall' && node.parentId === levelId, - ) - const slabs = children.filter((node: any) => node?.type === 'slab') - const ceilings = children.filter((node: any) => node?.type === 'ceiling') - const zones = children.filter((node: any) => node?.type === 'zone') - - const { wallUpdates, spaces, rooms } = detectSpacesFromWalls(levelId, walls) - - const changedWallUpdates = wallUpdates.filter((update) => { - const wall = nodes[update.wallId] - return wall && (wall.frontSide !== update.frontSide || wall.backSide !== update.backSide) - }) - - if (changedWallUpdates.length > 0) { - updateNodes( - changedWallUpdates.map((update) => ({ - id: update.wallId, - data: { - frontSide: update.frontSide, - backSide: update.backSide, - }, - })), - ) - } - - const levelNode = nodes[levelId] - const storeyHeight = - levelNode?.type === 'level' - ? getStoredLevelHeight(levelNode as LevelNode) - : DEFAULT_LEVEL_HEIGHT - const parsedSlabs: SlabNodeType[] = slabs.map((slab: any) => SlabNode.parse(slab)) - const parsedCeilings: CeilingNodeType[] = ceilings.map((ceiling: any) => - CeilingNode.parse(ceiling), - ) - const previousRooms = previousRoomsByLevel.get(levelId) ?? [] - const slabRooms = roomsEligibleForAutoSurface(previousRooms, rooms, parsedSlabs) - const ceilingRooms = roomsEligibleForAutoSurface(previousRooms, rooms, parsedCeilings) - const verticalPlacements = autoRoomVerticalPlacements( - spaces, - walls, - // A derived floor cannot be evidence for its own next elevation: that - // would lift unpinned walls, then lift the floor again on every pass. - parsedSlabs.filter((slab) => !slab.autoFromWalls), - nodes, - storeyHeight, - ) - const previousChildren = levelChildren(previousNodes, levelId) - const previousWalls = previousChildren.filter( - (node: any): node is WallNode => node?.type === 'wall' && node.parentId === levelId, - ) - const previousSlabs: SlabNodeType[] = previousChildren - .filter((node: any) => node?.type === 'slab') - .map((slab: any) => SlabNode.parse(slab)) - const previousLevelNode = previousNodes[levelId] - const previousStoreyHeight = - previousLevelNode?.type === 'level' - ? getStoredLevelHeight(previousLevelNode as LevelNode) - : DEFAULT_LEVEL_HEIGHT - const previousSpaces = detectSpacesFromWalls(levelId, previousWalls).spaces - const previousVerticalPlacements = autoRoomVerticalPlacements( - previousSpaces, - previousWalls, - previousSlabs.filter((slab) => !slab.autoFromWalls), - previousNodes, - previousStoreyHeight, - ) - const placementFor = (polygon: Array<[number, number]>) => - verticalPlacements.get(polygonSignature(polygon.map(pointFromTuple))) - const previousPlacementFor = (polygon: Array<[number, number]>) => - previousVerticalPlacements.get(polygonSignature(polygon.map(pointFromTuple))) - syncAutoSlabsForLevel( - levelId, - slabRooms.map((room) => room.polygon), - parsedSlabs, - sceneStore, - { - elevationForRoom: (polygon) => placementFor(polygon)?.slabElevation, - previousElevationForRoom: (polygon) => previousPlacementFor(polygon)?.slabElevation, - }, - ) - syncAutoCeilingsForLevel( - levelId, - ceilingRooms.map((room) => room.polygon), - parsedCeilings, - sceneStore, - { - storeyHeight, - ceilingClampBound: (polygon) => getCeilingClampBound(levelId, nodes, polygon), - heightForRoom: (polygon) => placementFor(polygon)?.ceilingHeight, - previousHeightForRoom: (polygon) => previousPlacementFor(polygon)?.ceilingHeight, - childPosition: (childId) => { - const child = nodes[childId] - return child && Array.isArray(child.position) - ? [child.position[0], child.position[2]] - : undefined - }, - }, - ) - const zonePlan = planAutoZonesForLevel( - spaces, - zones.map((zone: any) => ZoneNode.parse(zone)), - ) - if (zonePlan.update.length > 0) updateNodes(zonePlan.update) - - for (const space of spaces) { - nextSpaces[space.id] = space - } - previousRoomsByLevel.set(levelId, rooms) - } - - editorStore.getState().setSpaces(nextSpaces) -} - -function runIndexedSpaceDetection( - levelId: string, - topologyDelta: IndexedTopologyDelta, - sceneStore: any, - editorStore: any, - nodes: SceneNodes, previousNodes: SceneNodes, + mintId: StructureIdFactory, ) { - const { updateNodes } = sceneStore.getState() - const allRoomPolygons = topologyDelta.allCurrentRooms.map((room) => room.polygon) - const changedWallUpdates = topologyDelta.currentWalls - .map((wall) => ({ - wallId: wall.id, - ...resolveWallSurfaceSides(wall, allRoomPolygons), - })) - .filter((update) => { - const wall = nodes[update.wallId] - return ( - wall?.type === 'wall' && - (wall.frontSide !== update.frontSide || wall.backSide !== update.backSide) - ) - }) - if (changedWallUpdates.length > 0) { - updateNodes( - changedWallUpdates.map((update) => ({ - id: update.wallId, - data: { frontSide: update.frontSide, backSide: update.backSide }, - })), - ) - } - - const scopedRooms = [...topologyDelta.beforeRooms, ...topologyDelta.currentRooms].map((room) => ({ - polygon: room.polygon, - bbox: bboxOf(room.polygon), - })) - if (scopedRooms.length > 0) { - const unaffectedRooms = topologyDelta.allCurrentRooms - .filter((room) => !topologyDelta.currentRooms.includes(room)) - .map((room) => ({ polygon: room.polygon, bbox: bboxOf(room.polygon) })) - const currentChildren = levelChildren(nodes, levelId) - const allSlabs: SlabNodeType[] = currentChildren - .filter((node: any): node is SlabNodeType => node.type === 'slab') - .map((slab: SlabNodeType) => SlabNode.parse(slab)) - const allCeilings: CeilingNodeType[] = currentChildren - .filter((node: any): node is CeilingNodeType => node.type === 'ceiling') - .map((ceiling: CeilingNodeType) => CeilingNode.parse(ceiling)) - const touchesScopedRooms = (surface: RoomSurface) => { - const polygon = surface.polygon.map(pointFromTuple) - const bounded = { polygon, bbox: bboxOf(polygon) } - return ( - surfaceTouchesRooms(bounded, scopedRooms) && - (!surface.autoFromWalls || !surfaceTouchesRooms(bounded, unaffectedRooms)) - ) - } - const slabs = allSlabs.filter(touchesScopedRooms) - const ceilings = allCeilings.filter(touchesScopedRooms) - const slabRooms = roomsEligibleForAutoSurface( - topologyDelta.beforeRooms, - topologyDelta.currentRooms, - slabs, - ) - const ceilingRooms = roomsEligibleForAutoSurface( - topologyDelta.beforeRooms, - topologyDelta.currentRooms, - ceilings, - ) - const levelNode = nodes[levelId] - const storeyHeight = - levelNode?.type === 'level' - ? getStoredLevelHeight(levelNode as LevelNode) - : DEFAULT_LEVEL_HEIGHT - const currentSpaces = topologyDelta.currentRooms.map((room) => buildSpace(levelId, room)) - const verticalPlacements = autoRoomVerticalPlacements( - currentSpaces, - topologyDelta.currentWalls, - allSlabs.filter((slab) => !slab.autoFromWalls), - nodes, - storeyHeight, - ) - const previousChildren = levelChildren(previousNodes, levelId) - const previousSlabs: SlabNodeType[] = previousChildren - .filter((node: any): node is SlabNodeType => node.type === 'slab') - .map((slab: SlabNodeType) => SlabNode.parse(slab)) - const previousLevelNode = previousNodes[levelId] - const previousStoreyHeight = - previousLevelNode?.type === 'level' - ? getStoredLevelHeight(previousLevelNode as LevelNode) - : DEFAULT_LEVEL_HEIGHT - const previousSpaces = topologyDelta.beforeRooms.map((room) => buildSpace(levelId, room)) - const previousVerticalPlacements = autoRoomVerticalPlacements( - previousSpaces, - topologyDelta.previousWalls, - previousSlabs.filter((slab) => !slab.autoFromWalls), - previousNodes, - previousStoreyHeight, - ) - const placementFor = (polygon: Array<[number, number]>) => - verticalPlacements.get(polygonSignature(polygon.map(pointFromTuple))) - const previousPlacementFor = (polygon: Array<[number, number]>) => - previousVerticalPlacements.get(polygonSignature(polygon.map(pointFromTuple))) - - syncAutoSlabsForLevel( - levelId, - slabRooms.map((room) => room.polygon), - slabs, - sceneStore, - { - elevationForRoom: (polygon) => placementFor(polygon)?.slabElevation, - previousElevationForRoom: (polygon) => previousPlacementFor(polygon)?.slabElevation, - }, - allSlabs, - ) - syncAutoCeilingsForLevel( - levelId, - ceilingRooms.map((room) => room.polygon), - ceilings, - sceneStore, - { - storeyHeight, - ceilingClampBound: (polygon) => getCeilingClampBound(levelId, nodes, polygon), - heightForRoom: (polygon) => placementFor(polygon)?.ceilingHeight, - previousHeightForRoom: (polygon) => previousPlacementFor(polygon)?.ceilingHeight, - childPosition: (childId) => { - const child = nodes[childId] - return child && Array.isArray(child.position) - ? [child.position[0], child.position[2]] - : undefined - }, - }, - allCeilings, - ) - } - - const spaces = topologyDelta.allCurrentRooms.map((room) => buildSpace(levelId, room)) - const zones: ZoneNodeType[] = levelChildren(nodes, levelId) - .filter((node: any): node is ZoneNodeType => node.type === 'zone') - .map((zone: ZoneNodeType) => ZoneNode.parse(zone)) - const zonePlan = planAutoZonesForLevel(spaces, zones) - if (zonePlan.update.length > 0) updateNodes(zonePlan.update) + applyStructureReconciliation(sceneStore, { levelIds, previousNodes, mintId }) +} +function publishSpaces(levelIds: string[], nodes: SceneNodes, editorStore: any) { const existingSpaces = editorStore.getState().spaces as Record - const nextSpaces: Record = {} - for (const [spaceId, space] of Object.entries(existingSpaces)) { - if (space.levelId !== levelId) nextSpaces[spaceId] = space + const nextSpaces = Object.fromEntries( + Object.entries(existingSpaces).filter(([, space]) => !levelIds.includes(space.levelId)), + ) + for (const levelId of levelIds) { + const walls = levelChildren(nodes, levelId).filter( + (node: AnyNode): node is WallNode => node.type === 'wall', + ) + for (const space of detectSpacesFromWalls(levelId, walls).spaces) nextSpaces[space.id] = space } - for (const space of spaces) nextSpaces[space.id] = space editorStore.getState().setSpaces(nextSpaces) } -// Refcount of outstanding pause requests, matching the pauseSceneHistory -// pattern. The community editor flips this off while the AI is actively -// mutating the scene so the wall-driven auto slab/ceiling sync doesn't race -// `create_room`'s explicit slabs/ceilings (see plan -// `ai-pause-space-detection`). +// Batch writers pause intermediate topology; the final resume reconciles every +// level whose intent changed, including batches completed outside a store commit. let spaceDetectionPauseDepth = 0 +const resumeListeners = new Set<() => void>() -/** Pause the wall-driven auto slab/ceiling sync. Refcounted — pair with `resumeSpaceDetection`. */ +/** Pause structure reconciliation. Refcounted — pair with `resumeSpaceDetection`. */ export function pauseSpaceDetection(): void { spaceDetectionPauseDepth += 1 } -/** Resume the wall-driven auto slab/ceiling sync. No-op if not currently paused. */ +/** Resume structure reconciliation. No-op if not currently paused. */ export function resumeSpaceDetection(): void { if (spaceDetectionPauseDepth === 0) return spaceDetectionPauseDepth -= 1 + if (spaceDetectionPauseDepth === 0) for (const reconcile of resumeListeners) reconcile() } -/** True iff the wall-driven auto slab/ceiling sync is currently paused. */ +/** True iff structure reconciliation is currently paused. */ export function isSpaceDetectionPaused(): boolean { return spaceDetectionPauseDepth > 0 } +export function createRoomTopologyIndex() { + return new RoomTopologyIndex({ + detectRooms: extractRooms, + sampleWall: (wall) => sampleWallPointsForRoomDetection(wall).map(pointToTuple), + junctionTolerance: WALL_JUNCTION_TOLERANCE, + }) +} + export function initSpaceDetectionSync( sceneStore: any, editorStore: any, @@ -2686,22 +530,21 @@ export function initSpaceDetectionSync( // scene that merely loaded — rerunning on hydration resurrected auto slabs // the user had deleted in an earlier session. const initialNodes = sceneStore.getState().nodes - const previousRoomsByLevel = new Map() const topologyIndex = new RoomTopologyIndex({ detectRooms: extractRooms, sampleWall: (wall) => sampleWallPointsForRoomDetection(wall).map(pointToTuple), junctionTolerance: WALL_JUNCTION_TOLERANCE, + includeSeparators: false, }) let previousNodes = initialNodes let isProcessing = false + const mintId = options.mintId ?? generateId const adoptSceneBaseline = (nodes: SceneNodes) => { topologyIndex.rebuild(nodes) const roomsByLevel = detectedRoomsByLevel(nodes) - previousRoomsByLevel.clear() const spaces: Record = {} for (const [levelId, rooms] of roomsByLevel) { - previousRoomsByLevel.set(levelId, rooms) for (const room of rooms) { const space = buildSpace(levelId, room) spaces[space.id] = space @@ -2725,18 +568,17 @@ export function initSpaceDetectionSync( // boundary, and the paused writes would emit no replacement commit. const unsubscribe = sceneStore.subscribe((state: any) => { if (isProcessing) return - if (getSceneHistoryPauseDepth() > 0) return + if (isRestoringSceneHistory()) { + adoptSceneBaseline(state.nodes) + return + } + if (getSceneHistoryPauseDepth() > 0 || sceneStore.temporal.getState().isTracking === false) + return const nodes = state.nodes const candidateIds = activeSceneCommitNodeIds() - // Paused: roll the snapshot forward so we don't backfill (and re-duplicate) - // every paused change once detection resumes. Whatever the AI built while - // paused becomes the new baseline; only future changes will reconcile. - if (spaceDetectionPauseDepth > 0) { - adoptSceneBaseline(nodes) - return - } + if (spaceDetectionPauseDepth > 0) return const changedWalls = changedWallIdsByLevel(previousNodes, nodes, candidateIds) if (candidateIds && changedWalls.size > 0) { @@ -2745,17 +587,11 @@ export function initSpaceDetectionSync( isProcessing = true pauseSceneHistory(sceneStore) try { + const levels = [...new Set([...changedWalls.keys(), ...fallbackLevels])] + syncSceneStructure(levels, sceneStore, previousNodes, mintId) + publishSpaces(levels, sceneStore.getState().nodes, editorStore) for (const [levelId, wallIds] of changedWalls) { const topologyDelta = topologyIndex.applyWallDelta(levelId, wallIds, previousNodes, nodes) - runIndexedSpaceDetection( - levelId, - topologyDelta, - sceneStore, - editorStore, - nodes, - previousNodes, - ) - previousRoomsByLevel.set(levelId, topologyDelta.allCurrentRooms) options.onTopologyReconcile?.({ levelId, strategy: topologyDelta.strategy, @@ -2765,14 +601,6 @@ export function initSpaceDetectionSync( }) } if (fallbackLevels.size > 0) { - runSpaceDetection( - [...fallbackLevels], - sceneStore, - editorStore, - sceneStore.getState().nodes, - previousNodes, - previousRoomsByLevel, - ) const liveNodes = sceneStore.getState().nodes for (const levelId of fallbackLevels) topologyIndex.rebuildLevel(levelId, liveNodes) } @@ -2806,15 +634,6 @@ export function initSpaceDetectionSync( } if (levelsToUpdate.size === 0) { - if (candidateIds) { - previousNodes = nodes - return - } - const currentRoomsByLevel = detectedRoomsByLevel(nodes) - previousRoomsByLevel.clear() - for (const [levelId, rooms] of currentRoomsByLevel) { - previousRoomsByLevel.set(levelId, rooms) - } previousNodes = nodes return } @@ -2822,14 +641,8 @@ export function initSpaceDetectionSync( isProcessing = true pauseSceneHistory(sceneStore) try { - runSpaceDetection( - [...levelsToUpdate], - sceneStore, - editorStore, - nodes, - previousNodes, - previousRoomsByLevel, - ) + syncSceneStructure([...levelsToUpdate], sceneStore, previousNodes, mintId) + publishSpaces([...levelsToUpdate], sceneStore.getState().nodes, editorStore) } finally { resumeSceneHistory(sceneStore) const liveNodes = sceneStore.getState().nodes @@ -2839,9 +652,46 @@ export function initSpaceDetectionSync( } }) + const reconcilePaused = () => { + const capture = () => { + const { + nodes, + rootNodeIds = [], + collections = {}, + materials = {}, + installedPlugins = [], + } = sceneStore.getState() + return { nodes, rootNodeIds, collections, materials, installedPlugins } + } + const beforeCommit = capture() + const nodes = beforeCommit.nodes + const before = levelStructureSnapshots(previousNodes) + const after = levelStructureSnapshots(nodes) + const levels = [...new Set([...before.keys(), ...after.keys()])].filter( + (id) => before.get(id) !== after.get(id), + ) + if (!levels.length) return + isProcessing = true + pauseSceneHistory(sceneStore) + try { + syncSceneStructure(levels, sceneStore, previousNodes, mintId) + publishSpaces(levels, sceneStore.getState().nodes, editorStore) + for (const id of levels) topologyIndex.rebuildLevel(id, sceneStore.getState().nodes) + previousNodes = sceneStore.getState().nodes + } finally { + resumeSceneHistory(sceneStore) + isProcessing = false + } + // A pause may outlive the triggering commit; publish its completed derivation + // so collaboration receives the originator's ids even for AI/template batches. + notifySceneCommit({ origin: 'local', before: beforeCommit, current: capture() }) + } + resumeListeners.add(reconcilePaused) + return () => { unsubscribe() unsubscribeCommits() + resumeListeners.delete(reconcilePaused) } } diff --git a/packages/core/src/lib/structure-commit.ts b/packages/core/src/lib/structure-commit.ts new file mode 100644 index 0000000000..904c81b975 --- /dev/null +++ b/packages/core/src/lib/structure-commit.ts @@ -0,0 +1,84 @@ +import type { AnyNode, AnyNodeId } from '../schema' +import { DERIVED_WRITER_TOKEN, type DerivedWriteOptions } from '../store/derived-node-guard' +import { omitUndefined } from '../utils/omit-undefined' +import type { NodePatch, SceneNodes } from './structure-kernel' +import { reconcileSceneStructure, type StructureIdFactory } from './structure-reconcile' + +type StructureStoreLike = { + getState: () => { + nodes: SceneNodes + createNodes: ( + ops: { node: AnyNode; parentId?: AnyNodeId }[], + options?: DerivedWriteOptions, + ) => void + updateNodes: ( + updates: { id: AnyNodeId; data: Partial }[], + options?: DerivedWriteOptions, + ) => void + deleteNodes: (ids: AnyNodeId[], options?: DerivedWriteOptions) => void + } +} + +/** + * The only sanctioned writer of derived construction into a scene store. + * + * Runs the pure kernel over the requested levels and applies its patches while + * holding the derived-writer capability, so plates and auto ceilings reach the + * store through the guarded actions without any caller being able to forge the + * capability. Both the browser's commit subscriber (`initSpaceDetectionSync`) + * and the headless MCP bridge go through here. + * + * Callers own history framing: pause scene history around this call so the + * derived writes join the triggering edit's undo step + * (`wiki/architecture/space-detection.md`). + */ +export function applyStructureReconciliation( + sceneStore: StructureStoreLike, + options: { + levelIds?: string[] + previousNodes?: SceneNodes + mintId: StructureIdFactory + }, +): NodePatch[] { + const capability: DerivedWriteOptions = { derivedWriter: DERIVED_WRITER_TOKEN } + const { patches } = reconcileSceneStructure({ + levelIds: options.levelIds, + nodes: sceneStore.getState().nodes, + previousNodes: options.previousNodes, + mintId: options.mintId, + }) + const state = sceneStore.getState() + const creates = patches.flatMap((patch) => + patch.op === 'create' + ? [{ node: omitUndefined(patch.node), parentId: patch.node.parentId as AnyNodeId }] + : [], + ) + const updates = patches.flatMap((patch) => + patch.op === 'update' + ? [ + { + id: patch.id, + // Top-level undefined is the store's remove-field instruction, not a stored value. + data: Object.fromEntries( + Object.entries(patch.data).map(([key, value]) => [key, omitUndefined(value)]), + ), + }, + ] + : [], + ) + const deletes = patches.flatMap((patch) => (patch.op === 'delete' ? [patch.id] : [])) + if (creates.length) state.createNodes(creates, capability) + if (updates.length) state.updateNodes(updates, capability) + if (deletes.length) { + // Retiring a derived ceiling must not cascade into the children the kernel + // just re-parented off it. + const hosts = deletes.filter((id) => sceneStore.getState().nodes[id]?.type === 'ceiling') + if (hosts.length) + state.updateNodes( + hosts.map((id) => ({ id, data: { children: [] } as Partial })), + capability, + ) + state.deleteNodes(deletes, capability) + } + return patches +} diff --git a/packages/core/src/lib/structure-json.test.ts b/packages/core/src/lib/structure-json.test.ts new file mode 100644 index 0000000000..1db36d3996 --- /dev/null +++ b/packages/core/src/lib/structure-json.test.ts @@ -0,0 +1,341 @@ +import { expect, test } from 'bun:test' +import { createZone, divideZone, structureChangeBatch } from '../commands/structure' +import { type AnyNode, type AnyNodeId, CeilingNode, LevelNode, WallNode, ZoneNode } from '../schema' +import { subscribeSceneCommits } from '../store/history-control' +import useScene, { + applySceneOperationPatch, + clearSceneHistory, + type SceneOperationPatch, +} from '../store/use-scene' +import { migrateFloorPlates } from '../utils/floor-plate-migration' +import { migrateCeilingRoomLinks, migrateRoomZones } from '../utils/room-zone-migration' +import { buildFloorPlates } from './floor-plates' +import { initSpaceDetectionSync } from './space-detection' +import { applyStructureReconciliation } from './structure-commit' +import { type NodePatch, reconcileLevelStructure, type SceneNodes } from './structure-kernel' +import { reconcileSceneStructure } from './structure-reconcile' + +const levelId = 'level_json' +const polygon: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +function fixture() { + const walls = polygon.map((start, i) => + WallNode.parse({ + id: `wall_json_${i}`, + parentId: levelId, + start, + end: polygon[(i + 1) % polygon.length], + thickness: 0.2, + }), + ) + const level = LevelNode.parse({ id: levelId, children: walls.map((wall) => wall.id) }) + return Object.fromEntries([level, ...walls].map((node) => [node.id, node])) +} +function idFactory() { + let i = 0 + return (kind: string) => `${kind}_json_${++i}` +} +function expectJsonKeys(value: unknown) { + if (!value || typeof value !== 'object') return + for (const [key, child] of Object.entries(value)) { + expect(child, `undefined at ${key}`).not.toBeUndefined() + expectJsonKeys(child) + } +} +function expectCleanPatches(patches: NodePatch[]) { + for (const patch of patches) { + if (patch.op === 'create') expectJsonKeys(patch.node) + if (patch.op === 'update') expectJsonKeys(patch.data) + } +} + +test('close and Divide planners emit JSON-clean zones, ceilings, plates and updates', () => { + const nodes = fixture() + const mintId = idFactory() + const close = reconcileLevelStructure({ levelId, nodes, mintId }) + expect( + close.patches + .filter((p) => p.op === 'create') + .map((p) => p.node.type) + .sort(), + ).toEqual(['ceiling', 'slab', 'zone']) + expectCleanPatches(close.patches) + const initial = reconcileSceneStructure({ nodes, mintId }) + expectCleanPatches(initial.patches) + expectJsonKeys(initial.nodes) + const zone = Object.values(initial.nodes).find((node) => node.type === 'zone')! + const division = divideZone(initial.nodes, { + zoneId: zone.id, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }) + expect(division.conflicts).toBeUndefined() + expectCleanPatches(division.changes) + const separator = division.changes.find((patch) => patch.op === 'create')!.node + const divided = reconcileSceneStructure({ + nodes: { ...initial.nodes, [separator.id]: separator }, + mintId, + }) + expectCleanPatches(divided.patches) + expect(divided.patches.some((p) => p.op === 'update')).toBe(true) + expectJsonKeys(divided.nodes) + expect(Object.values(divided.nodes).filter((node) => node.type === 'zone')).toHaveLength(2) + expect(Object.values(divided.nodes).filter((node) => node.type === 'ceiling')).toHaveLength(2) +}) + +test('authored create planner strips absent intent fields before emitting a node', () => { + const level = LevelNode.parse({ id: levelId }) + const plan = createZone( + { [level.id]: level }, + { + levelId, + polygon, + mintId: idFactory(), + intent: { floor: null, wallMaterial: null, hasFloor: true, hasCeiling: true }, + }, + ) + expectCleanPatches(plan.changes) +}) + +test('plate builder cleans inherited optional and nested material keys without mutating its source', () => { + const nodes = fixture() + const mintId = idFactory() + const result = reconcileSceneStructure({ nodes, mintId }) + const snapshot = reconcileLevelStructure({ nodes: result.nodes, levelId, mintId }).snapshot + const source = Object.values(result.nodes).find((node) => node.type === 'slab')! + const template = { + ...source, + material: undefined, + slots: undefined, + metadata: { absent: undefined, keep: false }, + } + const plan = buildFloorPlates({ + levelId, + rooms: snapshot.rooms.map((room) => ({ + ...room, + id: room.zoneId, + zone: result.nodes[room.zoneId] as ZoneNode, + context: { revision: 0, walls: new Map(), wallFootprints: new Map() }, + })), + slabs: [template], + mintId: () => mintId('slab'), + }) + expect(plan.plates).toHaveLength(1) + expectJsonKeys(plan.plates) + expect(plan.plates[0]!.metadata).toEqual({ keep: false }) + expect(Object.hasOwn(template, 'material')).toBe(true) + expect(Object.hasOwn(template.metadata, 'absent')).toBe(true) +}) + +test('room, ceiling and floor migrations emit JSON-clean created and adopted nodes', () => { + const nodes = fixture() + const generic = ZoneNode.parse({ + id: 'zone_json_legacy', + parentId: levelId, + name: 'Kitchen', + polygon, + floor: { finish: undefined, elevation: 0.05 }, + wallMaterial: undefined, + hasFloor: undefined, + hasCeiling: undefined, + }) + const source = { ...nodes, [generic.id]: generic } + const rooms = migrateRoomZones(source) + expect(rooms.adoptedZoneIds).toEqual([generic.id]) + expectJsonKeys(rooms.nodes[generic.id]) + expectJsonKeys(migrateRoomZones(nodes).nodes) + const ceiling = CeilingNode.parse({ + id: 'ceiling_json_legacy', + parentId: levelId, + polygon, + autoFromWalls: true, + material: undefined, + materialPreset: undefined, + slots: undefined, + }) + const linked = migrateCeilingRoomLinks({ ...rooms.nodes, [ceiling.id]: ceiling }) + expect(linked.linkedCeilingIds).toEqual([ceiling.id]) + expectJsonKeys(linked.nodes[ceiling.id]) + const closed = reconcileSceneStructure({ nodes, mintId: idFactory() }).nodes + const plate = Object.values(closed).find((node) => node.type === 'slab')! + const { boundary: _, plateRole: _role, ...legacy } = plate + const plates = migrateFloorPlates({ + ...closed, + [plate.id]: { ...legacy, material: undefined, materialPreset: undefined }, + }) + expect(plates.plateIds).toHaveLength(1) + expectJsonKeys(plates.nodes) + expect(Object.hasOwn(generic, 'wallMaterial')).toBe(true) +}) + +function compensation(before: SceneNodes, after: SceneNodes): SceneOperationPatch { + const placements = (nodes: SceneNodes, other: SceneNodes) => + Object.values(nodes) + .filter((node) => !other[node.id]) + .map((node) => ({ + node, + position: (nodes[node.parentId!] as { children: AnyNodeId[] }).children.indexOf(node.id), + })) + return JSON.parse( + JSON.stringify({ + materialChanges: [], + nodeCreates: placements(after, before), + nodeDeletes: placements(before, after), + nodeUpdates: Object.values(after).flatMap((node) => { + const previous = before[node.id] + if (!previous) return [] + const data: Record = {} + const removeFields: string[] = [] + for (const key of new Set([...Object.keys(previous), ...Object.keys(node)])) { + if (key === 'children') continue + if (!Object.hasOwn(node, key)) removeFields.push(key) + else if ( + JSON.stringify(previous[key as keyof AnyNode]) !== + JSON.stringify(node[key as keyof AnyNode]) + ) + data[key] = node[key as keyof AnyNode] + } + return Object.keys(data).length || removeFields.length + ? [{ id: node.id, data, removeFields }] + : [] + }), + }), + ) +} + +for (const legacyUndefined of [false, true]) { + test(`JSON-recorded Divide compensation undoes and redoes with legacy undefined=${legacyUndefined}`, () => { + globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame ??= () => {} + const previous = useScene.getState() + useScene.setState({ + nodes: fixture(), + rootNodeIds: [levelId], + collections: {}, + materials: {}, + readOnly: false, + }) + clearSceneHistory() + const mintId = idFactory() + applyStructureReconciliation(useScene, { mintId }) + const before = useScene.getState().nodes + expectJsonKeys(before) + const zone = Object.values(before).find((node) => node.type === 'zone')! + const stop = initSpaceDetectionSync(useScene, { + getState: () => ({ spaces: {}, setSpaces: () => {} }), + }) + const origins: string[] = [] + const unsubscribe = subscribeSceneCommits((commit) => origins.push(commit.origin)) + try { + clearSceneHistory() + const division = divideZone(before, { + zoneId: zone.id, + cut: [ + [2, 0], + [2, 4], + ], + mintId, + }) + useScene.getState().applyNodeChanges(structureChangeBatch(division.changes)) + const after = useScene.getState().nodes + expectJsonKeys(after) + expect(origins).toEqual(['local']) + const undo = compensation(after, before) + const redo = compensation(before, after) + if (legacyUndefined) { + const dirty = { ...after } + for (const { node } of undo.nodeDeletes) { + if (node.type === 'zone') + dirty[node.id] = { + ...node, + floor: undefined, + wallMaterial: undefined, + hasFloor: undefined, + hasCeiling: undefined, + } + if (node.type === 'ceiling') + dirty[node.id] = { + ...node, + material: undefined, + materialPreset: undefined, + slots: undefined, + } + } + useScene.setState({ nodes: dirty }) + } + expect(applySceneOperationPatch(undo)).toBe(true) + expect(useScene.getState().nodes).toEqual(before) + expect(applySceneOperationPatch(redo)).toBe(true) + expect(useScene.getState().nodes).toEqual(after) + expect(origins.slice(-2)).toEqual(['host', 'host']) + } finally { + unsubscribe() + stop() + useScene.setState(previous) + clearSceneHistory() + } + }) +} + +test('compensation ignores undefined object keys on either side, recursively, but rejects real differences', () => { + const previous = useScene.getState() + const node = ZoneNode.parse({ + id: 'zone_json_equal', + name: 'Room', + polygon, + metadata: { nested: [{ keep: null }] }, + }) + const recorded = JSON.parse(JSON.stringify(node)) as ZoneNode + try { + for (const recordedUndefined of [false, true]) { + const extra = { + ...node, + floor: undefined, + metadata: { nested: [{ keep: null, absent: undefined }] }, + } + useScene.setState({ + nodes: { [node.id]: recordedUndefined ? recorded : extra }, + rootNodeIds: [node.id], + }) + clearSceneHistory() + expect( + applySceneOperationPatch({ + nodeCreates: [], + nodeUpdates: [], + materialChanges: [], + nodeDeletes: [{ node: recordedUndefined ? extra : recorded, position: 0 }], + }), + ).toBe(true) + } + for (const metadata of [ + { nested: [{ keep: false }] }, + { nested: [{}] }, + { nested: [{ keep: null }, {}] }, + ]) { + useScene.setState({ nodes: { [node.id]: { ...node, metadata } }, rootNodeIds: [node.id] }) + clearSceneHistory() + expect( + applySceneOperationPatch({ + nodeCreates: [], + nodeUpdates: [], + materialChanges: [], + nodeDeletes: [{ node: recorded, position: 0 }], + }), + ).toBe(false) + expect(useScene.getState().nodes[node.id as AnyNodeId]).toBeDefined() + } + } finally { + useScene.setState(previous) + clearSceneHistory() + } +}) diff --git a/packages/core/src/lib/structure-kernel.test.ts b/packages/core/src/lib/structure-kernel.test.ts new file mode 100644 index 0000000000..6d8e3581ae --- /dev/null +++ b/packages/core/src/lib/structure-kernel.test.ts @@ -0,0 +1,1014 @@ +import { describe, expect, spyOn, test } from 'bun:test' +import clipping from 'polygon-clipping' +import type { AnyNode } from '../schema' +import { + BuildingNode, + CeilingNode, + ItemNode, + LevelNode, + SeparatorNode, + SlabNode, + UnitNode, + WallNode, + ZoneNode, +} from '../schema' +import { clearLevelFootprintCaches } from './level-footprints' +import { area, containsPoint } from './polygon-boolean' +import { + createLevelStructurePreview, + type NodePatch, + reconcileLevelStructure, + type SceneNodes, +} from './structure-kernel' +import { deriveZoneQuantityReport } from './zone-quantities' + +const levelId = 'level_kernel' +const ring: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +function fixture() { + const walls = ring.map((start, i) => + WallNode.parse({ + id: `wall_${i}`, + parentId: levelId, + start, + end: ring[(i + 1) % 4], + thickness: 0.2, + }), + ) + const level = LevelNode.parse({ id: levelId, children: walls.map((wall) => wall.id) }) + return Object.fromEntries([level, ...walls].map((node) => [node.id, node])) +} +function apply(nodes: SceneNodes, patches: NodePatch[]): Record { + const result = { ...nodes } + for (const patch of patches) { + if (patch.op === 'delete') delete result[patch.id] + else if (patch.op === 'create') result[patch.node.id] = patch.node + else { + const node = { ...result[patch.id], ...patch.data } as AnyNode + for (const key of Object.keys(patch.data)) + if (patch.data[key as keyof typeof patch.data] === undefined) + delete (node as unknown as Record)[key] + result[patch.id] = node + } + } + return result +} +function run(nodes: SceneNodes) { + let count = 0 + const plan = reconcileLevelStructure({ + levelId, + nodes, + mintId: (kind) => { + let id: string + do { + id = `${kind}_${String(++count).padStart(4, '0')}` + } while (nodes[id]) + return id + }, + }) + return { ...plan, nodes: apply(nodes, plan.patches) } +} +function zones(nodes: SceneNodes) { + return Object.values(nodes).filter((node): node is ZoneNode => node.type === 'zone') +} +function ceilings(nodes: SceneNodes) { + return Object.values(nodes).filter((node): node is CeilingNode => node.type === 'ceiling') +} +function split(nodes: SceneNodes, x = 2, separator = false) { + const node = (separator ? SeparatorNode : WallNode).parse({ + id: separator ? 'separator_divider' : 'wall_divider', + parentId: levelId, + start: [x, 0], + end: [x, 4], + }) + return run({ ...nodes, [node.id]: node }) +} +function assertIdempotent(nodes: SceneNodes) { + expect(run(nodes).patches).toEqual([]) +} + +describe('structure kernel', () => { + test('close creates a room, clear ceiling and parent links; deterministic and idempotent', () => { + const nodes = fixture() + const bytes = JSON.stringify(nodes) + const result = run(nodes) + expect(run(Object.fromEntries(Object.entries(nodes).reverse()))).toEqual(result) + expect(JSON.stringify(nodes)).toBe(bytes) + expect(zones(result.nodes)).toHaveLength(1) + const zone = zones(result.nodes)[0]! + expect(zone).toMatchObject({ spaceRole: 'room', enclosureStatus: 'enclosed', seed: [4, 2] }) + const ceiling = ceilings(result.nodes)[0]! + expect(ceiling).toMatchObject({ zoneId: zone.id, boundary: 'auto', autoFromWalls: true }) + expect('height' in ceiling).toBe(false) + expect(area([{ outer: ceiling.polygon, holes: ceiling.holes }])).toBeCloseTo(7.8 * 3.8) + expect((result.nodes[levelId] as LevelNode).children).toEqual( + expect.arrayContaining([zone.id, ceiling.id]), + ) + assertIdempotent(result.nodes) + }) + test('split preserves seed identity, inherits intent, and merge keeps the largest overlap', () => { + const initial = run(fixture()).nodes + const zone = zones(initial)[0]! + initial[zone.id] = { + ...zone, + name: 'Kitchen', + seed: [1, 2], + floor: { elevation: 0.3, finish: 'oak' }, + wallMaterial: 'white', + hasFloor: false, + } + const divided = split(initial) + expect(zones(divided.nodes)).toHaveLength(2) + expect(divided.nodes[zone.id]).toMatchObject({ name: 'Kitchen', seed: [1, 2] }) + for (const room of zones(divided.nodes)) + expect(room).toMatchObject({ + floor: { elevation: 0.3, finish: 'oak' }, + wallMaterial: 'white', + hasFloor: false, + }) + const { wall_divider: _, ...merged } = divided.nodes + const result = run(merged) + const larger = zones(divided.nodes).find((room) => room.id !== zone.id)! + expect(zones(result.nodes).map((room) => room.id)).toEqual([larger.id]) + expect(result.events).toContainEqual({ + type: 'retired', + zoneId: zone.id, + survivorId: larger.id, + }) + assertIdempotent(divided.nodes) + assertIdempotent(result.nodes) + }) + test('open retains room data, removes its ceiling and quantities; reclose re-adopts', () => { + const initial = run(fixture()).nodes + const zone = zones(initial)[0]! + initial[zone.id] = { ...zone, name: 'Office', roomNumber: '42', floor: { finish: 'oak' } } + const { wall_3: closing, ...open } = initial + const opened = run(open) + expect(opened.nodes[zone.id]).toMatchObject({ + name: 'Office', + roomNumber: '42', + floor: { finish: 'oak' }, + enclosureStatus: 'open', + polygon: zone.polygon, + }) + expect(ceilings(opened.nodes)).toEqual([]) + const report = deriveZoneQuantityReport(opened.nodes[zone.id] as ZoneNode, opened.nodes) + expect(report.floorSurface.status).toBe('unavailable') + expect(report.wallSurface.status).toBe('unavailable') + expect(report.volume.status).toBe('unavailable') + const reclosed = run({ ...opened.nodes, [closing!.id]: closing! }) + expect(zones(reclosed.nodes).map((room) => room.id)).toEqual([zone.id]) + expect(reclosed.events).toContainEqual({ type: 'reopened', zoneId: zone.id }) + assertIdempotent(opened.nodes) + assertIdempotent(reclosed.nodes) + }) + test('nested loop creates an outer hole and a separate inner room', () => { + const nodes = fixture() + const hole: [number, number][] = [ + [3, 1], + [5, 1], + [5, 3], + [3, 3], + ] + for (let i = 0; i < 4; i++) { + const wall = WallNode.parse({ + id: `wall_inner_${i}`, + parentId: levelId, + start: hole[i], + end: hole[(i + 1) % 4], + thickness: 0.2, + }) + nodes[wall.id] = wall + } + const result = run(nodes) + expect(zones(result.nodes)).toHaveLength(2) + const outer = zones(result.nodes).find((room) => room.holes.length)! + expect(area([{ outer: outer.polygon, holes: outer.holes }])).toBe(28) + expect(containsPoint([{ outer: outer.polygon, holes: outer.holes }], outer.seed!)).toBe(true) + expect( + ceilings(result.nodes).find((ceiling) => ceiling.zoneId === outer.id)?.holes, + ).toHaveLength(1) + assertIdempotent(result.nodes) + }) + test('separator splits zones and ceilings', () => { + const result = split(run(fixture()).nodes, 2, true) + expect(zones(result.nodes)).toHaveLength(2) + expect(ceilings(result.nodes)).toHaveLength(2) + for (const zone of zones(result.nodes)) + expect(zone.boundarySeparatorIds).toEqual(['separator_divider']) + assertIdempotent(result.nodes) + }) + test('generic adoption uses IoU >= 0.9 including clear footprints; unrelated manual zones stay unchanged', () => { + for (const polygon of [ + ring, + [ + [0.1, 0.1], + [7.9, 0.1], + [7.9, 3.9], + [0.1, 3.9], + ] as [number, number][], + ]) { + const generic = ZoneNode.parse({ + id: 'zone_generic', + parentId: levelId, + name: 'Kitchen', + polygon, + }) + const unrelated = ZoneNode.parse({ + id: 'zone_garden', + parentId: levelId, + name: 'Garden', + polygon: [ + [20, 20], + [24, 20], + [24, 24], + [20, 24], + ], + }) + const result = run({ ...fixture(), [generic.id]: generic, [unrelated.id]: unrelated }) + expect(result.nodes[generic.id]).toMatchObject({ + spaceRole: 'room', + autoFromWalls: true, + name: 'Kitchen', + }) + expect(result.nodes[unrelated.id]).toBe(unrelated) + expect(result.events).toContainEqual({ type: 'adopted', zoneId: generic.id }) + } + }) + test('hasCeiling false deletes owned ceiling and never regenerates; manual ceiling stays untouched', () => { + const initial = run(fixture()).nodes + const zone = zones(initial)[0]! + const manual = CeilingNode.parse({ + id: 'ceiling_manual', + parentId: levelId, + zoneId: zone.id, + polygon: ring, + height: 2.1, + autoFromWalls: true, + }) + const result = run({ + ...initial, + [zone.id]: { ...zone, hasCeiling: false }, + [manual.id]: manual, + }) + expect(ceilings(result.nodes)).toEqual([manual]) + expect(result.nodes[manual.id]).toBe(manual) + assertIdempotent(result.nodes) + const divided = split(result.nodes) + expect(zones(divided.nodes).every((room) => room.hasCeiling === false)).toBe(true) + expect(ceilings(divided.nodes)).toEqual([manual]) + }) + test('children partition by position and union on merge, boundary child stays on survivor', () => { + const initial = run(fixture()).nodes + const zone = zones(initial)[0]! + initial[zone.id] = { ...zone, seed: [1, 2] } + const ceiling = ceilings(initial)[0]! + const items = [ + [1, 2], + [6, 2], + [2, 2], + ].map(([x, z], i) => + ItemNode.parse({ + id: `item_${i}`, + parentId: ceiling.id, + position: [x, 0, z], + asset: { + id: 'light', + name: 'Light', + category: 'lighting', + thumbnail: '', + src: '/light.glb', + }, + }), + ) + for (const item of items) initial[item.id] = item + initial[ceiling.id] = { ...ceiling, children: items.map((item) => item.id) } + const divided = split(initial) + const left = ceilings(divided.nodes).find((node) => node.zoneId === zone.id)! + expect(left.children).toEqual(['item_0', 'item_2']) + const right = ceilings(divided.nodes).find((node) => node.id !== left.id)! + expect(right.children).toEqual(['item_1']) + expect(divided.nodes.item_1?.parentId).toBe(right.id) + const { wall_divider: _, ...merged } = divided.nodes + const result = run(merged) + expect(ceilings(result.nodes)).toHaveLength(1) + expect(ceilings(result.nodes)[0]!.children).toEqual(items.map((item) => item.id)) + for (const item of items) expect(result.nodes[item.id]?.parentId).toBe(right.id) + assertIdempotent(result.nodes) + }) + test('wall sides classify exterior, partition, and two rooms on the same face', () => { + const result = split(run(fixture()).nodes) + expect(result.nodes.wall_0).toMatchObject({ frontSide: 'interior', backSide: 'exterior' }) + expect(result.nodes.wall_divider).toMatchObject({ frontSide: 'interior', backSide: 'interior' }) + expect( + result.snapshot.rooms + .flatMap((room) => room.spans) + .filter((span) => span.boundaryId === 'wall_0' && span.face === 'a'), + ).toHaveLength(2) + const nodes = fixture() + nodes.wall_0 = { ...(nodes.wall_0 as WallNode), start: [8, 0], end: [0, 0] } + expect(run(nodes).nodes.wall_0).toMatchObject({ frontSide: 'exterior', backSide: 'interior' }) + }) + test('overlap fallback moves a lost seed; equal overlap chooses the first canonical face', () => { + const nodes = run(fixture()).nodes + const zone = zones(nodes)[0]! + nodes[zone.id] = { ...zone, seed: [100, 100] } + const result = split(nodes, 4) + const kept = result.nodes[zone.id] as ZoneNode + expect(containsPoint([{ outer: kept.polygon, holes: kept.holes }], kept.seed!)).toBe(true) + expect(kept.polygon).toContainEqual([0, 0]) + assertIdempotent(result.nodes) + }) + test('a drawn zone covering most of a room is adopted; an overlapping loser is never deleted', () => { + const dining = ZoneNode.parse({ + id: 'zone_a_dining', + parentId: levelId, + name: 'Dining', + polygon: [ + [0, 0], + [5, 0], + [5, 4], + [0, 4], + ], + }) + const kitchen = ZoneNode.parse({ + id: 'zone_b_kitchen', + parentId: levelId, + name: 'Kitchen', + polygon: [ + [-0.3, -0.3], + [7, -0.3], + [7, 4.3], + [-0.3, 4.3], + ], + }) + const result = run({ ...fixture(), [dining.id]: dining, [kitchen.id]: kitchen }) + expect(result.nodes[kitchen.id]).toMatchObject({ spaceRole: 'room', name: 'Kitchen' }) + expect(result.nodes[dining.id]).toBe(dining) + expect(zones(result.nodes)).toHaveLength(2) + assertIdempotent(result.nodes) + }) + test('a drawn zone spanning a partition belongs to the room holding most of it', () => { + const zone = ZoneNode.parse({ + id: 'zone_open', + parentId: levelId, + name: 'Living', + polygon: ring, + }) + const result = split({ ...fixture(), [zone.id]: zone }, 5) + const living = result.nodes[zone.id] as ZoneNode + expect(living).toMatchObject({ spaceRole: 'room', autoFromWalls: true, name: 'Living' }) + expect(area([{ outer: living.polygon, holes: living.holes }])).toBeCloseTo(20) + expect(zones(result.nodes)).toHaveLength(2) + assertIdempotent(result.nodes) + }) + test('rooms the kernel creates are numbered; existing and cleared names are never touched', () => { + const closed = run(fixture()).nodes + const first = zones(closed)[0]! + expect(first.name).toBe('Room 1') + const cleared = { ...closed, [first.id]: { ...first, name: '' } } as SceneNodes + assertIdempotent(cleared) + const divided = split(cleared, 4) + const names = zones(divided.nodes) + .map((zone) => zone.name) + .sort() + // The seed side keeps its cleared name; the new side takes the lowest free number. + expect(names).toEqual(['', 'Room 1']) + const kitchen = split({ ...closed, [first.id]: { ...first, name: 'Kitchen' } } as SceneNodes, 4) + expect( + zones(kitchen.nodes) + .map((zone) => zone.name) + .sort(), + ).toEqual(['Kitchen', 'Room 1']) + }) + test('generic auto zones still need the adoption threshold', () => { + const generic = ZoneNode.parse({ + id: 'zone_generic_auto', + name: 'Analysis', + parentId: levelId, + polygon: [ + [0, 0], + [2, 0], + [2, 2], + [0, 2], + ], + seed: [1, 1], + autoFromWalls: true, + }) + const result = run({ ...fixture(), [generic.id]: generic }) + expect(result.nodes[generic.id]).toBe(generic) + expect(zones(result.nodes)).toHaveLength(2) + assertIdempotent(result.nodes) + }) + test('merge keeps the bedroom over a smaller closet; a unit containing only the closet follows the survivor', () => { + const nodes = fixture() + const left = ZoneNode.parse({ + id: 'zone_z_old', + parentId: levelId, + name: 'Bedroom', + floor: { finish: 'oak' }, + wallMaterial: 'white', + polygon: [ + [2, 0], + [8, 0], + [8, 4], + [2, 4], + ], + autoFromWalls: true, + spaceRole: 'room', + seed: [6, 2], + }) + const right = ZoneNode.parse({ + ...left, + id: 'zone_a_old', + name: 'Closet', + floor: { finish: 'tile' }, + wallMaterial: 'blue', + polygon: [ + [0, 0], + [2, 0], + [2, 4], + [0, 4], + ], + seed: [1, 2], + }) + const building = BuildingNode.parse({ id: 'building_test', children: [levelId, 'unit_test'] }) + nodes[building.id] = building + nodes[levelId] = { ...nodes[levelId], parentId: building.id } as LevelNode + const unit = UnitNode.parse({ id: 'unit_test', parentId: building.id, members: [right.id] }) + const result = run({ ...nodes, [left.id]: left, [right.id]: right, [unit.id]: unit }) + expect(zones(result.nodes).map((zone) => zone.id)).toEqual([left.id]) + expect(result.nodes[left.id]).toMatchObject({ + name: 'Bedroom', + seed: [6, 2], + floor: { finish: 'oak' }, + wallMaterial: 'white', + }) + expect(result.nodes[unit.id]).toMatchObject({ members: [left.id] }) + assertIdempotent(result.nodes) + }) + test('unlinked auto ceiling adopts a clear polygon and retains materials and authored holes on split', () => { + const initial = run(fixture()).nodes + const zone = zones(initial)[0]! + const ceiling = ceilings(initial)[0]! + initial[zone.id] = { + ...zone, + seed: [1, 2], + floor: { regions: [{ id: 'region_floor', finish: 'oak', polygon: ring }] }, + wallOverrides: [{ wallId: 'wall_0', face: 'a', finish: 'paint' }], + } + initial[ceiling.id] = { + ...ceiling, + zoneId: undefined, + materialPreset: 'plaster', + holes: [ + [ + [0.5, 0.5], + [1, 0.5], + [1, 1], + [0.5, 1], + ], + ], + holeMetadata: [{ source: 'manual' }], + } + const linked = run(initial) + expect(ceilings(linked.nodes)).toHaveLength(1) + expect(ceilings(linked.nodes)[0]!.id).toBe(ceiling.id) + const divided = split(linked.nodes) + for (const host of ceilings(divided.nodes)) expect(host.materialPreset).toBe('plaster') + expect(ceilings(divided.nodes).find((host) => host.zoneId === zone.id)!.holes).toHaveLength(1) + expect( + zones(divided.nodes).reduce( + (sum, room) => + sum + + area((room.floor?.regions ?? []).map((region) => ({ outer: region.polygon, holes: [] }))), + 0, + ), + ).toBe(32) + for (const room of zones(divided.nodes)) + expect(room.wallOverrides).toEqual([{ wallId: 'wall_0', face: 'a', finish: 'paint' }]) + assertIdempotent(divided.nodes) + }) + test('zone and ceiling previews change polygons without mutating the scene', () => { + const nodes = run(fixture()).nodes + const bytes = JSON.stringify(nodes) + const walls = Object.values(nodes) + .filter((node): node is WallNode => node.type === 'wall') + .map((wall) => ({ + ...wall, + start: [wall.start[0] * 2, wall.start[1]] as [number, number], + end: [wall.end[0] * 2, wall.end[1]] as [number, number], + })) + const updates = createLevelStructurePreview(levelId, nodes)(walls) + expect( + updates.some((patch) => nodes[patch.id]?.type === 'zone' && 'polygon' in patch.data), + ).toBe(true) + expect( + updates.some((patch) => nodes[patch.id]?.type === 'ceiling' && 'polygon' in patch.data), + ).toBe(true) + expect(JSON.stringify(nodes)).toBe(bytes) + }) + test('equal merge overlap breaks ties by lowest id independent of node order', () => { + const nodes = fixture() + for (const [id, x] of [ + ['zone_z', 0], + ['zone_a', 4], + ] as const) { + nodes[id] = ZoneNode.parse({ + id, + name: id, + parentId: levelId, + polygon: [ + [x, 0], + [x + 4, 0], + [x + 4, 4], + [x, 4], + ], + seed: [x + 2, 2], + autoFromWalls: true, + spaceRole: 'room', + }) + } + expect(zones(run(nodes).nodes).map((zone) => zone.id)).toEqual(['zone_a']) + expect(run(Object.fromEntries(Object.entries(nodes).reverse()))).toEqual(run(nodes)) + }) + test('explicit auto ceiling height and material survive a wall move', () => { + const nodes = run(fixture()).nodes + const ceiling = ceilings(nodes)[0]! + nodes[ceiling.id] = { ...ceiling, height: 2.1, materialPreset: 'plaster' } + for (const node of Object.values(nodes)) { + if (node.type === 'wall') + nodes[node.id] = { + ...node, + start: [node.start[0] * 1.2, node.start[1]], + end: [node.end[0] * 1.2, node.end[1]], + } + } + const result = run(nodes) + expect(result.nodes[ceiling.id]).toMatchObject({ + height: 2.1, + materialPreset: 'plaster', + boundary: 'auto', + }) + expect((result.nodes[ceiling.id] as CeilingNode).polygon).not.toEqual(ceiling.polygon) + assertIdempotent(result.nodes) + }) + test('all ceiling boundaries suppress minting at 60 percent clear-face coverage, including holes', () => { + for (const autoFromWalls of [false, true]) { + for (const coverage of [0.59, 0.6, 0.61]) { + const manual = CeilingNode.parse({ + id: 'ceiling_manual', + parentId: levelId, + autoFromWalls, + polygon: [ + [0.1, 0.1], + [7.9, 0.1], + [7.9, 3.9], + [0.1, 3.9], + ], + holes: [ + [ + [0.1, 0.1], + [0.1 + 7.8 * (1 - coverage), 0.1], + [0.1 + 7.8 * (1 - coverage), 3.9], + [0.1, 3.9], + ], + ], + }) + const result = run({ ...fixture(), [manual.id]: manual }) + expect(ceilings(result.nodes)).toHaveLength(coverage >= 0.6 ? 1 : 2) + expect(result.nodes[manual.id]).toBe(manual) + assertIdempotent(result.nodes) + } + } + }) + test('explicit manual and auto heights clamp downward as covering slabs change, never upward', () => { + const nodes = run(fixture()).nodes + const auto = ceilings(nodes)[0]! + const manual = CeilingNode.parse({ + id: 'ceiling_manual', + parentId: levelId, + polygon: [ + [20, 0], + [24, 0], + [24, 4], + [20, 4], + ], + height: 2.4, + }) + const slab = SlabNode.parse({ + id: 'slab_above', + parentId: 'level_above', + polygon: [ + [-1, -1], + [25, -1], + [25, 5], + [-1, 5], + ], + elevation: 0, + thickness: 0.5, + }) + const above = LevelNode.parse({ id: 'level_above', level: 1, children: [slab.id] }) + nodes[auto.id] = { ...auto, height: 2.4 } + nodes[manual.id] = manual + nodes[slab.id] = slab + nodes[above.id] = above + const result = run(nodes) + for (const id of [auto.id, manual.id]) + expect((result.nodes[id] as CeilingNode).height).toBeCloseTo(1.99) + result.nodes[slab.id] = { ...slab, thickness: 0.1 } + const raised = run(result.nodes) + for (const id of [auto.id, manual.id]) + expect((raised.nodes[id] as CeilingNode).height).toBeCloseTo(1.99) + assertIdempotent(raised.nodes) + }) + + test('a reusable preview never enumerates the source scene after drag start and resets removed walls', () => { + const nodes = run(fixture()).nodes + let scans = 0 + const scene = new Proxy(nodes, { + ownKeys(target) { + scans++ + return Reflect.ownKeys(target) + }, + }) + const preview = createLevelStructurePreview(levelId, scene) + expect(scans).toBe(1) + const walls = Object.values(nodes).filter((node): node is WallNode => node.type === 'wall') + const divider = WallNode.parse({ + id: 'wall_preview_divider', + parentId: levelId, + start: [2, 0], + end: [2, 4], + }) + expect( + preview([...walls, divider]).some( + (patch) => nodes[patch.id]?.type === 'zone' && 'polygon' in patch.data, + ), + ).toBe(true) + expect(preview(walls)).toEqual([]) + expect(scans).toBe(1) + assertIdempotent(nodes) + }) + test('an unlinked auto ceiling covering the face is adopted without minting a duplicate', () => { + const orphan = CeilingNode.parse({ + id: 'ceiling_orphan', + parentId: levelId, + boundary: 'auto', + polygon: [ + [-2, -2], + [10, -2], + [10, 6], + [-2, 6], + ], + height: 2.1, + }) + const result = run({ ...fixture(), [orphan.id]: orphan }) + expect(ceilings(result.nodes).map((ceiling) => ceiling.id)).toEqual([orphan.id]) + expect( + result.patches.some((patch) => patch.op === 'create' && patch.node.type === 'ceiling'), + ).toBe(false) + expect(result.nodes[orphan.id]).toMatchObject({ + height: 2.1, + zoneId: zones(result.nodes)[0]!.id, + }) + assertIdempotent(result.nodes) + }) + test('re-adopting a ceiling after zone deletion preserves its hosted child links', () => { + const nodes = run(fixture()).nodes + const zone = zones(nodes)[0]! + const ceiling = ceilings(nodes)[0]! + const item = ItemNode.parse({ + id: 'item_hosted', + parentId: ceiling.id, + position: [1, 0, 1], + asset: { id: 'light', name: 'Light', category: 'lighting', thumbnail: '', src: '/light.glb' }, + }) + nodes[item.id] = item + nodes[ceiling.id] = { ...ceiling, children: [item.id] } + delete nodes[zone.id] + const result = run(nodes) + expect(ceilings(result.nodes)).toHaveLength(1) + expect(result.nodes[ceiling.id]).toMatchObject({ + zoneId: zones(result.nodes)[0]!.id, + children: [item.id], + }) + expect(result.nodes[item.id]?.parentId).toBe(ceiling.id) + assertIdempotent(result.nodes) + }) +}) + +function plates(nodes: SceneNodes) { + return Object.values(nodes).filter( + (node): node is SlabNode => node.type === 'slab' && node.boundary === 'auto', + ) +} + +test.each([ + false, + true, +])('one full-footprint plate survives partition add/remove (separator=%s)', (separator) => { + const initial = run(fixture()).nodes + const plate = plates(initial)[0]! + expect(plate.polygon).toContainEqual([-0.1, -0.1]) + const divided = split(initial, 2, separator).nodes + expect(plates(divided)).toHaveLength(1) + expect(plates(divided)[0]).toMatchObject({ + id: plate.id, + zoneIds: zones(divided) + .map((zone) => zone.id) + .sort(), + }) + delete divided[separator ? 'separator_divider' : 'wall_divider'] + const merged = run(divided).nodes + expect(plates(merged).map((node) => node.id)).toEqual([plate.id]) + assertIdempotent(merged) +}) + +describe('ceiling outline', () => { + function divided(divider: Partial) { + const nodes = fixture() + const wall = WallNode.parse({ + id: 'wall_divider', + parentId: levelId, + start: [4, 0], + end: [4, 4], + thickness: 0.2, + ...divider, + }) + ;(nodes[levelId] as LevelNode).children.push(wall.id) + nodes[wall.id] = wall + return run(nodes).nodes + } + const reach = (nodes: SceneNodes) => + ceilings(nodes) + .map((ceiling) => ceiling.polygon.map(([x]) => x)) + .map((xs) => [Math.min(...xs), Math.max(...xs)]) + .sort((a, b) => a[0]! - b[0]!) + + test('stops at the faces of walls that reach it', () => { + const nodes = divided({}) + expect(reach(nodes)).toEqual([ + [0.1, 3.9], + [4.1, 7.9], + ]) + assertIdempotent(nodes) + }) + + test('spans a half wall to its reference line instead of leaving a slot above it', () => { + const nodes = divided({ height: 1 }) + expect(reach(nodes)).toEqual([ + [0.1, 4], + [4, 7.9], + ]) + assertIdempotent(nodes) + }) + + test('a room pinched in two by its walls keeps both parts and reloads without swapping ids', () => { + // Two 3×4 rooms joined by a 0.1 m neck that 0.2 m walls close entirely. + const outline: [number, number][] = [ + [0, 0], + [3, 0], + [3, 1.95], + [5, 1.95], + [5, 0], + [8, 0], + [8, 4], + [5, 4], + [5, 2.05], + [3, 2.05], + [3, 4], + [0, 4], + ] + const walls = outline.map((start, i) => + WallNode.parse({ + id: `wall_neck_${String(i).padStart(2, '0')}`, + parentId: levelId, + start, + end: outline[(i + 1) % outline.length], + thickness: 0.2, + }), + ) + const level = LevelNode.parse({ id: levelId, children: walls.map((wall) => wall.id) }) + const result = run(Object.fromEntries([level, ...walls].map((node) => [node.id, node]))).nodes + expect(zones(result)).toHaveLength(1) + const parts = ceilings(result) + expect(parts).toHaveLength(2) + for (const part of parts) + expect(area([{ outer: part.polygon, holes: part.holes }])).toBeCloseTo(2.8 * 3.8, 1) + assertIdempotent(result) + }) +}) + +test('elevation splits plates; retirement remaps both support and deck references', () => { + const initial = split(run(fixture()).nodes).nodes + const zone = zones(initial)[0]! + const original = plates(initial)[0]! + initial[zone.id] = { ...zone, floor: { elevation: 0.4 } } + const raised = run(initial).nodes + expect(plates(raised)).toHaveLength(2) + const high = plates(raised).find((plate) => plate.elevation === 0.4)! + expect(high.id).not.toBe(original.id) + const wall = raised.wall_0 as WallNode + raised.wall_0 = { ...wall, supportSlabId: high.id } + raised.stair_ref = { + id: 'stair_ref', + type: 'stair', + parentId: 'level_elsewhere', + deckSlabId: high.id, + } as AnyNode + raised[zone.id] = { ...raised[zone.id], floor: { elevation: 0.05 } } as ZoneNode + const merged = run(raised).nodes + expect(plates(merged).map((plate) => plate.id)).toEqual([original.id]) + expect(merged[high.id]).toBeUndefined() + expect(merged.wall_0).toMatchObject({ supportSlabId: original.id }) + expect((merged.stair_ref as { deckSlabId?: string }).deckSlabId).toBeUndefined() + assertIdempotent(merged) +}) + +test('a floorless inner room leaves a courtyard hole with walls supported', () => { + const nodes = fixture() + const hole: [number, number][] = [ + [3, 1], + [5, 1], + [5, 3], + [3, 3], + ] + hole.forEach((start, i) => { + const wall = WallNode.parse({ + id: `wall_void_${i}`, + parentId: levelId, + start, + end: hole[(i + 1) % 4], + thickness: 0.2, + }) + nodes[wall.id] = wall + }) + const initial = run(nodes).nodes + const inner = zones(initial).find((zone) => !zone.holes.length)! + initial[inner.id] = { ...inner, hasFloor: false } + const result = run(initial).nodes + expect(plates(result)).toHaveLength(1) + const plate = plates(result)[0]! + expect(plate.holes).toHaveLength(1) + expect(containsPoint([{ outer: plate.polygon, holes: plate.holes }], [4, 2])).toBe(false) + expect(containsPoint([{ outer: plate.polygon, holes: plate.holes }], [3, 2])).toBe(true) + assertIdempotent(result) +}) + +test('manual coverage never elects room floor ownership at runtime', () => { + for (const coverage of [0.59, 0.6, 0.61]) { + const manual = SlabNode.parse({ + id: 'slab_manual', + parentId: levelId, + polygon: [ + [0, 0], + [8 * coverage, 0], + [8 * coverage, 4], + [0, 4], + ], + }) + const result = run({ ...fixture(), [manual.id]: manual }).nodes + expect(plates(result)).toHaveLength(1) + expect(result[manual.id]).toBe(manual) + assertIdempotent(result) + } +}) + +test('manual and stair holes survive a plate merge with parallel metadata', () => { + const initial = split(run(fixture()).nodes).nodes + const plate = plates(initial)[0]! + initial[plate.id] = { + ...plate, + holes: [ + [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], + ], + ], + holeMetadata: [{ source: 'stair', stairId: 'stair_test' }], + } + delete initial.wall_divider + const result = run(initial).nodes + expect(plates(result)[0]).toMatchObject({ + holes: (initial[plate.id] as SlabNode).holes, + holeMetadata: [{ source: 'stair', stairId: 'stair_test' }], + }) + assertIdempotent(result) +}) + +test('kernel does not adopt legacy elevation intent; migration owns that conversion', () => { + const initial = fixture() + const legacy = SlabNode.parse({ + id: 'slab_legacy', + parentId: levelId, + polygon: ring, + autoFromWalls: true, + elevation: 0.4, + }) + initial[legacy.id] = legacy + const adopted = run(initial).nodes + expect(plates(adopted)).toHaveLength(1) + expect(plates(adopted)[0]).toMatchObject({ + id: legacy.id, + boundary: 'auto', + elevation: 0.05, + }) + expect(zones(adopted)[0]!.floor?.elevation).toBeUndefined() + const { wall_0: _, ...opened } = adopted + expect(plates(run(opened).nodes)).toHaveLength(0) + const { wall_0: _legacyWall, ...legacyOpened } = initial + expect(plates(run(legacyOpened).nodes)).toHaveLength(0) + const cover = SlabNode.parse({ id: 'slab_legacy_cover', parentId: levelId, polygon: ring }) + const zone = zones(adopted)[0]! + const suppressed = run({ + ...adopted, + [zone.id]: { ...zone, floor: { ...zone.floor, sourceSlabId: cover.id } }, + [cover.id]: cover, + }).nodes + expect(suppressed[legacy.id]).toBeUndefined() + expect(suppressed[cover.id]).toBe(cover) + assertIdempotent(adopted) +}) + +test('a failing plate union leaves existing level construction unchanged and warns once', () => { + const original = run(fixture()).nodes + clearLevelFootprintCaches() + const warning = spyOn(console, 'warn').mockImplementation(() => {}) + const clip = spyOn(clipping, 'union').mockImplementation(() => { + throw new Error('fixture union failure') + }) + try { + expect(run(original).patches).toEqual([]) + expect(run(original).patches).toEqual([]) + expect( + warning.mock.calls.filter( + ([message]) => message === '[floor plates] Keeping existing level construction', + ), + ).toHaveLength(1) + } finally { + clip.mockRestore() + warning.mockRestore() + } +}) + +test('connected rooms without authored elevation share the highest boundary base', () => { + const nodes = fixture() + nodes.wall_1 = { ...nodes.wall_1, supportOffset: 0.4 } as WallNode + const result = split(nodes, 4).nodes + expect(plates(result)).toHaveLength(1) + expect(plates(result)[0]!.elevation).toBe(0.45) + expect(plates(result)[0]!.zoneIds).toHaveLength(2) + expect(zones(result).every((zone) => zone.floor?.elevation === undefined)).toBe(true) + assertIdempotent(result) +}) + +test('a reconciliation without retired plates never spreads unrelated scene nodes', () => { + const initial = run(fixture()).nodes + let reads = 0 + const unrelated = { + id: 'item_elsewhere', + type: 'item', + parentId: 'level_other', + get metadata() { + reads++ + return {} + }, + } as AnyNode + const result = run({ ...initial, [unrelated.id]: unrelated }) + expect(reads).toBe(0) + expect(result.patches).toEqual([]) + expect(result.nodes[unrelated.id]).toBe(unrelated) +}) + +test('a wall move that bridges a junction keeps the room and adds the bridge to its boundary', () => { + const initial = run(fixture()).nodes + const zone = zones(initial)[0]! + // The east wall moved out to x = 9; a new bridge wall closes the corner it left. + const bridge = WallNode.parse({ + id: 'wall_bridge', + parentId: levelId, + start: [8, 0], + end: [9, 0], + thickness: 0.2, + }) + const level = initial[levelId] as LevelNode + const moved = { + ...initial, + wall_1: { ...initial.wall_1, start: [9, 0], end: [9, 4] } as WallNode, + wall_2: { ...initial.wall_2, start: [9, 4] } as WallNode, + [bridge.id]: bridge, + [levelId]: { ...level, children: [...level.children, bridge.id] } as LevelNode, + } + const result = run(moved).nodes + expect(zones(result).map((room) => room.id)).toEqual([zone.id]) + expect(zones(result)[0]!.polygon).toContainEqual([9, 0]) + expect(zones(result)[0]!.boundaryWallIds).toContain(bridge.id) + assertIdempotent(result) +}) diff --git a/packages/core/src/lib/structure-kernel.ts b/packages/core/src/lib/structure-kernel.ts new file mode 100644 index 0000000000..eb5838e1e5 --- /dev/null +++ b/packages/core/src/lib/structure-kernel.ts @@ -0,0 +1,854 @@ +import type { AnyNode, AnyNodeId, SeparatorNode, WallNode } from '../schema' +import { CeilingNode } from '../schema/nodes/ceiling' +import { SlabNode } from '../schema/nodes/slab' +import type { SurfacePaintRegion } from '../schema/nodes/surface-paint-region' +import { ZoneNode } from '../schema/nodes/zone' +import { + CEILING_CLAMP_MARGIN, + getCeilingClampBound, + getStoredLevelHeight, +} from '../services/storey' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { omitUndefined } from '../utils/omit-undefined' +import { absorbWallSeparators } from './absorb-wall-separators' +import { partitionCeilingChildren } from './ceiling-children' +import { resolvedFootprintPlane } from './floor-foundation-datum' +import { type FloorOpeningIndex, openingsForSurface } from './floor-opening-intent' +import { floorPlateId } from './floor-plate-id' +import { buildFloorPlates, warnPlateFailure } from './floor-plates' +import { floorRoomFaces } from './floor-room-faces' +import { type FloorStepOverride, remapFloorStepOverrideKeys } from './floor-step-finish' +import { replacementPlateFor } from './plate-reference' +import { + area, + containsPoint, + difference, + intersection, + type Polygon, + type Ring, + union, +} from './polygon-boolean' +import { polygonInteriorPoint } from './polygon-label' +import { pointFromTuple } from './room-graph' +import { roomNameAllocator } from './room-name' +import type { BoundarySpan } from './room-topology-index' +import { + adoptableFace, + compareAdoptionFits, + compareExistingRooms, + existingRoomFace, + type ZoneFaceFit, + zoneFaceFits, +} from './room-zone-adoption' + +export const ORPHAN_MERGE_COVERAGE_THRESHOLD = 0.6 + +export type SceneNodes = Readonly> +export type NodePatch = + | { op: 'create'; node: AnyNode } + | { op: 'update'; id: AnyNodeId; data: Partial } + | { op: 'delete'; id: AnyNodeId } +export type StructureEvent = { + type: 'created' | 'adopted' | 'opened' | 'reopened' | 'retired' + zoneId: string + survivorId?: string +} +export type StructureRoom = { + zoneId: ZoneNode['id'] + polygon: Ring + holes: Ring[] + clear: Polygon + spans: BoundarySpan[] +} +export type LevelStructureSnapshot = { levelId: string; rooms: StructureRoom[] } + +function compareIds(a: string, b: string) { + return a < b ? -1 : a > b ? 1 : 0 +} + +function footprint(node: { polygon: Ring; holes?: Ring[] }): Polygon { + return { outer: node.polygon, holes: node.holes ?? [] } +} + +/** Parts of a room's ceiling smaller than this (m²) are wall-junction slivers, not ceiling. */ +const MIN_CEILING_PART_AREA = 0.01 + +/** + * A room's ceiling outline: its face minus the plane-bound boundary walls, which + * rise to the storey plane above it. An explicit-height wall (half wall, parapet, + * a wall standing on a raised floor) may stop below the ceiling or start above it, + * so the ceiling spans it to the reference line, as legacy ceilings did, instead of + * leaving a slot; where such a wall does reach, it hides that strip. A legacy + * ceiling stored above the storey plane meets no wall and keeps its whole face. + * Every part is kept (walls can pinch a room in two); a room whose walls leave + * nothing, or whose boolean fails on acute miters, keeps its reference face rather + * than losing its ceiling. Largest part first. + */ +function ceilingSurface( + face: { polygon: Polygon; boundaryWallIds: readonly string[] }, + aboveStorey: boolean, + nodes: SceneNodes, + wallFootprints: ReadonlyMap, +): Polygon[] { + const reaching = (aboveStorey ? [] : face.boundaryWallIds).flatMap((id) => { + const wall = nodes[id] + return wall?.type === 'wall' && wall.height == null && wallFootprints.has(id) + ? [wallFootprints.get(id)!] + : [] + }) + const parts = (reaching.length ? difference(face.polygon, union(reaching)) : [face.polygon]) + .filter((part) => area([part]) >= MIN_CEILING_PART_AREA) + .sort((a, b) => area([b]) - area([a])) + return parts.length ? parts : [face.polygon] +} + +function iou(a: Polygon, b: Polygon) { + const overlap = area(intersection(a, b)) + const combined = area([a]) + area([b]) - overlap + return combined > 0 ? overlap / combined : 0 +} + +function equal(a: unknown, b: unknown) { + return JSON.stringify(a) === JSON.stringify(b) +} + +export function classifyWallSides( + wall: WallNode, + spans: readonly BoundarySpan[], +): Pick { + const boundary = spans.filter((span) => span.boundaryId === wall.id) + if (!boundary.length) return { frontSide: wall.frontSide, backSide: wall.backSide } + return { + frontSide: boundary.some((span) => span.face === 'a') ? 'interior' : 'exterior', + backSide: boundary.some((span) => span.face === 'b') ? 'interior' : 'exterior', + } +} + +export function reconcileLevelStructure( + input: Parameters[0], +): ReturnType { + try { + const absorbed = absorbWallSeparators(input.nodes, input.levelId, () => + input.mintId('separator'), + ) + const result = planLevelStructure({ ...input, nodes: absorbed.nodes }) + return { ...result, patches: [...absorbed.patches, ...result.patches] } + } catch (error) { + warnPlateFailure( + input.levelId, + Object.values(input.nodes) + .filter((node) => node.parentId === input.levelId) + .map((node) => node.id), + error, + ) + return { patches: [], snapshot: { levelId: input.levelId, rooms: [] }, events: [] } + } +} + +function planLevelStructure({ + levelId, + nodes, + mintId, + openingIndex, +}: { + levelId: string + nodes: SceneNodes + previousNodes?: SceneNodes + mintId: (kind: 'zone' | 'ceiling' | 'slab' | 'separator') => string + openingIndex?: FloorOpeningIndex +}): { patches: NodePatch[]; snapshot: LevelStructureSnapshot; events: StructureEvent[] } { + const snapshot: LevelStructureSnapshot = { levelId, rooms: [] } + const events: StructureEvent[] = [] + const level = nodes[levelId] + if (level?.type !== 'level') return { patches: [], snapshot, events } + const building = level.parentId ? nodes[level.parentId] : undefined + const units = + building?.type === 'building' + ? building.children.flatMap((id) => (nodes[id]?.type === 'unit' ? [nodes[id]!] : [])) + : [] + const children = Object.values(nodes) + .filter((node) => node.parentId === levelId) + .sort((a, b) => compareIds(a.id, b.id)) + const walls = children.filter((node): node is WallNode => node.type === 'wall') + const separators = children.filter((node): node is SeparatorNode => node.type === 'separator') + const allZones = children.filter((node): node is ZoneNode => node.type === 'zone') + const stacked = allZones.filter( + (zone) => zone.spaceRole === 'room' && zone.floor?.support === 'open', + ) + const zones = allZones.filter((zone) => !stacked.includes(zone)) + const allCeilings = children.filter((node): node is CeilingNode => node.type === 'ceiling') + const ceilings = allCeilings.filter((node) => node.boundary === 'auto') + const miters = calculateLevelMiters(walls) + const wallFootprints = new Map( + walls.map((wall) => [ + wall.id, + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ]), + ) + const faces = [...floorRoomFaces([...walls, ...separators])] + .sort((a, b) => compareIds(a.id, b.id)) + .map((room) => { + const polygon = { outer: room.referencePolygon, holes: room.holes } + const boundaryWallIds = [ + ...new Set( + room.spans + .filter((span) => span.kind === 'wall') + .map((span) => span.boundaryId as WallNode['id']), + ), + ].sort() + const clear = difference( + polygon, + union( + boundaryWallIds.flatMap((id) => + wallFootprints.has(id) ? [wallFootprints.get(id)!] : [], + ), + ), + ).sort((a, b) => area([b]) - area([a]))[0] ?? { outer: [], holes: [] } + return { + key: room.id, + polygon, + clear, + spans: room.spans, + boundaryWallIds, + boundarySeparatorIds: [ + ...new Set( + room.spans.filter((span) => span.kind === 'separator').map((span) => span.boundaryId), + ), + ].sort(), + } + }) + const next = new Map() + const deleted = new Set() + for (const child of children) + if ( + child.type === 'floor-opening' && + child.source === 'stair' && + child.ownerId && + nodes[child.ownerId]?.type !== 'stair' + ) + deleted.add(child.id) + const put = (node: AnyNode) => next.set(node.id, node) + const preferred = new Map() + const adoptionFits = new Map() + const scores = new Map() + for (const zone of zones) { + const overlaps = faces.map((face) => iou(footprint(zone), face.polygon)) + scores.set(zone.id, overlaps) + if (!(zone.autoFromWalls && zone.spaceRole === 'room')) { + // Hand-drawn zones follow the load migration's adoption rule. + const fit = adoptableFace(zoneFaceFits(zone, faces)) + if (fit) { + preferred.set(zone.id, fit.face) + adoptionFits.set(zone.id, fit) + } + continue + } + const face = existingRoomFace(zone, faces, overlaps) + if (face !== undefined) preferred.set(zone.id, face) + } + const sourceByFace = new Map() + const zoneByFace = new Map() + const retiredTo = new Map() + const nextRoomName = roomNameAllocator(allZones) + faces.forEach((face, index) => { + const rooms = zones + .filter((zone) => preferred.get(zone.id) === index && !adoptionFits.has(zone.id)) + .sort(compareExistingRooms(face)) + // An existing room keeps its face; a hand-drawn zone that loses stays as it is. + const drawn = zones + .filter((zone) => preferred.get(zone.id) === index && adoptionFits.has(zone.id)) + .map((zone) => ({ id: zone.id, zone, fit: adoptionFits.get(zone.id)! })) + .sort(compareAdoptionFits) + const survivor = rooms[0] ?? drawn[0]?.zone + const contenders = rooms + const source = + survivor ?? + zones + .filter( + (zone) => + zone.autoFromWalls && + zone.spaceRole === 'room' && + (scores.get(zone.id)?.[index] ?? 0) > 0, + ) + .sort( + (a, b) => scores.get(b.id)![index]! - scores.get(a.id)![index]! || compareIds(a.id, b.id), + )[0] + if (source) sourceByFace.set(index, source) + const zone = + survivor ?? + ZoneNode.parse({ + id: mintId('zone'), + parentId: levelId, + name: nextRoomName(), + polygon: face.polygon.outer, + floor: source?.floor, + wallMaterial: source?.wallMaterial, + floorStepFinish: source?.floorStepFinish, + floorStepOverrides: source?.floorStepOverrides, + floorEdgeFinish: source?.floorEdgeFinish, + hasFloor: source?.hasFloor, + hasCeiling: source?.hasCeiling, + }) + const seed = + zone.seed && containsPoint([face.polygon], zone.seed) + ? zone.seed + : polygonInteriorPoint( + { polygon: face.polygon.outer, holes: face.polygon.holes }, + !zone.seed, + ) + const updated: ZoneNode = { + ...zone, + spaceRole: 'room', + autoFromWalls: true, + enclosureStatus: 'enclosed', + seed, + polygon: face.polygon.outer, + holes: face.polygon.holes, + boundaryWallIds: face.boundaryWallIds, + boundarySeparatorIds: face.boundarySeparatorIds, + } + put(updated) + zoneByFace.set(index, updated) + snapshot.rooms.push({ + zoneId: updated.id, + polygon: updated.polygon, + holes: updated.holes, + clear: face.clear, + spans: face.spans, + }) + if (!survivor) events.push({ type: 'created', zoneId: zone.id }) + else if (!survivor.autoFromWalls || survivor.spaceRole !== 'room') + events.push({ type: 'adopted', zoneId: zone.id }) + else if (survivor.enclosureStatus === 'open') events.push({ type: 'reopened', zoneId: zone.id }) + for (const retired of contenders.slice(1)) { + deleted.add(retired.id) + retiredTo.set(retired.id, zone.id) + events.push({ type: 'retired', zoneId: retired.id, survivorId: zone.id }) + } + }) + for (const zone of zones) { + if (preferred.has(zone.id) || !zone.autoFromWalls || zone.spaceRole !== 'room') continue + put({ ...zone, enclosureStatus: 'open' }) + if (zone.enclosureStatus !== 'open') events.push({ type: 'opened', zoneId: zone.id }) + } + // Partition spatial intent with the same faces used for identity, including holes. + for (const [index, zone] of zoneByFace) { + const source = sourceByFace.get(index) + if (!source) continue + const face = faces[index]! + const contributors = zones.filter( + (candidate) => candidate.id === source.id || retiredTo.get(candidate.id) === zone.id, + ) + // Painted floor and ceiling parts follow the room: kept whole when it is + // unchanged, else each contributor's regions clipped to the new face. + const partition = (pick: (zone: ZoneNode) => SurfacePaintRegion[] | undefined) => + contributors.length === 1 && equal(footprint(source), face.polygon) + ? pick(source) + : contributors + .flatMap((candidate) => pick(candidate) ?? []) + .flatMap((region) => + intersection(region.polygon, face.polygon).map((part) => ({ + ...region, + polygon: part.outer, + })), + ) + const regions = partition((candidate) => candidate.floor?.regions) + const ceilingRegions = partition((candidate) => candidate.ceiling?.regions) + const overrides = contributors + .flatMap((candidate) => candidate.wallOverrides ?? []) + .filter((override) => + face.spans.some( + (span) => span.boundaryId === override.wallId && span.face === override.face, + ), + ) + if (contributors.some((candidate) => candidate.floor?.regions)) + zone.floor = { ...zone.floor, regions } + if (contributors.some((candidate) => candidate.ceiling?.regions)) + zone.ceiling = { ...zone.ceiling, regions: ceilingRegions } + if (contributors.some((candidate) => candidate.wallOverrides)) + zone.wallOverrides = [ + ...new Map( + overrides.map((override) => [`${override.wallId}:${override.face}`, override]), + ).values(), + ] + // Doorway step paint follows its doors into the merged room; the room's own + // paint wins a doorway both stored. + if ( + contributors.some((candidate) => candidate.id !== zone.id && candidate.floorStepOverrides) + ) { + const steps = new Map() + for (const candidate of [zone, ...contributors]) + for (const entry of candidate.floorStepOverrides ?? []) { + const id = `${entry.key}#${entry.step ?? ''}` + if (!steps.has(id)) steps.set(id, entry) + } + zone.floorStepOverrides = [...steps.values()] + } + } + // A step keyed by a room that merged into another now looks at the survivor. + if (retiredTo.size) + for (const candidate of allZones) { + if (deleted.has(candidate.id)) continue + const current = (next.get(candidate.id) ?? candidate) as ZoneNode + const remapped = remapFloorStepOverrideKeys(current, retiredTo) + if (remapped) put(remapped) + } + for (const zone of stacked) { + const clear = difference(footprint(zone), union([...wallFootprints.values()])).sort( + (a, b) => area([b]) - area([a]), + )[0] + if (!clear) continue + const index = faces.length + faces.push({ + key: `mezzanine:${zone.id}`, + polygon: footprint(zone), + clear, + spans: [], + boundaryWallIds: [], + boundarySeparatorIds: [], + }) + zoneByFace.set(index, zone) + sourceByFace.set(index, zone) + put(zone) + snapshot.rooms.push({ + zoneId: zone.id, + polygon: clear.outer, + holes: clear.holes, + clear, + spans: [], + }) + } + const context = { + revision: 0, + walls: new Map(walls.map((wall) => [wall.id, wall])), + wallFootprints, + } + const floorPlan = buildFloorPlates({ + levelId, + rooms: snapshot.rooms.map((room) => ({ + ...room, + id: room.zoneId, + context, + zone: next.get(room.zoneId) as ZoneNode, + })), + slabs: children + .filter((node): node is SlabNode => node.type === 'slab') + .map((slab) => SlabNode.parse(slab)), + mintId: (ids, component, role) => floorPlateId(levelId, role ?? 'base', ids, component), + retiredZones: retiredTo, + nodes, + openingIndex, + }) + for (const room of zoneByFace.values()) { + if (!room.floor?.footprint || room.floor.elevation === undefined) continue + const base = floorPlan.plates.find( + (plate) => plate.plateRole === 'base' && plate.zoneIds?.includes(room.id), + ) + if (!base || Math.abs(base.elevation - room.floor.elevation) > 1e-6) continue + const { elevation: _elevation, ...floor } = room.floor + room.floor = floor + put(room) + } + for (const plate of floorPlan.plates) put(plate) + for (const plate of floorPlan.retired) deleted.add(plate.id) + if (floorPlan.remap.size > 0) + for (const node of Object.values(nodes)) { + if (deleted.has(node.id)) continue + const updated = { ...(next.get(node.id) ?? node) } as AnyNode & { + supportSlabId?: string + deckSlabId?: string + } + let changed = false + for (const field of ['supportSlabId', 'deckSlabId'] as const) { + const host = updated[field] + if (!(host && floorPlan.remap.has(host))) continue + const replacement = replacementPlateFor( + updated, + field, + [ + ...floorPlan.plates, + ...children.filter( + (node): node is SlabNode => + node.type === 'slab' && node.boundary !== 'auto' && !node.autoFromWalls, + ), + ], + nodes, + ) + if (replacement) updated[field] = replacement + else delete updated[field] + changed = true + } + if (changed) put(updated as AnyNode) + } + const ceilingByFace = new Map() + const ceilingComponentsByFace = new Map() + const usedCeilings = new Set() + const ceilingOpenings = openingsForSurface(nodes, levelId, 'ceiling', openingIndex) + for (const [index, zone] of zoneByFace) { + if ( + zone.hasCeiling === false || + (zone.floor?.support === 'open' && + (zone.hasFloor === false || + resolvedFootprintPlane(nodes, zone, getStoredLevelHeight(level)) - + (zone.floor.elevation ?? 0.05) < + 2)) + ) + continue + const clear = faces[index]!.clear + const coversFace = (ceiling: CeilingNode) => + area(intersection(footprint(ceiling), clear)) / area([clear]) >= + ORPHAN_MERGE_COVERAGE_THRESHOLD + const source = sourceByFace.get(index) + const linked = + ceilings.find((ceiling) => ceiling.zoneId === zone.id && !usedCeilings.has(ceiling.id)) ?? + ceilings.find( + (ceiling) => + retiredTo.get(ceiling.zoneId ?? '') === zone.id && !usedCeilings.has(ceiling.id), + ) + if ( + !linked && + allCeilings.some((ceiling) => ceiling.boundary !== 'auto' && coversFace(ceiling)) + ) + continue + const existing = + linked ?? + ceilings.find( + (ceiling) => + !( + (ceiling.zoneId && allZones.some((zone) => zone.id === ceiling.zoneId)) || + usedCeilings.has(ceiling.id) + ) && coversFace(ceiling), + ) + const surface = ceilingSurface( + faces[index]!, + existing?.height !== undefined && existing.height > getStoredLevelHeight(level) + 1e-6, + nodes, + wallFootprints, + ) + if (surface[0]!.outer.length < 3) continue + const template = existing ?? ceilings.find((ceiling) => ceiling.zoneId === source?.id) + const ceiling = + existing ?? + CeilingNode.parse({ + id: mintId('ceiling'), + parentId: levelId, + name: `${zone.name || 'Room'} Ceiling`, + polygon: [], + material: template?.material, + materialPreset: template?.materialPreset, + slots: template?.slots, + visible: template?.visible, + }) + const updated: CeilingNode = { + ...ceiling, + zoneId: zone.id, + boundary: 'auto' as const, + autoFromWalls: true, + children: [] as CeilingNode['children'], + } + const cutouts = + zone.floor?.support === 'open' + ? [] + : union( + stacked.flatMap((mezzanine) => + mezzanine.hasFloor === false ? [] : intersection(footprint(mezzanine), surface), + ), + ) + const base = surface.map((part) => ({ + outer: part.outer, + holes: [ + ...part.holes, + ...cutouts.flatMap((cutout) => + area(intersection(cutout, part)) > 1e-6 ? [cutout.outer] : [], + ), + ], + })) + const authored = ceilingOpenings + .filter((opening) => !opening.legacyCeilingCuts) + .flatMap((opening) => + intersection(opening.polygon, surface).map((part) => ({ opening, part })), + ) + const parts = ( + authored.length ? difference(base, union(authored.map(({ part }) => part))) : base + ) + .filter((part) => area([part]) > 1e-6) + .sort((a, b) => area([b]) - area([a])) + const components = parts.map((part, componentIndex) => { + // Each part keeps the ceiling that already covers it, so a reload never swaps ids. + const reused = + [...new Set([ceiling, ...ceilings.filter((candidate) => candidate.zoneId === zone.id)])] + .filter((candidate) => !usedCeilings.has(candidate.id)) + .map((candidate) => ({ candidate, overlap: iou(footprint(candidate), part) })) + .filter(({ overlap }) => overlap > 0) + .sort((a, b) => b.overlap - a.overlap || a.candidate.id.localeCompare(b.candidate.id))[0] + ?.candidate ?? (componentIndex === 0 ? ceiling : undefined) + const component: CeilingNode = { + ...(reused ?? ceiling), + ...updated, + id: (reused?.id ?? mintId('ceiling')) as CeilingNode['id'], + polygon: part.outer, + holes: part.holes, + holeMetadata: part.holes.map((hole) => { + const match = authored.find(({ part: cut }) => area(intersection(hole, cut)) > 1e-6) + return match + ? { source: 'floor-opening' as const, openingId: match.opening.id } + : { source: 'room' as const } + }), + ...(authored.length + ? { openingIds: [...new Set(authored.map(({ opening }) => opening.id))].sort() } + : { openingIds: undefined }), + children: [], + } + for (const opening of ceilingOpenings) { + for (const hole of opening.legacyCeilingCuts?.[component.id] ?? []) { + if (component.holes.some((ring) => equal(ring, hole))) continue + component.holes.push(hole) + component.holeMetadata.push({ source: 'floor-opening', openingId: opening.id }) + component.openingIds = [...new Set([...(component.openingIds ?? []), opening.id])].sort() + } + } + usedCeilings.add(component.id) + put(component) + return component + }) + if (components.length) { + ceilingByFace.set(index, components[0]!) + ceilingComponentsByFace.set(index, components) + } + } + const detected = faces.map((face) => ({ + poly: face.polygon.outer.map(pointFromTuple), + holes: face.polygon.holes, + })) + for (const ceiling of ceilings) { + const related = [...ceilingByFace.keys()].filter((index) => { + const source = sourceByFace.get(index) + return ( + ceilingByFace.get(index)?.id === ceiling.id || + ceiling.zoneId === zoneByFace.get(index)?.id || + ceiling.zoneId === source?.id || + retiredTo.get(ceiling.zoneId ?? '') === zoneByFace.get(index)?.id || + (!ceiling.zoneId && area(intersection(footprint(ceiling), faces[index]!.polygon)) > 0) + ) + }) + const fallback = + related.find((index) => ceilingByFace.get(index)?.id === ceiling.id) ?? related[0] + const assignments = partitionCeilingChildren(ceiling, related, detected, fallback, (id) => { + const node = nodes[id] + return node && 'position' in node && Array.isArray(node.position) + ? [node.position[0], node.position[2]] + : undefined + }) + for (const [index, childIds] of assignments) { + const components = ceilingComponentsByFace.get(index) ?? [ceilingByFace.get(index)!] + const target = ceilingByFace.get(index)! + for (const id of childIds) { + const child = nodes[id] + if (!child) continue + const position = + 'position' in child && Array.isArray(child.position) + ? ([child.position[0], child.position[2]] as [number, number]) + : undefined + const host = + (position && + components.find((component) => containsPoint([footprint(component)], position))) || + target + host.children.push(id) + put({ ...child, parentId: host.id }) + } + const unchangedFace = + target.id === ceiling.id && + equal(target.polygon, ceiling.polygon) && + equal( + target.holes.filter((_, i) => target.holeMetadata[i]?.source === 'room'), + ceiling.holes.filter((_, i) => ceiling.holeMetadata[i]?.source === 'room'), + ) + for (const [holeIndex, hole] of ceiling.holes.entries()) { + const metadata = ceiling.holeMetadata[holeIndex] ?? { source: 'manual' as const } + if (metadata.source === 'room' || metadata.source === 'floor-opening') continue + if ( + metadata.source === 'manual' && + ceilingOpenings.some( + (opening) => + area(intersection(hole, opening.polygon)) >= + area([{ outer: hole, holes: [] }]) - 1e-6, + ) + ) + continue + for (const part of unchangedFace + ? [{ outer: hole }] + : intersection(hole, faces[index]!.clear)) { + const host = unchangedFace + ? { component: target, overlap: 1 } + : components + .map((component) => ({ + component, + overlap: area(intersection(part.outer, component.polygon)), + })) + .sort((a, b) => b.overlap - a.overlap)[0] + if (!host || host.overlap <= 1e-6) continue + if ( + host.component.holes.some( + (ring, i) => + equal(ring, part.outer) && equal(host.component.holeMetadata[i], metadata), + ) + ) + continue + host.component.holes.push(part.outer) + host.component.holeMetadata.push(metadata) + } + } + } + if (!usedCeilings.has(ceiling.id)) { + deleted.add(ceiling.id) + // Removing the derived host must not silently destroy authored contents. + if (!related.length) + for (const id of ceiling.children) if (nodes[id]) put({ ...nodes[id]!, parentId: levelId }) + } + } + for (const components of ceilingComponentsByFace.values()) + for (const ceiling of components) ceiling.children = [...new Set(ceiling.children)].sort() + const spans = snapshot.rooms.flatMap((room) => room.spans) + for (const wall of walls) + put({ ...wall, ...next.get(wall.id), ...classifyWallSides(wall, spans) } as WallNode) + for (const ceiling of allCeilings) { + if (deleted.has(ceiling.id)) continue + const updated = (next.get(ceiling.id) ?? ceiling) as CeilingNode + if (updated.height === undefined) continue + // A floor reassignment pins the ceiling's existing world height. Only a + // physical covering floor can subsequently clamp that authored height. + const height = Math.min( + updated.height, + getCeilingClampBound( + levelId, + nodes, + updated.polygon, + updated.metadata.floorReassignmentHeight === true + ? updated.height + CEILING_CLAMP_MARGIN + : undefined, + ), + ) + if (height !== updated.height) put({ ...updated, height }) + } + for (const node of units) { + if ( + node.type === 'unit' && + node.members.some((id) => deleted.has(id as AnyNodeId) || retiredTo.has(id)) + ) + put({ + ...node, + members: [...new Set(node.members.map((id) => retiredTo.get(id) ?? id))].filter( + (id) => !deleted.has(id as AnyNodeId) && (next.has(id) || !!nodes[id]), + ) as typeof node.members, + }) + } + const all = new Map( + [level, ...children, ...units].map((node) => [node.id, node]), + ) + for (const id of deleted) all.delete(id) + for (const [id, node] of next) if (!deleted.has(id as AnyNodeId)) all.set(id, node) + const parentIds = new Set([levelId]) + for (const [id, node] of next) { + if (node.parentId) parentIds.add(node.parentId) + if (nodes[id]?.parentId) parentIds.add(nodes[id]!.parentId!) + } + for (const parentId of parentIds) { + const parent = all.get(parentId) ?? nodes[parentId] + if (!(parent && 'children' in parent && Array.isArray(parent.children))) continue + const childIds = [ + ...parent.children.filter( + (id) => !deleted.has(id as AnyNodeId) && (all.get(id) ?? nodes[id])?.parentId === parentId, + ), + ] + const added = [...all.values()] + .filter((node) => node.parentId === parentId && !childIds.includes(node.id as never)) + .map((node) => node.id) + .sort() + if (added.length || !equal(childIds, parent.children)) + put({ ...parent, children: [...childIds, ...added] } as AnyNode) + } + const patches: NodePatch[] = [] + for (const [id, node] of [...next].sort(([a], [b]) => compareIds(a, b))) { + if (deleted.has(id as AnyNodeId)) continue + const before = nodes[id] + if (before) { + const data: Record = {} + for (const key of new Set([...Object.keys(before), ...Object.keys(node)])) { + const value = (node as unknown as Record)[key] + if (!equal((before as unknown as Record)[key], value)) + data[key] = omitUndefined(value) + } + if (Object.keys(data).length) + patches.push({ op: 'update', id: node.id, data: data as Partial }) + } else patches.push({ op: 'create', node: omitUndefined(node) }) + } + for (const id of [...deleted].sort()) patches.push({ op: 'delete', id }) + return { patches, snapshot, events } +} + +export function createLevelStructurePreview(levelId: string, nodes: SceneNodes) { + const level = nodes[levelId] + const draft: Record = {} + const sceneNodes = Object.values(nodes) + const stackLevels = new Set( + sceneNodes + .filter((node) => node.type === 'level' && node.parentId === level?.parentId) + .map((node) => node.id), + ) + const levelSlabs = new Set( + sceneNodes + .filter((node) => node.type === 'slab' && node.parentId === levelId) + .map((node) => node.id), + ) + // Everything the level's reconciliation reads, as the commit sees it: stack + // context for explicit-height clamps and floor planes, hosted children for + // partitioning, openings (doorway steps) and stairs landing on the level's + // plates. Only a copy of the level, so a large scene never slows a drag. + for (const node of sceneNodes) { + if ( + node.id === levelId || + node.parentId === levelId || + stackLevels.has(node.id) || + node.id === level?.parentId || + (node.type === 'slab' && node.parentId && stackLevels.has(node.parentId as AnyNodeId)) || + (node.type === 'unit' && node.parentId === level?.parentId) || + (node.type === 'stair' && node.deckSlabId && levelSlabs.has(node.deckSlabId)) + ) + draft[node.id] = node + } + for (const node of Object.values(draft)) { + if (node.type !== 'ceiling' && node.type !== 'wall' && node.type !== 'stair') continue + for (const id of node.children) if (nodes[id]) draft[id] = nodes[id]! + } + let wallIds = new Set( + Object.values(draft) + .filter((node): node is WallNode => node.type === 'wall' && node.parentId === levelId) + .map((node) => node.id), + ) + return (walls: readonly WallNode[]) => { + const currentIds = new Set() + for (const wall of walls) { + if (wall.parentId !== levelId) continue + currentIds.add(wall.id) + if (draft[wall.id] !== wall) draft[wall.id] = wall + } + // A level wall left out is one the gesture removes. + for (const id of wallIds) if (!currentIds.has(id)) delete draft[id] + wallIds = currentIds + let id = 0 + // The stored surfaces are the committed reconciliation; only what the + // moved walls reshape differs from them. + return reconcileLevelStructure({ + levelId, + nodes: draft, + mintId: (kind) => `${kind}_preview_${id++}`, + }).patches.flatMap((patch) => + patch.op === 'update' && + (nodes[patch.id]?.type === 'zone' || + nodes[patch.id]?.type === 'ceiling' || + nodes[patch.id]?.type === 'slab') + ? [patch] + : [], + ) + } +} diff --git a/packages/core/src/lib/structure-preview.test.ts b/packages/core/src/lib/structure-preview.test.ts new file mode 100644 index 0000000000..9cbe1e5aea --- /dev/null +++ b/packages/core/src/lib/structure-preview.test.ts @@ -0,0 +1,123 @@ +import { afterEach, expect, test } from 'bun:test' +import { createZone, setZoneIntent, structureChangeBatch } from '../commands/structure' +import type { StructurePlan } from '../commands/structure/types' +import { type AnyNode, BuildingNode, DoorNode, LevelNode, type WallNode } from '../schema' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { initSpaceDetectionSync } from './space-detection' +import { createLevelStructurePreview } from './structure-kernel' + +// A drag's live floors are the kernel run on the moved walls. They must be the +// floors its release commits, and only those: a room raised through a doorway +// (its plate steps down through the opening) next to the moved room keeps its +// stored shape while the other room's wall moves. + +globalThis.requestAnimationFrame ??= (callback) => { + callback(0) + return 0 +} +globalThis.cancelAnimationFrame ??= () => {} + +const LEVEL = 'level_preview' +let stop = () => {} +afterEach(() => { + stop() + clearSceneHistory() +}) + +const nodes = () => useScene.getState().nodes as Record +const apply = (plan: StructurePlan) => + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + +function seed() { + const level = LevelNode.parse({ id: LEVEL, parentId: 'building_preview' }) + const building = BuildingNode.parse({ id: 'building_preview', children: [level.id] }) + useScene.setState({ + nodes: { [level.id]: level, [building.id]: building }, + rootNodeIds: [building.id], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + readOnly: false, + }) + useScene.temporal.getState().resume() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) + let i = 0 + const mintId = (kind: string) => `${kind}_preview${++i}` + const room = (polygon: [number, number][]) => { + const plan = createZone(nodes(), { levelId: LEVEL, polygon, enclose: true, mintId }) + apply(plan) + return plan.zoneId + } + room([ + [0, 0], + [6, 0], + [6, 4], + [0, 4], + ]) + const raised = room([ + [-4, 0], + [0, 0], + [0, 4], + [-4, 4], + ]) + const shared = Object.values(nodes()).find( + (n): n is WallNode => n.type === 'wall' && n.start[0] === 0 && n.end[0] === 0, + )! + const door = DoorNode.parse({ parentId: shared.id, wallId: shared.id, position: [2, 0, 0] }) + useScene.getState().applyNodeChanges({ create: [{ node: door, parentId: shared.id }] }) + apply(setZoneIntent(nodes(), { zoneId: raised, patch: { floor: { elevation: 0.45 } } })) + clearSceneHistory() + return raised +} + +/** The east wall at x = 6 moved to x = 7, its neighbours' corners following. */ +function movedWalls(): WallNode[] { + const move = ([x, z]: [number, number]): [number, number] => [x === 6 ? 7 : x, z] + return Object.values(nodes()).flatMap((n) => + n.type === 'wall' && n.parentId === LEVEL + ? [{ ...n, start: move(n.start), end: move(n.end) }] + : [], + ) +} + +test('a live wall move previews exactly the floors its release commits, and no others', () => { + const raised = seed() + const raisedPlate = Object.values(nodes()).find( + (n) => n.type === 'slab' && n.plateRole === 'platform' && n.zoneIds?.includes(raised), + )! + // The doorway step is part of the raised plate's stored outline. + expect((raisedPlate as { polygon: unknown[] }).polygon.length).toBeGreaterThan(4) + + const before = nodes() + const preview = createLevelStructurePreview(LEVEL, before) + // Nothing moved yet: nothing to draw from a preview. + expect(preview(Object.values(before).filter((n): n is WallNode => n.type === 'wall'))).toEqual([]) + const walls = movedWalls() + const patches = preview(walls) + expect(patches.map((patch) => patch.id)).not.toContain(raisedPlate.id) + expect(patches.length).toBeGreaterThan(0) + + useScene.getState().updateNodes(walls.map(({ id, start, end }) => ({ id, data: { start, end } }))) + const after = nodes() + const json = (value: unknown) => JSON.stringify(value ?? null) + for (const patch of patches) { + if (patch.op !== 'update') continue + for (const [key, value] of Object.entries(patch.data)) + expect(`${patch.id}.${key}=${json(value)}`).toBe( + `${patch.id}.${key}=${json((after[patch.id] as Record)[key])}`, + ) + } + const reshaped = Object.keys(after).filter( + (id) => + ['slab', 'ceiling', 'zone'].includes(after[id]!.type) && + before[id] && + json((before[id] as { polygon?: unknown }).polygon) !== + json((after[id] as { polygon?: unknown }).polygon), + ) + expect(reshaped.sort()).toEqual( + patches + .filter((patch) => patch.op === 'update' && 'polygon' in patch.data) + .map((patch) => patch.id) + .sort(), + ) +}) diff --git a/packages/core/src/lib/structure-reconcile.test.ts b/packages/core/src/lib/structure-reconcile.test.ts new file mode 100644 index 0000000000..7cda5d3b6e --- /dev/null +++ b/packages/core/src/lib/structure-reconcile.test.ts @@ -0,0 +1,446 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import * as Bun from 'bun' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + CeilingNode, + LevelNode, + SeparatorNode, + SiteNode, + SlabNode, + WallNode, + type ZoneNode, +} from '../schema' +import { type SceneCommit, subscribeSceneCommits } from '../store/history-control' +import useLiveTerrain from '../store/use-live-terrain' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { initSpaceDetectionSync } from './space-detection' +import type { SceneNodes } from './structure-kernel' +import { reconcileSceneStructure, type StructureIdFactory } from './structure-reconcile' +import { createTerrainField } from './terrain-field' +import { commitTerrainField } from './terrain-source-persisted' + +const levelId = 'level_reconcile' +const polygon: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +function room(closed = true, id = levelId) { + const walls = polygon.map((start, index) => + WallNode.parse({ + id: `wall_${id}_${index}`, + parentId: id, + start, + end: polygon[(index + 1) % 4], + thickness: 0.2, + }), + ) + const kept = closed ? walls : walls.slice(0, 3) + const level = LevelNode.parse({ id, children: kept.map((wall) => wall.id) }) + return { walls, nodes: Object.fromEntries([level, ...kept].map((node) => [node.id, node])) } +} +function factory(start = 0): StructureIdFactory { + let sequence = start + return (kind) => `${kind}_authority_${sequence++}` +} +function ofKind(nodes: SceneNodes, kind: AnyNode['type']) { + return Object.values(nodes).filter((node) => node.type === kind) +} +function assertIdempotent(nodes: SceneNodes) { + const result = reconcileSceneStructure({ + nodes, + mintId: () => { + throw new Error('Idempotent reconciliation must not mint') + }, + }) + expect(result.patches).toEqual([]) + expect(result.events).toEqual([]) + expect(result.nodes).toBe(nodes) +} +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +let previousState: ReturnType +let stop = () => {} +let stopCommits = () => {} +beforeEach(() => { + previousState = useScene.getState() + globalThis.requestAnimationFrame = (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame = () => {} +}) +afterEach(() => { + stop() + stopCommits() + useLiveTerrain.getState().endAll() + useScene.setState(previousState, true) + clearSceneHistory() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf +}) +function watch(nodes: SceneNodes, mintId: StructureIdFactory) { + useScene.setState({ + nodes, + rootNodeIds: [levelId], + dirtyNodes: new Set(), + readOnly: false, + }) + clearSceneHistory() + const editor = { + spaces: {}, + setSpaces(spaces: Record) { + this.spaces = spaces + }, + } + stop = initSpaceDetectionSync(useScene, { getState: () => editor }, { mintId }) +} + +test('snapshot reconciliation and the closing store commit produce the identical graph and mint sequence', () => { + const open = room(false) + const closed = room().nodes + const before = JSON.stringify(closed) + const result = reconcileSceneStructure({ nodes: closed, mintId: factory() }) + expect( + ['zone', 'ceiling', 'slab'].map((kind) => + ofKind(result.nodes, kind as AnyNode['type']).map((node) => node.id), + ), + ).toEqual([['zone_authority_0'], ['ceiling_authority_1'], [expect.stringMatching(/^slab_/)]]) + watch(open.nodes, factory()) + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + useScene.getState().createNode(open.walls[3]!, levelId) + expect(useScene.getState().nodes).toEqual(result.nodes) + expect(commits).toHaveLength(1) + expect(commits[0]!.current.nodes).toEqual(result.nodes) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(open.nodes) + expect(JSON.stringify(closed)).toBe(before) + assertIdempotent(result.nodes) +}) + +test('all-level and explicit-level reconciliation use stable ordering and leave excluded levels alone', () => { + const nodes = { ...room(true, 'level_z').nodes, ...room(true, 'level_a').nodes } + const all = reconcileSceneStructure({ nodes, mintId: factory() }) + expect( + reconcileSceneStructure({ + nodes: Object.fromEntries(Object.entries(nodes).reverse()), + levelIds: ['level_z', 'level_a', 'level_z'], + mintId: factory(), + }), + ).toEqual(all) + const only = reconcileSceneStructure({ nodes, levelIds: ['level_a'], mintId: factory() }) + expect(ofKind(only.nodes, 'zone')).toHaveLength(1) + expect(only.nodes.level_z).toBe(nodes.level_z) + for (const wall of room(true, 'level_z').walls) expect(only.nodes[wall.id]).toBe(nodes[wall.id]) + assertIdempotent(all.nodes) +}) + +test('edit parity preserves deleted surfaces, persisted ceiling opt-out, and subsequent wall moves', () => { + const initial = reconcileSceneStructure({ nodes: room().nodes, mintId: factory() }).nodes + watch(initial, factory(3)) + const slab = ofKind(initial, 'slab')[0]! + const ceiling = ofKind(initial, 'ceiling')[0]! + const current = { ...initial } + delete current[slab.id] + delete current[ceiling.id] + const level = current[levelId] as LevelNode + current[levelId] = { + ...level, + children: level.children.filter((id) => id !== slab.id && id !== ceiling.id), + } + const result = reconcileSceneStructure({ + nodes: current, + previousNodes: initial, + mintId: factory(3), + }) + useScene.getState().deleteNodes([slab.id, ceiling.id]) + expect(useScene.getState().nodes).toEqual(result.nodes) + expect(ofKind(result.nodes, 'slab')).toEqual([]) + expect(ofKind(result.nodes, 'ceiling')).toEqual([]) + expect(ofKind(result.nodes, 'zone')[0]).toMatchObject({ hasCeiling: false }) + assertIdempotent(result.nodes) + const moved = { ...result.nodes } + const updates = ofKind(moved, 'wall').map((node) => { + const wall = node as WallNode + const data = { + start: [wall.start[0] * 1.1, wall.start[1]] as [number, number], + end: [wall.end[0] * 1.1, wall.end[1]] as [number, number], + } + moved[wall.id] = { ...wall, ...data } + return { id: wall.id, data } + }) + const next = reconcileSceneStructure({ + nodes: moved, + previousNodes: result.nodes, + mintId: factory(3), + }) + useScene.getState().updateNodes(updates) + expect(useScene.getState().nodes).toEqual(next.nodes) + assertIdempotent(next.nodes) +}) + +test('edit reconciliation preserves unrelated wall sides even with a serialized prior graph', () => { + const left = room() + const right = room(true, 'level_remote_ids') + const remoteWalls = right.walls.map((wall) => ({ + ...wall, + parentId: levelId, + start: [wall.start[0] + 20, wall.start[1]] as [number, number], + end: [wall.end[0] + 20, wall.end[1]] as [number, number], + })) + const previous: Record = { ...left.nodes } + for (const wall of remoteWalls) previous[wall.id] = wall + previous[levelId] = { + ...previous[levelId], + children: [...left.walls, ...remoteWalls].map((wall) => wall.id), + } as LevelNode + const current = { ...previous, [left.walls[0]!.id]: { ...left.walls[0]!, height: 3 } } + const result = reconcileSceneStructure({ + nodes: current, + previousNodes: previous, + mintId: factory(), + }) + for (const wall of remoteWalls) expect(result.nodes[wall.id]).toBe(previous[wall.id]) + expect( + reconcileSceneStructure({ + nodes: current, + previousNodes: structuredClone(previous), + mintId: factory(), + }), + ).toEqual(result) + expect( + result.patches.filter((patch) => patch.op === 'update' && current[patch.id]?.type === 'wall'), + ).toHaveLength(4) +}) + +test('partition removal preserves plate identity and slab host references in the store and pure result', () => { + const divider = WallNode.parse({ + id: 'wall_divider', + parentId: levelId, + start: [2, 0], + end: [2, 4], + }) + const initial = { + ...reconcileSceneStructure({ + nodes: { ...room().nodes, [divider.id]: divider }, + mintId: factory(), + }).nodes, + } + const smaller = ofKind(initial, 'slab')[0]! + const wallId = room().walls[0]!.id + initial[wallId] = { ...initial[wallId], supportSlabId: smaller.id } as WallNode + const current = { ...initial } + delete current[divider.id] + const level = current[levelId] as LevelNode + current[levelId] = { ...level, children: level.children.filter((id) => id !== divider.id) } + const result = reconcileSceneStructure({ + nodes: current, + previousNodes: initial, + mintId: factory(20), + }) + expect(result.nodes[smaller.id]).toBeDefined() + expect((result.nodes[wallId] as WallNode).supportSlabId).toBe(smaller.id) + watch(initial, factory(20)) + useScene.getState().deleteNode(divider.id) + expect(useScene.getState().nodes).toEqual(result.nodes) + assertIdempotent(result.nodes) +}) + +test('an explicitly associated manual floor suppresses a duplicate plate and opening a room retires its plate', () => { + const manual = SlabNode.parse({ id: 'slab_manual', parentId: levelId, polygon }) + const supplied = reconcileSceneStructure({ nodes: room().nodes, mintId: factory() }).nodes + const zone = Object.values(supplied).find((node) => node.type === 'zone') as ZoneNode + const covered = reconcileSceneStructure({ + nodes: { + ...supplied, + [zone.id]: { ...zone, floor: { ...zone.floor, sourceSlabId: manual.id } }, + [manual.id]: manual, + }, + mintId: factory(), + }) + expect(ofKind(covered.nodes, 'slab')).toEqual([manual]) + assertIdempotent(covered.nodes) + const initial = reconcileSceneStructure({ nodes: room().nodes, mintId: factory() }).nodes + const current = { ...initial } + delete current[`wall_${levelId}_3`] + const result = reconcileSceneStructure({ + nodes: current, + previousNodes: initial, + mintId: factory(3), + }) + expect(ofKind(result.nodes, 'slab')).toHaveLength(0) + expect(ofKind(result.nodes, 'ceiling')).toEqual([]) + expect(ofKind(result.nodes, 'zone')[0]).toMatchObject({ enclosureStatus: 'open' }) + assertIdempotent(result.nodes) +}) + +test('separator splits have two zones and ceilings but one shared plate', () => { + const separator = SeparatorNode.parse({ + id: 'separator_split', + parentId: levelId, + start: [2, 0], + end: [2, 4], + }) + const result = reconcileSceneStructure({ + nodes: { ...room().nodes, [separator.id]: separator }, + mintId: factory(), + }) + expect(ofKind(result.nodes, 'zone')).toHaveLength(2) + expect(ofKind(result.nodes, 'ceiling')).toHaveLength(2) + expect(ofKind(result.nodes, 'slab')).toHaveLength(1) + assertIdempotent(result.nodes) +}) + +test('zone elevation remains authoritative through wall support edits', () => { + for (const custom of [false, true]) { + const initial = { ...reconcileSceneStructure({ nodes: room().nodes, mintId: factory() }).nodes } + const slab = ofKind(initial, 'slab')[0] as SlabNode + if (custom) { + const zone = ofKind(initial, 'zone')[0]! + initial[zone.id] = { ...zone, floor: { elevation: 0.42 } } as AnyNode + } + const nodes = Object.fromEntries( + Object.values(initial).map((node) => [ + node.id, + node.type === 'wall' ? { ...node, supportOffset: 0.6 } : node, + ]), + ) + const result = reconcileSceneStructure({ nodes, previousNodes: initial, mintId: factory(3) }) + expect(result.nodes[slab.id]).toMatchObject({ plateRole: 'base', elevation: 0.65 }) + if (custom) + expect( + ofKind(result.nodes, 'slab').find( + (node) => node.type === 'slab' && node.plateRole === 'sunken', + ), + ).toMatchObject({ elevation: 0.42 }) + assertIdempotent(result.nodes) + } +}) + +test('upper slab holds its underside when its walls change, independent of requested level order', () => { + const upper = room(true, 'level_upper') + const nodes = { ...room().nodes, ...upper.nodes } + const building = BuildingNode.parse({ id: 'building_stack', children: [levelId, 'level_upper'] }) + nodes[building.id] = building + nodes[levelId] = { ...nodes[levelId], parentId: building.id } as LevelNode + nodes.level_upper = { ...nodes.level_upper, parentId: building.id, level: 1 } as LevelNode + for (const wall of upper.walls) nodes[wall.id] = { ...wall, supportOffset: 0.45 } + const ceiling = CeilingNode.parse({ + id: 'ceiling_manual', + parentId: levelId, + polygon, + height: 2.4, + }) + nodes[ceiling.id] = ceiling + const initial = { ...reconcileSceneStructure({ nodes, mintId: factory() }).nodes } + const slab = Object.values(initial).find( + (node): node is SlabNode => node.type === 'slab' && node.parentId === 'level_upper', + )! + initial[slab.id] = { ...slab, thickness: 0.5 } + const current = { ...initial } + for (const wall of upper.walls) + current[wall.id] = { ...current[wall.id], supportOffset: 0 } as WallNode + const result = reconcileSceneStructure({ + nodes: current, + previousNodes: initial, + levelIds: [levelId, 'level_upper'], + mintId: factory(10), + }) + expect((result.nodes[slab.id] as SlabNode).elevation).toBeCloseTo(0.5) + expect((result.nodes[ceiling.id] as CeilingNode).height).toBeCloseTo(2.4) + expect( + reconcileSceneStructure({ + nodes: current, + previousNodes: initial, + levelIds: ['level_upper', levelId], + mintId: factory(10), + }), + ).toEqual(result) + assertIdempotent(result.nodes) +}) + +test('plate elevation follows persisted terrain and ignores live uncommitted terrain', () => { + const nodes = room().nodes + const terrain = createTerrainField({ spacing: 8, cols: 3, rows: 3 }) + terrain.heights.fill(1000) + const site = SiteNode.parse({ + id: 'site_terrain', + terrain: commitTerrainField(terrain), + children: ['building_terrain'], + }) + const building = BuildingNode.parse({ + id: 'building_terrain', + parentId: site.id, + children: [levelId], + }) + nodes[site.id] = site + nodes[building.id] = building + nodes[levelId] = { ...nodes[levelId], parentId: building.id } as LevelNode + const expected = reconcileSceneStructure({ nodes, mintId: factory() }) + const live = createTerrainField({ spacing: 8, cols: 3, rows: 3 }) + live.heights.fill(2000) + useLiveTerrain.getState().begin(site.id, live) + expect(reconcileSceneStructure({ nodes, mintId: factory() })).toEqual(expected) + expect((ofKind(expected.nodes, 'slab')[0] as SlabNode).elevation).toBe(10.05) + const initialPlate = ofKind(expected.nodes, 'slab')[0] as SlabNode + const sculpted = { ...expected.nodes, [site.id]: { ...site, terrain: commitTerrainField(live) } } + const updated = reconcileSceneStructure({ + nodes: sculpted, + previousNodes: expected.nodes, + mintId: factory(20), + }) + expect(updated.nodes[initialPlate.id]).toMatchObject({ elevation: 20.05 }) + expect( + (ofKind(updated.nodes, 'zone')[0] as AnyNode & { floor?: { elevation?: number } }).floor + ?.elevation, + ).toBeUndefined() + assertIdempotent(updated.nodes) +}) + +test('scene-migrations exports the orchestrator through a clean Node bundle', async () => { + const loaded = new Set() + const build = await Bun.build({ + entrypoints: [new URL('../utils/scene-migrations.ts', import.meta.url).pathname], + target: 'node', + plugins: [ + { + name: 'record-imports', + setup(builder) { + builder.onLoad({ filter: /\.[tj]sx?$/ }, ({ path }) => { + loaded.add(path) + return + }) + }, + }, + ], + }) + expect(build.success).toBe(true) + const source = await build.outputs[0]!.text() + const fixture = JSON.stringify(room().nodes) + const probe = `${source}\nlet i = 0; const result = reconcileSceneStructure({ nodes: ${fixture}, mintId: kind => kind + '_probe_' + i++ }); console.log(JSON.stringify(Object.values(result.nodes).map(node => node.type).sort()));` + const result = Bun.spawnSync(['node', '--input-type=module'], { + stdin: Buffer.from(probe), + stdout: 'pipe', + stderr: 'pipe', + }) + expect(result.stderr.toString()).toBe('') + expect(result.exitCode).toBe(0) + expect(JSON.parse(result.stdout.toString())).toEqual([ + 'ceiling', + 'level', + 'slab', + 'wall', + 'wall', + 'wall', + 'wall', + 'zone', + ]) + expect( + [...loaded].filter((path) => /\/store\/|\/node_modules\/(react|zustand|three)\//.test(path)), + ).toEqual([]) +}) diff --git a/packages/core/src/lib/structure-reconcile.ts b/packages/core/src/lib/structure-reconcile.ts new file mode 100644 index 0000000000..a92d70a268 --- /dev/null +++ b/packages/core/src/lib/structure-reconcile.ts @@ -0,0 +1,283 @@ +import type { AnyNode, AnyNodeId } from '../schema' +import { floorFootprintSupportClass } from './floor-foundation-datum' +import { createFloorOpeningIndex } from './floor-opening-intent' +import { + type ExtractedRoom, + extractRooms, + pointToTuple, + sampleWallPointsForRoomDetection, + WALL_JUNCTION_TOLERANCE, +} from './room-graph' +import { RoomTopologyIndex } from './room-topology-index' +import { + type NodePatch, + reconcileLevelStructure, + type SceneNodes, + type StructureEvent, +} from './structure-kernel' + +export type StructureIdFactory = (kind: 'zone' | 'ceiling' | 'slab' | 'separator') => string +export type SceneStructureInput = { + nodes: SceneNodes + levelIds?: string[] + mintId: StructureIdFactory + previousNodes?: SceneNodes +} +export type SceneStructureResult = { + nodes: SceneNodes + patches: NodePatch[] + events: StructureEvent[] +} + +function levelChildren(nodes: SceneNodes, levelId: string) { + return Object.values(nodes) + .filter((node) => node.parentId === levelId) + .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) +} + +function applyPatch(nodes: Record, patch: NodePatch) { + if (patch.op === 'delete') delete nodes[patch.id] + else if (patch.op === 'create') nodes[patch.node.id] = patch.node + else { + const node = { ...nodes[patch.id], ...patch.data } as AnyNode + for (const [key, value] of Object.entries(patch.data)) + if (value === undefined) delete (node as unknown as Record)[key] + nodes[patch.id] = node + } +} + +function affectedWalls( + levelId: string, + nodes: SceneNodes, + previousNodes: SceneNodes, + children: AnyNode[], + previousChildren: AnyNode[], +) { + const changed = new Set( + [...children, ...previousChildren] + .filter( + (node) => + node.type === 'wall' && + JSON.stringify(nodes[node.id]) !== JSON.stringify(previousNodes[node.id]), + ) + .map((node) => node.id), + ) + if (!changed.size) return + const index = new RoomTopologyIndex({ + detectRooms: extractRooms, + sampleWall: (wall) => sampleWallPointsForRoomDetection(wall).map(pointToTuple), + junctionTolerance: WALL_JUNCTION_TOLERANCE, + includeSeparators: false, + }) + return new Set(index.applyWallDelta(levelId, changed, previousNodes, nodes).examinedWallIds) +} + +function supportInputsChanged(before: SceneNodes, after: SceneNodes) { + for (const id of new Set([...Object.keys(before), ...Object.keys(after)])) { + const old = before[id], + next = after[id] + if (old === next) continue + if (old?.type === 'slab' || next?.type === 'slab') { + if (old?.type !== 'slab' || next?.type !== 'slab') return true + if (old.plateRole === 'base' || next.plateRole === 'base') { + if (old.plateRole !== next.plateRole) return true + if ( + old.parentId !== next.parentId || + JSON.stringify([old.polygon, old.holes, old.zoneIds]) !== + JSON.stringify([next.polygon, next.holes, next.zoneIds]) + ) + return true + } + } + if ( + (old?.type === 'zone' && old.spaceRole === 'room') !== + (next?.type === 'zone' && next.spaceRole === 'room') + ) + return true + if (old?.type === 'level' && next?.type === 'level') + if (old.level !== next.level || old.parentId !== next.parentId) return true + } + return false +} + +export function reconcileSceneStructure({ + nodes, + levelIds, + mintId, + previousNodes, +}: SceneStructureInput): SceneStructureResult { + const draft = { ...nodes } + const events: StructureEvent[] = [] + const openingIndex = createFloorOpeningIndex(nodes) + // Reconcile covering slabs before the ceilings on the level below them. + const levels = [ + ...new Set( + levelIds ?? + Object.values(nodes) + .filter((node) => node.type === 'level') + .map((node) => node.id), + ), + ].sort( + (a, b) => + (nodes[b]?.type === 'level' ? nodes[b].level : 0) - + (nodes[a]?.type === 'level' ? nodes[a].level : 0) || (a < b ? -1 : a > b ? 1 : 0), + ) + const reconcileLevel = (levelId: string) => { + if (draft[levelId]?.type !== 'level') return + const children = levelChildren(draft, levelId) + const previousChildren = previousNodes ? levelChildren(previousNodes, levelId) : [] + for (const surface of previousChildren) { + if ( + (surface.type !== 'ceiling' && surface.type !== 'slab') || + surface.boundary !== 'auto' || + draft[surface.id] + ) + continue + const ids = surface.type === 'ceiling' ? [surface.zoneId] : (surface.zoneIds ?? []) + for (const id of ids) { + const zone = id ? draft[id] : undefined + if (zone?.type === 'zone') + draft[zone.id] = { + ...zone, + [surface.type === 'ceiling' ? 'hasCeiling' : 'hasFloor']: false, + } + } + } + const wallIds = previousNodes + ? affectedWalls(levelId, nodes, previousNodes, children, previousChildren) + : undefined + const structure = reconcileLevelStructure({ + levelId, + nodes: draft, + mintId, + previousNodes, + openingIndex, + }) + for (const patch of structure.patches) { + // Preserve the indexed edit's wall scope: remote legacy walls must not + // become a full-level rebuild merely because their sides were unclassified. + if ( + patch.op === 'update' && + wallIds && + draft[patch.id]?.type === 'wall' && + !wallIds.has(patch.id) + ) + continue + applyPatch(draft, patch) + } + events.push(...structure.events) + } + for (const levelId of levels) reconcileLevel(levelId) + const flipped = new Set() + if (supportInputsChanged(nodes, draft)) { + const supportClasses = new Map( + Object.values(nodes).flatMap((node) => + node.type === 'slab' && node.plateRole === 'base' + ? [[node.id, floorFootprintSupportClass(nodes, node)] as const] + : [], + ), + ) + for (const node of Object.values(draft)) + if ( + node.type === 'slab' && + node.plateRole === 'base' && + floorFootprintSupportClass(draft, node) !== + (supportClasses.get(node.id) ?? 'ground-bearing') + ) + flipped.add(node.parentId) + } + if (flipped.size) { + for (const levelId of [...flipped]) { + const index = levels.indexOf(levelId!) + if (index >= 0 && index + 1 < levels.length) flipped.add(levels[index + 1]!) + } + for (const levelId of levels) if (flipped.has(levelId)) reconcileLevel(levelId) + } + const legacyCutsBySurface = new Map< + string, + Map< + string, + { hole: [number, number][]; metadata: { source: 'floor-opening'; openingId: string } } + > + >() + for (const node of Object.values(draft)) { + if (node.type !== 'floor-opening') continue + for (const [surfaceId, cuts] of Object.entries({ + ...node.legacyPlateCuts, + ...node.legacyCeilingCuts, + })) + for (const hole of cuts) { + const byPolygon = legacyCutsBySurface.get(surfaceId) ?? new Map() + const key = JSON.stringify(hole) + const existing = byPolygon.get(key) + if (!existing || node.id < existing.metadata.openingId) + byPolygon.set(key, { hole, metadata: { source: 'floor-opening', openingId: node.id } }) + legacyCutsBySurface.set(surfaceId, byPolygon) + } + } + const levelSet = new Set(levels) + for (const surface of Object.values(draft)) { + if ( + (surface.type !== 'slab' && surface.type !== 'ceiling') || + surface.boundary === 'auto' || + !levelSet.has(surface.parentId ?? '') + ) + continue + const desired = [...(legacyCutsBySurface.get(surface.id)?.values() ?? [])] + const retained = (surface.holes ?? []).flatMap((hole, index) => { + const metadata = surface.holeMetadata?.[index] + if (metadata?.source !== 'floor-opening') + return [{ hole, metadata: metadata ?? { source: 'manual' as const } }] + const opening = metadata.openingId ? draft[metadata.openingId] : undefined + return opening?.type === 'floor-opening' && + !opening.legacyPlateCuts?.[surface.id] && + !opening.legacyCeilingCuts?.[surface.id] + ? [{ hole, metadata }] + : [] + }) + const holes = [...retained, ...desired] + if ( + JSON.stringify([surface.holes ?? [], surface.holeMetadata ?? []]) !== + JSON.stringify([holes.map((entry) => entry.hole), holes.map((entry) => entry.metadata)]) + ) + draft[surface.id] = { + ...surface, + holes: holes.map((entry) => entry.hole), + holeMetadata: holes.map((entry) => entry.metadata), + } + } + const patches: NodePatch[] = [] + for (const id of [...new Set([...Object.keys(nodes), ...Object.keys(draft)])].sort()) { + const before = nodes[id] + const after = draft[id] + if (before === after) continue + if (!after) { + patches.push({ op: 'delete', id: id as AnyNodeId }) + continue + } + if (!before) { + patches.push({ op: 'create', node: after }) + continue + } + const data: Record = {} + for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) { + const value = (after as unknown as Record)[key] + if ( + JSON.stringify((before as unknown as Record)[key]) !== + JSON.stringify(value) + ) + data[key] = value + } + if (Object.keys(data).length) + patches.push({ op: 'update', id: after.id, data: data as Partial }) + else draft[id] = before + } + return { + nodes: patches.length ? draft : nodes, + patches, + events: events.filter( + (event, index) => + events.findIndex((other) => JSON.stringify(other) === JSON.stringify(event)) === index, + ), + } +} diff --git a/packages/core/src/lib/terrain-source-persisted.ts b/packages/core/src/lib/terrain-source-persisted.ts new file mode 100644 index 0000000000..7eb1b079fa --- /dev/null +++ b/packages/core/src/lib/terrain-source-persisted.ts @@ -0,0 +1,79 @@ +/** + * Scene → `TerrainField`, cached. + * + * Every consumer that needs the ground — the mesh builder, the raycast, the + * placement predicate, the collider, the 2D view — starts here. It exists to + * solve one problem: the scene stores terrain as base64 (`site.terrain`), and + * decoding that per frame, or per pointer-move, would be absurd. + * + * The cache is a `WeakMap` keyed on the **`TerrainData` object identity**, which + * is a correct version key because the scene store is immutable-by-convention: + * `updateNode` produces a new node object with a new `terrain` object, so a + * changed terrain necessarily misses the cache and a stale entry is unreachable. + * No invalidation call, no version counter, nothing to forget to bump. + * + * `commitTerrainField` closes the loop: it encodes a field *and* primes the cache + * with the field it just encoded. That is what makes a sculpt stroke free — after + * the commit, the next read is a cache hit, so a stroke never decodes base64 even + * once, let alone per dab. + */ + +import type { SiteNode } from '../schema/nodes/site' +import type { TerrainData } from '../schema/terrain' +import { decodeTerrainField, encodeTerrainField } from './terrain-codec' +import { createTerrainField, type TerrainField } from './terrain-field' + +const fieldCache = new WeakMap() + +/** + * Sites whose `terrain` failed to decode. Prevents re-attempting a doomed decode + * on every frame — the corrupt-scene path must be cheap, not just survivable. + */ +const failedDecodes = new WeakSet() + +export function persistedTerrainFieldOf( + site: Pick | null | undefined, +): TerrainField | null { + const data = site?.terrain + if (!data) return null + const cached = fieldCache.get(data) + if (cached) return cached + if (failedDecodes.has(data)) return null + + const field = decodeTerrainField(data) + if (!field) { + failedDecodes.add(data) + return null + } + fieldCache.set(data, field) + return field +} + +/** + * The field a site *would* sculpt into: its existing terrain, or a fresh flat + * field sized to `options`. + * + * Separate from `terrainFieldOf` because the read path wants `null` for "no + * terrain" and the write path wants something to write into. Collapsing them + * would force every reader to allocate a field it does not need. + */ +export function terrainFieldForEdit( + site: Pick | null | undefined, + options?: Parameters[0], +): TerrainField { + return persistedTerrainFieldOf(site) ?? createTerrainField(options) +} + +/** + * Encode a field for persistence and prime the read cache with it. + * + * Call this instead of `encodeTerrainField` whenever the result is going into the + * scene. The returned data is what to write to `site.terrain`; the cache priming + * means the very next `terrainFieldOf` on the updated node returns this exact + * field object without decoding. + */ +export function commitTerrainField(field: TerrainField): TerrainData { + const data = encodeTerrainField(field) + fieldCache.set(data, field) + return data +} diff --git a/packages/core/src/lib/terrain-source.ts b/packages/core/src/lib/terrain-source.ts index c78394a869..12845e5725 100644 --- a/packages/core/src/lib/terrain-source.ts +++ b/packages/core/src/lib/terrain-source.ts @@ -1,36 +1,13 @@ -/** - * Scene → `TerrainField`, cached. - * - * Every consumer that needs the ground — the mesh builder, the raycast, the - * placement predicate, the collider, the 2D view — starts here. It exists to - * solve one problem: the scene stores terrain as base64 (`site.terrain`), and - * decoding that per frame, or per pointer-move, would be absurd. - * - * The cache is a `WeakMap` keyed on the **`TerrainData` object identity**, which - * is a correct version key because the scene store is immutable-by-convention: - * `updateNode` produces a new node object with a new `terrain` object, so a - * changed terrain necessarily misses the cache and a stale entry is unreachable. - * No invalidation call, no version counter, nothing to forget to bump. - * - * `commitTerrainField` closes the loop: it encodes a field *and* primes the cache - * with the field it just encoded. That is what makes a sculpt stroke free — after - * the commit, the next read is a cache hit, so a stroke never decodes base64 even - * once, let alone per dab. - */ - import type { SiteNode } from '../schema/nodes/site' -import type { TerrainData } from '../schema/terrain' import useLiveTerrain from '../store/use-live-terrain' -import { decodeTerrainField, encodeTerrainField } from './terrain-codec' -import { createTerrainField, type TerrainField } from './terrain-field' +import type { TerrainField } from './terrain-field' +import { persistedTerrainFieldOf } from './terrain-source-persisted' -const fieldCache = new WeakMap() - -/** - * Sites whose `terrain` failed to decode. Prevents re-attempting a doomed decode - * on every frame — the corrupt-scene path must be cheap, not just survivable. - */ -const failedDecodes = new WeakSet() +export { + commitTerrainField, + persistedTerrainFieldOf, + terrainFieldForEdit, +} from './terrain-source-persisted' /** * The terrain field for a site, or `null` when the site has no sculpted terrain. @@ -57,50 +34,3 @@ export function terrainFieldOf( } return persistedTerrainFieldOf(site) } - -export function persistedTerrainFieldOf( - site: Pick | null | undefined, -): TerrainField | null { - const data = site?.terrain - if (!data) return null - const cached = fieldCache.get(data) - if (cached) return cached - if (failedDecodes.has(data)) return null - - const field = decodeTerrainField(data) - if (!field) { - failedDecodes.add(data) - return null - } - fieldCache.set(data, field) - return field -} - -/** - * The field a site *would* sculpt into: its existing terrain, or a fresh flat - * field sized to `options`. - * - * Separate from `terrainFieldOf` because the read path wants `null` for "no - * terrain" and the write path wants something to write into. Collapsing them - * would force every reader to allocate a field it does not need. - */ -export function terrainFieldForEdit( - site: Pick | null | undefined, - options?: Parameters[0], -): TerrainField { - return persistedTerrainFieldOf(site) ?? createTerrainField(options) -} - -/** - * Encode a field for persistence and prime the read cache with it. - * - * Call this instead of `encodeTerrainField` whenever the result is going into the - * scene. The returned data is what to write to `site.terrain`; the cache priming - * means the very next `terrainFieldOf` on the updated node returns this exact - * field object without decoding. - */ -export function commitTerrainField(field: TerrainField): TerrainData { - const data = encodeTerrainField(field) - fieldCache.set(data, field) - return data -} diff --git a/packages/core/src/lib/terrain-support-query.ts b/packages/core/src/lib/terrain-support-query.ts new file mode 100644 index 0000000000..e1032b3773 --- /dev/null +++ b/packages/core/src/lib/terrain-support-query.ts @@ -0,0 +1,219 @@ +/** + * Terrain as the level base — the third and last place flat ground was assumed. + * + * `getFloorPlacedElevation` returns a *lift* added to a node's level-local Y, and + * two of its `0`-returns mean "supported by the level base". This module is what + * those two branches call so that "the level base" can mean the sculpted ground + * instead of the plane `y = 0`. The other `0`-returns are `+0` no-ops for + * wall/ceiling-attached items, non-`level` parents, and broken graphs; substituting + * terrain there would lift sconces off walls, so they stay `0` forever. + * + * The whole file is pure — nodes in, metres out — which is what lets the stacking + * matrix be tested per kind without a canvas. + */ + +import type { AnyNode, AnyNodeId } from '../schema' +import type { BuildingNode } from '../schema/nodes/building' +import type { SiteNode } from '../schema/nodes/site' +import { getAuthoredLevelElevations } from '../services/storey' +import { heightAt } from './terrain-field' +import { persistedTerrainFieldOf } from './terrain-source-persisted' + +/** + * World Y of the site datum — the plane terrain heights are measured from. + * + * Terrain vertices are absolute world coordinates (the site group renders at the + * origin and `terrain-geometry` writes `origin + col * spacing` straight into the + * buffer), so the datum is a constant rather than a site property. It is named + * because the *comparison* against it is load-bearing, not the value: it is what + * separates "the ground" from every other horizontal surface in the scene. + */ +export const SITE_DATUM_Y = 0 + +/** + * How close a surface must sit to the datum to count as the ground. + * + * Loose enough to absorb float drift through a level's world matrix, tight enough + * that a ground slab (5 cm) still reads as a built surface rather than as terrain. + */ +export const SITE_DATUM_EPSILON = 1e-4 + +/** True when a world-space height is the site datum — i.e. the terrain's plane. */ +export function isSiteDatum(worldY: number): boolean { + return Math.abs(worldY - SITE_DATUM_Y) < SITE_DATUM_EPSILON +} + +/** + * `getAuthoredLevelElevations` memoized on the `nodes` record identity. + * + * Without this the stacking resolver is O(N) per node and therefore O(N²) per + * frame, since `FloorElevationSystem` calls it for every dirty floor-placed node. + * The scene store is immutable-by-convention, so the record identity is a correct + * version key — the same reasoning (and the same `WeakMap` shape) as + * `terrain-source`'s field cache and the spatial grid's `levelWallsCache`. + */ +const levelElevationCache = new WeakMap>() + +function cachedLevelElevations( + nodes: Record, +): ReturnType { + const cached = levelElevationCache.get(nodes) + if (cached) return cached + const elevations = getAuthoredLevelElevations(nodes as Record) + levelElevationCache.set(nodes, elevations) + return elevations +} + +/** + * `siteOf` memoized on the `nodes` record identity, for the same reason + * `levelElevationCache` exists: the resolver is called per wall per frame (the + * spatial grid) and per wall per store update (the space-detection trigger), so + * an O(N) scan inside it makes those callers O(N²). + */ +const siteCache = new WeakMap() + +function siteOf(nodes: Record): SiteNode | null { + const cached = siteCache.get(nodes) + if (cached !== undefined) return cached + let site: SiteNode | null = null + for (const node of Object.values(nodes)) { + if (node?.type === 'site') { + site = node as SiteNode + break + } + } + siteCache.set(nodes, site) + return site +} + +/** + * Level-local XZ → world XZ, through the building's transform. + * + * A level group carries only a Y offset (`LevelSystem` writes `position.y` and + * nothing else), so level-local XZ is building-local XZ; the building carries the + * site-space placement, and the site renders at the origin. Only the Y rotation + * matters — a building tipped in X or Z is not a thing the editor can produce. + */ +function levelLocalToWorldXZ( + building: BuildingNode | null, + x: number, + z: number, +): [number, number] { + if (!building) return [x, z] + const angle = building.rotation?.[1] ?? 0 + const [px, , pz] = building.position ?? [0, 0, 0] + if (angle === 0) return [x + px, z + pz] + const cos = Math.cos(angle) + const sin = Math.sin(angle) + return [cos * x + sin * z + px, -sin * x + cos * z + pz] +} + +/** + * Where a level sits relative to the datum, for the levels terrain can support. + * + * **Only the storey the level stack puts at the datum follows terrain.** An upper + * storey has a real floor, and draping it would sink its contents into the + * hillside under the building. The test is that storey's own base height against + * the datum — deliberately asked of `getAuthoredLevelElevations`, the same function the + * renderer positions level groups with, so placement can never hold a second + * opinion about which storey is on the ground. + * + * Which storey that is follows from the stack, not from the ordinal: today the + * lowest ordinal anchors at 0, so a building with an ordinal `-1` level has *that* + * level at grade and its ground floor a storey up. When genuine below-grade + * stacking lands, this rule tracks it with no change here — an excavated basement + * will stop being at the datum, and stop being draped, on its own. + */ +function levelDatum( + nodes: Record, + levelId: string, +): { building: BuildingNode | null; baseWorldY: number } | null { + const elevation = cachedLevelElevations(nodes).get(levelId) + if (!elevation) return null + + const building = elevation.buildingId + ? ((nodes[elevation.buildingId] ?? null) as BuildingNode | null) + : null + const datum = building?.position?.[1] ?? 0 + const baseWorldY = datum + elevation.baseY + if (!isSiteDatum(baseWorldY)) return null + + return { building, baseWorldY } +} + +/** + * Whether the sculpted ground is what a node on `levelId` stands on — i.e. + * whether moving the terrain moves that node. + * + * Split out of `terrainSupportLift` so the invalidation rule that re-elevates + * nodes after a sculpt (`markTerrainSupportDependents`) tests grade-ness with + * the *same* predicate the resolver does. Two copies of this test would drift, + * and the failure is silent: a level the resolver drapes but the dirty rule + * skips leaves its contents frozen at the height the ground used to be. + * + * Deliberately independent of whether a field exists. A stroke that clears the + * terrain has to re-elevate exactly the nodes a stroke that creates it does, and + * asking about the field here would mark none of them on the way back down. + */ +export function isLevelAtSiteDatum(nodes: Record, levelId: string): boolean { + return levelDatum(nodes, levelId) !== null +} + +/** + * The lift, in level-local metres, that the sculpted ground provides to a node on + * `levelId` at level-local `x`/`z`. Null when terrain does not support this node — + * no sculpted ground, an unresolvable level, or a storey whose floor is not at + * grade. + * + * Null rather than 0 so callers keep their existing flat-ground path verbatim. + * That is what makes this change invisible to every scene that never touched + * terrain, which is nearly all of them. + */ +export function terrainSupportLift( + nodes: Record, + levelId: string, + x: number, + z: number, + fieldOf: (site: SiteNode) => ReturnType = persistedTerrainFieldOf, +): number | null { + const site = siteOf(nodes) + const field = site ? fieldOf(site) : null + if (!field) return null + + const datum = levelDatum(nodes, levelId) + if (!datum) return null + + const [worldX, worldZ] = levelLocalToWorldXZ(datum.building, x, z) + // The lift is measured from the storey's own base, so a building sited on a + // datum other than 0 does not double-count it. + return heightAt(field, worldX, worldZ) - datum.baseWorldY +} + +/** + * **The level base, in level-local metres, at level-local `x`/`z`** — the surface + * a node rests on when nothing built is under it. Sculpted ground where terrain + * supports this storey, `0` everywhere else. + * + * This is the one function every "nothing is under me, so I'm at zero" site in + * the codebase should call, and the reason it exists separately from + * {@link terrainSupportLift}: that function answers *"is there terrain here"* + * (nullable, so a caller can branch), while this one answers *"how high is the + * floor of the world here"* (total, so a caller does not have to know terrain + * exists). Spelling the second question `terrainSupportLift(…) ?? 0` at each + * site is what made terrain opt-in per kind — every new consumer had to remember + * to ask, and the ones that forgot silently assumed the plane `y = 0`. Kinds + * inherit terrain by resolving their base through here instead of hardcoding a + * zero; nothing has to be registered for that to work. + * + * Callers that must distinguish "flat ground" from "a built surface flush with + * the storey base" still need {@link terrainSupportLift}'s null — both read `0` + * here and only the first follows a hillside. + */ +export function levelBaseElevationAt( + nodes: Record, + levelId: string, + x: number, + z: number, +): number { + return terrainSupportLift(nodes, levelId, x, z) ?? 0 +} diff --git a/packages/core/src/lib/terrain-support.ts b/packages/core/src/lib/terrain-support.ts index 68725bb5ad..97005d73a5 100644 --- a/packages/core/src/lib/terrain-support.ts +++ b/packages/core/src/lib/terrain-support.ts @@ -1,213 +1,23 @@ -/** - * Terrain as the level base — the third and last place flat ground was assumed. - * - * `getFloorPlacedElevation` returns a *lift* added to a node's level-local Y, and - * two of its `0`-returns mean "supported by the level base". This module is what - * those two branches call so that "the level base" can mean the sculpted ground - * instead of the plane `y = 0`. The other `0`-returns are `+0` no-ops for - * wall/ceiling-attached items, non-`level` parents, and broken graphs; substituting - * terrain there would lift sconces off walls, so they stay `0` forever. - * - * The whole file is pure — nodes in, metres out — which is what lets the stacking - * matrix be tested per kind without a canvas. - */ - -import type { AnyNode, AnyNodeId } from '../schema' -import type { BuildingNode } from '../schema/nodes/building' -import type { SiteNode } from '../schema/nodes/site' -import { getLevelElevations } from '../services/storey' -import { heightAt } from './terrain-field' +import type { AnyNode } from '../schema' import { terrainFieldOf } from './terrain-source' +import { terrainSupportLift as queryTerrainSupportLift } from './terrain-support-query' -/** - * World Y of the site datum — the plane terrain heights are measured from. - * - * Terrain vertices are absolute world coordinates (the site group renders at the - * origin and `terrain-geometry` writes `origin + col * spacing` straight into the - * buffer), so the datum is a constant rather than a site property. It is named - * because the *comparison* against it is load-bearing, not the value: it is what - * separates "the ground" from every other horizontal surface in the scene. - */ -export const SITE_DATUM_Y = 0 - -/** - * How close a surface must sit to the datum to count as the ground. - * - * Loose enough to absorb float drift through a level's world matrix, tight enough - * that a ground slab (5 cm) still reads as a built surface rather than as terrain. - */ -export const SITE_DATUM_EPSILON = 1e-4 - -/** True when a world-space height is the site datum — i.e. the terrain's plane. */ -export function isSiteDatum(worldY: number): boolean { - return Math.abs(worldY - SITE_DATUM_Y) < SITE_DATUM_EPSILON -} - -/** - * `getLevelElevations` memoized on the `nodes` record identity. - * - * Without this the stacking resolver is O(N) per node and therefore O(N²) per - * frame, since `FloorElevationSystem` calls it for every dirty floor-placed node. - * The scene store is immutable-by-convention, so the record identity is a correct - * version key — the same reasoning (and the same `WeakMap` shape) as - * `terrain-source`'s field cache and the spatial grid's `levelWallsCache`. - */ -const levelElevationCache = new WeakMap>() - -function cachedLevelElevations( - nodes: Record, -): ReturnType { - const cached = levelElevationCache.get(nodes) - if (cached) return cached - const elevations = getLevelElevations(nodes as Record) - levelElevationCache.set(nodes, elevations) - return elevations -} - -/** - * `siteOf` memoized on the `nodes` record identity, for the same reason - * `levelElevationCache` exists: the resolver is called per wall per frame (the - * spatial grid) and per wall per store update (the space-detection trigger), so - * an O(N) scan inside it makes those callers O(N²). - */ -const siteCache = new WeakMap() - -function siteOf(nodes: Record): SiteNode | null { - const cached = siteCache.get(nodes) - if (cached !== undefined) return cached - let site: SiteNode | null = null - for (const node of Object.values(nodes)) { - if (node?.type === 'site') { - site = node as SiteNode - break - } - } - siteCache.set(nodes, site) - return site -} - -/** - * Level-local XZ → world XZ, through the building's transform. - * - * A level group carries only a Y offset (`LevelSystem` writes `position.y` and - * nothing else), so level-local XZ is building-local XZ; the building carries the - * site-space placement, and the site renders at the origin. Only the Y rotation - * matters — a building tipped in X or Z is not a thing the editor can produce. - */ -function levelLocalToWorldXZ( - building: BuildingNode | null, - x: number, - z: number, -): [number, number] { - if (!building) return [x, z] - const angle = building.rotation?.[1] ?? 0 - const [px, , pz] = building.position ?? [0, 0, 0] - if (angle === 0) return [x + px, z + pz] - const cos = Math.cos(angle) - const sin = Math.sin(angle) - return [cos * x + sin * z + px, -sin * x + cos * z + pz] -} - -/** - * Where a level sits relative to the datum, for the levels terrain can support. - * - * **Only the storey the level stack puts at the datum follows terrain.** An upper - * storey has a real floor, and draping it would sink its contents into the - * hillside under the building. The test is that storey's own base height against - * the datum — deliberately asked of `getLevelElevations`, the same function the - * renderer positions level groups with, so placement can never hold a second - * opinion about which storey is on the ground. - * - * Which storey that is follows from the stack, not from the ordinal: today the - * lowest ordinal anchors at 0, so a building with an ordinal `-1` level has *that* - * level at grade and its ground floor a storey up. When genuine below-grade - * stacking lands, this rule tracks it with no change here — an excavated basement - * will stop being at the datum, and stop being draped, on its own. - */ -function levelDatum( - nodes: Record, - levelId: string, -): { building: BuildingNode | null; baseWorldY: number } | null { - const elevation = cachedLevelElevations(nodes).get(levelId) - if (!elevation) return null - - const building = elevation.buildingId - ? ((nodes[elevation.buildingId] ?? null) as BuildingNode | null) - : null - const datum = building?.position?.[1] ?? 0 - const baseWorldY = datum + elevation.baseY - if (!isSiteDatum(baseWorldY)) return null +export { + isLevelAtSiteDatum, + isSiteDatum, + SITE_DATUM_EPSILON, + SITE_DATUM_Y, +} from './terrain-support-query' - return { building, baseWorldY } -} - -/** - * Whether the sculpted ground is what a node on `levelId` stands on — i.e. - * whether moving the terrain moves that node. - * - * Split out of `terrainSupportLift` so the invalidation rule that re-elevates - * nodes after a sculpt (`markTerrainSupportDependents`) tests grade-ness with - * the *same* predicate the resolver does. Two copies of this test would drift, - * and the failure is silent: a level the resolver drapes but the dirty rule - * skips leaves its contents frozen at the height the ground used to be. - * - * Deliberately independent of whether a field exists. A stroke that clears the - * terrain has to re-elevate exactly the nodes a stroke that creates it does, and - * asking about the field here would mark none of them on the way back down. - */ -export function isLevelAtSiteDatum(nodes: Record, levelId: string): boolean { - return levelDatum(nodes, levelId) !== null -} - -/** - * The lift, in level-local metres, that the sculpted ground provides to a node on - * `levelId` at level-local `x`/`z`. Null when terrain does not support this node — - * no sculpted ground, an unresolvable level, or a storey whose floor is not at - * grade. - * - * Null rather than 0 so callers keep their existing flat-ground path verbatim. - * That is what makes this change invisible to every scene that never touched - * terrain, which is nearly all of them. - */ export function terrainSupportLift( nodes: Record, levelId: string, x: number, z: number, ): number | null { - const site = siteOf(nodes) - const field = site ? terrainFieldOf(site) : null - if (!field) return null - - const datum = levelDatum(nodes, levelId) - if (!datum) return null - - const [worldX, worldZ] = levelLocalToWorldXZ(datum.building, x, z) - // The lift is measured from the storey's own base, so a building sited on a - // datum other than 0 does not double-count it. - return heightAt(field, worldX, worldZ) - datum.baseWorldY + return queryTerrainSupportLift(nodes, levelId, x, z, terrainFieldOf) } -/** - * **The level base, in level-local metres, at level-local `x`/`z`** — the surface - * a node rests on when nothing built is under it. Sculpted ground where terrain - * supports this storey, `0` everywhere else. - * - * This is the one function every "nothing is under me, so I'm at zero" site in - * the codebase should call, and the reason it exists separately from - * {@link terrainSupportLift}: that function answers *"is there terrain here"* - * (nullable, so a caller can branch), while this one answers *"how high is the - * floor of the world here"* (total, so a caller does not have to know terrain - * exists). Spelling the second question `terrainSupportLift(…) ?? 0` at each - * site is what made terrain opt-in per kind — every new consumer had to remember - * to ask, and the ones that forgot silently assumed the plane `y = 0`. Kinds - * inherit terrain by resolving their base through here instead of hardcoding a - * zero; nothing has to be registered for that to work. - * - * Callers that must distinguish "flat ground" from "a built surface flush with - * the storey base" still need {@link terrainSupportLift}'s null — both read `0` - * here and only the first follows a hillside. - */ export function levelBaseElevationAt( nodes: Record, levelId: string, diff --git a/packages/core/src/lib/unit-containment.test.ts b/packages/core/src/lib/unit-containment.test.ts index 6cd2e36f8b..1cf5088e7f 100644 --- a/packages/core/src/lib/unit-containment.test.ts +++ b/packages/core/src/lib/unit-containment.test.ts @@ -142,7 +142,7 @@ describe('deriveUnit', () => { expect(result.boundaryWallIds).not.toContain(farWall.id) }) - test('resolves auto zones from current walls instead of the stored polygon', () => { + test('uses the authoritative zone footprint for containment', () => { const s = scene() const polygon = rectangle() const walls = polygon.map((start, index) => @@ -160,7 +160,7 @@ describe('deriveUnit', () => { }), ) const column = s.add(ColumnNode.parse({ parentId: s.lower.id, position: [2, 0, 2] })) - expect(deriveUnit(s.unit([zone]), s.nodes).containedNodeIds).toEqual([column.id]) + expect(deriveUnit(s.unit([zone]), s.nodes).containedNodeIds).not.toContain(column.id) }) test('finds crossing supports and excludes holes and supports on other levels', () => { diff --git a/packages/core/src/lib/unit-containment.ts b/packages/core/src/lib/unit-containment.ts index c9b8403917..691404c34f 100644 --- a/packages/core/src/lib/unit-containment.ts +++ b/packages/core/src/lib/unit-containment.ts @@ -10,7 +10,7 @@ import type { import { pointOnPolygonBoundary, wallOverlapsSlabFootprint } from '../systems/slab/slab-support' import { measurementCentroid } from './measurement-geometry' import { type Point2D, pointInPolygon } from './polygon-relations' -import { detectSpacesForLevel, resolveAutoZonePolygon } from './space-detection' +import { detectSpacesForLevel } from './space-detection' export type UnitDerivation = { unitId: UnitNode['id'] @@ -80,7 +80,7 @@ export function deriveUnit(unit: UnitNode, nodes: Nodes): UnitDerivation { if (level?.type !== 'level') continue levels.set(level.id, level) const polygons = polygonsByLevel.get(level.id) ?? [] - polygons.push(resolveAutoZonePolygon(zone, (id) => nodes[id])) + polygons.push(zone.polygon) polygonsByLevel.set(level.id, polygons) } const levelIds = [...levels.values()] diff --git a/packages/core/src/lib/unit-report.test.ts b/packages/core/src/lib/unit-report.test.ts index 1cdd39a823..d0ac4ef774 100644 --- a/packages/core/src/lib/unit-report.test.ts +++ b/packages/core/src/lib/unit-report.test.ts @@ -79,7 +79,7 @@ describe('buildUnitReport', () => { }) }) - test('measures the resolved auto zone polygon', () => { + test('measures the authoritative auto zone polygon without re-deriving walls', () => { const level = LevelNode.parse({ level: 0 }) const polygon: [number, number][] = [ [0, 0], @@ -95,12 +95,17 @@ describe('buildUnitReport', () => { parentId: level.id, autoFromWalls: true, boundaryWallIds: walls.map((wall) => wall.id), - polygon: [], + polygon: [ + [0, 0], + [6, 0], + [6, 3], + [0, 3], + ], }) const nodes: Record = Object.fromEntries( [level, zone, ...walls].map((node) => [node.id, node]), ) const report = buildUnitReport(UnitNode.parse({ members: [zone.id] }), nodes) - expect(report.grossAreaM2).toBeCloseTo(12) + expect(report.grossAreaM2).toBeCloseTo(18) }) }) diff --git a/packages/core/src/lib/unit-report.ts b/packages/core/src/lib/unit-report.ts index 909b8941fb..9700126bc9 100644 --- a/packages/core/src/lib/unit-report.ts +++ b/packages/core/src/lib/unit-report.ts @@ -1,6 +1,5 @@ import type { AnyNode, AnyNodeId, LevelNode, UnitNode, ZoneNode } from '../schema' -import { measurementArea } from './measurement-geometry' -import { resolveAutoZonePolygon } from './space-detection' +import { area } from './polygon-boolean' export type UnitReport = { memberCount: number @@ -25,14 +24,17 @@ export function buildUnitReport( if (zone?.type !== 'zone') return [] const level = zone.parentId ? nodes[zone.parentId as AnyNodeId] : undefined if (level?.type === 'level') levels.set(level.id, level.level) - const polygon = resolveAutoZonePolygon(zone, (nodeId) => nodes[nodeId]) + const { polygon, holes } = zone return [ { zoneId: zone.id, name: zone.name, levelId: level?.type === 'level' ? level.id : null, levelOrdinal: level?.type === 'level' ? level.level : null, - areaM2: measurementArea(polygon.map(([x, z]) => [x, 0, z])), + areaM2: + zone.autoFromWalls && zone.enclosureStatus === 'open' + ? 0 + : area([{ outer: polygon, holes }]), }, ] }) diff --git a/packages/core/src/lib/wall-bound-surface-follower.test.ts b/packages/core/src/lib/wall-bound-surface-follower.test.ts deleted file mode 100644 index ae01e0a877..0000000000 --- a/packages/core/src/lib/wall-bound-surface-follower.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { expect, test } from 'bun:test' -import { SlabNode, WallNode } from '../schema' -import { createWallBoundSurfaceFollower } from './space-detection' - -test('a collinear branch outside a room cannot carry its corner', () => { - const levelId = 'level_collinear-follower' - const branch = WallNode.parse({ parentId: levelId, start: [2, 0], end: [4, 0] }) - const walls = [ - branch, - WallNode.parse({ parentId: levelId, start: [0, 0], end: [2, 0] }), - WallNode.parse({ parentId: levelId, start: [2, 0], end: [2, 4] }), - WallNode.parse({ parentId: levelId, start: [2, 4], end: [0, 4] }), - WallNode.parse({ parentId: levelId, start: [0, 4], end: [0, 0] }), - ] - const slab = SlabNode.parse({ - parentId: levelId, - autoFromWalls: true, - polygon: [ - [0, 0], - [2, 0], - [2, 4], - [0, 4], - ], - }) - const nodes = Object.fromEntries([...walls, slab].map((node) => [node.id, node])) - const follow = createWallBoundSurfaceFollower(levelId, nodes, new Set([branch.id])) - const preview = new Map(follow(new Map([[branch.id, { start: [2, -1], end: [4, -1] }]]))) - expect(preview.get(slab.id) ?? slab.polygon).toEqual(slab.polygon) -}) diff --git a/packages/core/src/lib/zone-quantities.test.ts b/packages/core/src/lib/zone-quantities.test.ts index 4bdeb23a93..c0bc3e6943 100644 --- a/packages/core/src/lib/zone-quantities.test.ts +++ b/packages/core/src/lib/zone-quantities.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from 'bun:test' import { type AnyNode, CeilingNode, SlabNode, WallNode, ZoneNode } from '../schema' +import { floorStepFixture } from '../systems/slab/__fixtures__/floor-step' +import { reconcileStructureOnLoad } from '../utils/reconcile-structure-on-load' import { detectSpacesForLevel } from './space-detection' import { deriveZoneQuantityReport } from './zone-quantities' @@ -218,7 +220,7 @@ describe('deriveZoneQuantityReport', () => { }) }) - test('uses the closed zone boundary when small wall-end seams prevent loop detection', () => { + test('closes small wall-end seams into the room boundary', () => { const zone = ZoneNode.parse({ id: 'zone_seamed', name: 'Room with modeling seams', @@ -579,3 +581,17 @@ describe('deriveZoneQuantityReport', () => { if (report.volume.status === 'available') expect(report.volume.value).toBeCloseTo(113.75) }) }) + +test('base and room plates prove the clear floor at the room elevation', () => { + const source = floorStepFixture() + source.nodes[source.zones[0]!.id] = { ...source.zones[0]!, floor: { elevation: 0.55 } } + const { nodes } = reconcileStructureOnLoad(source.nodes) + for (const original of source.zones) { + const zone = nodes[original.id] as ZoneNode + const report = deriveZoneQuantityReport(zone, nodes) + expect(report.floorSurface.status).toBe('available') + if (report.floorSurface.status === 'available') + expect(report.floorSurface.value).toBeCloseTo(3.8 * 3.8) + expect(report.volume.status).toBe('available') + } +}) diff --git a/packages/core/src/lib/zone-quantities.ts b/packages/core/src/lib/zone-quantities.ts index b1830696d3..97d0e48054 100644 --- a/packages/core/src/lib/zone-quantities.ts +++ b/packages/core/src/lib/zone-quantities.ts @@ -4,8 +4,20 @@ import { DEFAULT_LEVEL_HEIGHT, resolveCeilingHeight } from '../services/level-he import { getWallPlaneTop } from '../services/storey' import { computeWallSlabSupport } from '../systems/slab/slab-support' import { sampleWallCenterline } from '../systems/wall/wall-curve' -import { DEFAULT_WALL_THICKNESS } from '../systems/wall/wall-footprint' +import { getWallLocalFaceZ } from '../systems/wall/wall-frame' import { resolveWallEffectiveHeight } from '../systems/wall/wall-top' +import { levelWallCover } from './plate-surface' +import { + area, + containsPoint, + difference, + distanceToBoundary, + intersection, + type Polygon, + type Ring, + union, +} from './polygon-boolean' +import { roomFloorPlate } from './room-floor-plate' import { detectSpacesForLevel, type Space } from './space-detection' type Point2D = readonly [number, number] @@ -28,7 +40,6 @@ export type ZoneQuantityReport = { const BOUNDARY_TOLERANCE = 0.08 const SURFACE_COVERAGE_THRESHOLD = 0.95 const SPACE_CONTAINMENT_THRESHOLD = 0.95 -const COVERAGE_SAMPLE_STEPS = 24 const SURFACE_DATUM_EPSILON = 1e-4 function pointDistance(a: Point2D, b: Point2D): number { @@ -48,183 +59,6 @@ function pointToSegmentDistance(point: Point2D, start: Point2D, end: Point2D): n return pointDistance(point, [start[0] + t * dx, start[1] + t * dy]) } -function pointToPolygonBoundaryDistance(point: Point2D, polygon: readonly Point2D[]): number { - let best = Number.POSITIVE_INFINITY - for (let index = 0; index < polygon.length; index += 1) { - const start = polygon[index] - const end = polygon[(index + 1) % polygon.length] - if (!(start && end)) continue - best = Math.min(best, pointToSegmentDistance(point, start, end)) - } - return best -} - -function signedPolygonArea(polygon: readonly Point2D[]): number { - let area = 0 - for (let index = 0; index < polygon.length; index += 1) { - const start = polygon[index] - const end = polygon[(index + 1) % polygon.length] - if (!(start && end)) continue - area += start[0] * end[1] - end[0] * start[1] - } - return area / 2 -} - -function polygonArea(polygon: readonly Point2D[]): number { - return Math.abs(signedPolygonArea(polygon)) -} - -function polygonsDescribeSameRegion(a: readonly Point2D[], b: readonly Point2D[]): boolean { - if (a.length < 3 || b.length < 3) return false - - const aArea = polygonArea(a) - const bArea = polygonArea(b) - const areaTolerance = Math.max(0.02, Math.max(aArea, bArea) * 0.01) - if (Math.abs(aArea - bArea) > areaTolerance) return false - - return ( - a.every((point) => pointToPolygonBoundaryDistance(point, b) <= BOUNDARY_TOLERANCE) && - b.every((point) => pointToPolygonBoundaryDistance(point, a) <= BOUNDARY_TOLERANCE) - ) -} - -function pointInPolygon(point: Point2D, polygon: readonly Point2D[], includeBoundary = true) { - if (polygon.length < 3) return false - if (pointToPolygonBoundaryDistance(point, polygon) <= 1e-6) return includeBoundary - - let inside = false - for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index++) { - const currentPoint = polygon[index]! - const previousPoint = polygon[previous]! - if ( - currentPoint[1] > point[1] !== previousPoint[1] > point[1] && - point[0] < - ((previousPoint[0] - currentPoint[0]) * (point[1] - currentPoint[1])) / - (previousPoint[1] - currentPoint[1]) + - currentPoint[0] - ) { - inside = !inside - } - } - return inside -} - -function segmentsCrossProperly(a: Point2D, b: Point2D, c: Point2D, d: Point2D) { - const cross = (start: Point2D, end: Point2D, point: Point2D) => - (end[0] - start[0]) * (point[1] - start[1]) - (end[1] - start[1]) * (point[0] - start[0]) - const abC = cross(a, b, c) - const abD = cross(a, b, d) - const cdA = cross(c, d, a) - const cdB = cross(c, d, b) - return abC * abD < -1e-12 && cdA * cdB < -1e-12 -} - -function polygonContainsRegion(outer: readonly Point2D[], inner: readonly Point2D[]): boolean { - if (outer.length < 3 || inner.length < 3) return false - if (polygonsDescribeSameRegion(outer, inner)) return true - if ( - !inner.every( - (point) => - pointInPolygon(point, outer) || - pointToPolygonBoundaryDistance(point, outer) <= BOUNDARY_TOLERANCE, - ) - ) { - return false - } - - for (let innerIndex = 0; innerIndex < inner.length; innerIndex += 1) { - const innerStart = inner[innerIndex]! - const innerEnd = inner[(innerIndex + 1) % inner.length]! - for (let outerIndex = 0; outerIndex < outer.length; outerIndex += 1) { - if ( - segmentsCrossProperly( - innerStart, - innerEnd, - outer[outerIndex]!, - outer[(outerIndex + 1) % outer.length]!, - ) - ) { - return false - } - } - } - - return inner.some((start, index) => { - const end = inner[(index + 1) % inner.length]! - const midpoint: Point2D = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2] - return pointInPolygon(start, outer, false) || pointInPolygon(midpoint, outer, false) - }) -} - -function polygonsHaveInteriorOverlap(a: readonly Point2D[], b: readonly Point2D[]): boolean { - if (polygonsDescribeSameRegion(a, b)) return true - if ( - a.some((point, index) => { - const end = a[(index + 1) % a.length]! - return ( - pointInPolygon(point, b, false) || - pointInPolygon([(point[0] + end[0]) / 2, (point[1] + end[1]) / 2], b, false) - ) - }) - ) { - return true - } - if ( - b.some((point, index) => { - const end = b[(index + 1) % b.length]! - return ( - pointInPolygon(point, a, false) || - pointInPolygon([(point[0] + end[0]) / 2, (point[1] + end[1]) / 2], a, false) - ) - }) - ) { - return true - } - for (let aIndex = 0; aIndex < a.length; aIndex += 1) { - for (let bIndex = 0; bIndex < b.length; bIndex += 1) { - if ( - segmentsCrossProperly( - a[aIndex]!, - a[(aIndex + 1) % a.length]!, - b[bIndex]!, - b[(bIndex + 1) % b.length]!, - ) - ) { - return true - } - } - } - return false -} - -function polygonCoverageRatio(subject: readonly Point2D[], covers: readonly Point2D[][]): number { - if (subject.length < 3 || covers.length === 0) return 0 - - const xs = subject.map((point) => point[0]) - const ys = subject.map((point) => point[1]) - const minX = Math.min(...xs) - const maxX = Math.max(...xs) - const minY = Math.min(...ys) - const maxY = Math.max(...ys) - if (maxX - minX <= 1e-9 || maxY - minY <= 1e-9) return 0 - - let inside = 0 - let covered = 0 - for (let xIndex = 0; xIndex < COVERAGE_SAMPLE_STEPS; xIndex += 1) { - for (let yIndex = 0; yIndex < COVERAGE_SAMPLE_STEPS; yIndex += 1) { - const point: Point2D = [ - minX + ((xIndex + 0.5) / COVERAGE_SAMPLE_STEPS) * (maxX - minX), - minY + ((yIndex + 0.5) / COVERAGE_SAMPLE_STEPS) * (maxY - minY), - ] - if (!pointInPolygon(point, subject)) continue - inside += 1 - if (covers.some((cover) => pointInPolygon(point, cover))) covered += 1 - } - } - - return inside > 0 ? covered / inside : 0 -} - function pointToPolylineDistance(point: Point2D, polyline: readonly Point2D[]): number { let best = Number.POSITIVE_INFINITY for (let index = 0; index < polyline.length - 1; index += 1) { @@ -281,7 +115,7 @@ function segmentParameter(point: Point2D, start: Point2D, end: Point2D): number function segmentLengthInsideOrNearPolygon( start: Point2D, end: Point2D, - polygon: readonly Point2D[], + polygon: Polygon, tolerance: number, ): number { const dx = end[0] - start[0] @@ -290,26 +124,28 @@ function segmentLengthInsideOrNearPolygon( if (length <= 1e-9) return 0 const breaks = [0, 1] - for (let index = 0; index < polygon.length; index += 1) { - const polygonStart = polygon[index]! - const polygonEnd = polygon[(index + 1) % polygon.length]! - const edgeX = polygonEnd[0] - polygonStart[0] - const edgeY = polygonEnd[1] - polygonStart[1] - const denominator = dx * edgeY - dy * edgeX - if (Math.abs(denominator) > 1e-12) { - const t = - ((polygonStart[0] - start[0]) * edgeY - (polygonStart[1] - start[1]) * edgeX) / denominator - const edgeT = - ((polygonStart[0] - start[0]) * dy - (polygonStart[1] - start[1]) * dx) / denominator - if (t > 0 && t < 1 && edgeT >= -1e-9 && edgeT <= 1 + 1e-9) breaks.push(t) - } + for (const ring of [polygon.outer, ...polygon.holes]) { + for (let index = 0; index < ring.length; index += 1) { + const polygonStart = ring[index]! + const polygonEnd = ring[(index + 1) % ring.length]! + const edgeX = polygonEnd[0] - polygonStart[0] + const edgeY = polygonEnd[1] - polygonStart[1] + const denominator = dx * edgeY - dy * edgeX + if (Math.abs(denominator) > 1e-12) { + const t = + ((polygonStart[0] - start[0]) * edgeY - (polygonStart[1] - start[1]) * edgeX) / + denominator + const edgeT = + ((polygonStart[0] - start[0]) * dy - (polygonStart[1] - start[1]) * dx) / denominator + if (t > 0 && t < 1 && edgeT >= -1e-9 && edgeT <= 1 + 1e-9) breaks.push(t) + } - if (pointToSegmentDistance(polygonStart, start, end) <= tolerance) { - const projected = segmentParameter(polygonStart, start, end) - if (projected > 0 && projected < 1) breaks.push(projected) + if (pointToSegmentDistance(polygonStart, start, end) <= tolerance) { + const projected = segmentParameter(polygonStart, start, end) + if (projected > 0 && projected < 1) breaks.push(projected) + } } } - breaks.sort((a, b) => a - b) const uniqueBreaks = breaks.filter( (value, index) => index === 0 || value - breaks[index - 1]! > 1e-7, @@ -320,8 +156,8 @@ function segmentLengthInsideOrNearPolygon( const t1 = uniqueBreaks[index + 1]! const midpoint = pointAlongSegment(start, end, (t0 + t1) / 2) if ( - pointInPolygon(midpoint, polygon) || - pointToPolygonBoundaryDistance(midpoint, polygon) <= tolerance + containsPoint([polygon], [midpoint[0], midpoint[1]]) || + distanceToBoundary([polygon], [midpoint[0], midpoint[1]]) <= tolerance ) { insideLength += length * (t1 - t0) } @@ -351,13 +187,16 @@ function spansFromSpaces( const wall = wallsById.get(boundary.wallId) if (!wall) return null - const tolerance = (wall.thickness ?? DEFAULT_WALL_THICKNESS) / 2 + BOUNDARY_TOLERANCE + const tolerance = + getWallLocalFaceZ(wall, boundary.face === 'front' ? 'a' : 'b') * + (boundary.face === 'front' ? 1 : -1) + + BOUNDARY_TOLERANCE let length = 0 for (let index = 0; index < boundary.points.length - 1; index += 1) { length += segmentLengthInsideOrNearPolygon( boundary.points[index]!, boundary.points[index + 1]!, - zone.polygon, + { outer: zone.polygon, holes: zone.holes ?? [] }, tolerance, ) } @@ -369,34 +208,36 @@ function spansFromSpaces( function spansFromZoneBoundary(zone: ZoneNode, wallPaths: readonly WallPath[]) { const spans: BoundaryWallSpan[] = [] - for (let edgeIndex = 0; edgeIndex < zone.polygon.length; edgeIndex += 1) { - const start = zone.polygon[edgeIndex]! - const end = zone.polygon[(edgeIndex + 1) % zone.polygon.length]! - const edgeLength = pointDistance(start, end) - if (edgeLength <= 1e-6) continue - - const breaks = [0, 1] - for (const path of wallPaths) { - for (const point of path.points) { - if (pointToSegmentDistance(point, start, end) > BOUNDARY_TOLERANCE) continue - const t = segmentParameter(point, start, end) - if (t > 0 && t < 1) breaks.push(t) + for (const ring of [zone.polygon, ...(zone.holes ?? [])]) { + for (let edgeIndex = 0; edgeIndex < ring.length; edgeIndex += 1) { + const start = ring[edgeIndex]! + const end = ring[(edgeIndex + 1) % ring.length]! + const edgeLength = pointDistance(start, end) + if (edgeLength <= 1e-6) continue + + const breaks = [0, 1] + for (const path of wallPaths) { + for (const point of path.points) { + if (pointToSegmentDistance(point, start, end) > BOUNDARY_TOLERANCE) continue + const t = segmentParameter(point, start, end) + if (t > 0 && t < 1) breaks.push(t) + } } - } - breaks.sort((a, b) => a - b) - const uniqueBreaks = breaks.filter( - (value, index) => index === 0 || value - breaks[index - 1]! > 1e-6, - ) + breaks.sort((a, b) => a - b) + const uniqueBreaks = breaks.filter( + (value, index) => index === 0 || value - breaks[index - 1]! > 1e-6, + ) - for (let index = 0; index < uniqueBreaks.length - 1; index += 1) { - const t0 = uniqueBreaks[index]! - const t1 = uniqueBreaks[index + 1]! - if (t1 - t0 <= 1e-6) continue - const spanStart = pointAlongSegment(start, end, t0) - const spanEnd = pointAlongSegment(start, end, t1) - const wall = wallForBoundarySegment(spanStart, spanEnd, wallPaths) - if (!wall) return null - spans.push({ wall, length: edgeLength * (t1 - t0) }) + for (let index = 0; index < uniqueBreaks.length - 1; index += 1) { + const t0 = uniqueBreaks[index]! + const t1 = uniqueBreaks[index + 1]! + if (t1 - t0 <= 1e-6) continue + const spanStart = pointAlongSegment(start, end, t0) + const spanEnd = pointAlongSegment(start, end, t1) + const wall = wallForBoundarySegment(spanStart, spanEnd, wallPaths) + if (!wall) return null + spans.push({ wall, length: edgeLength * (t1 - t0) }) + } } } return spans.length > 0 ? spans : null @@ -411,18 +252,14 @@ function proveSurfaceCoverage( nodes: readonly T[], getDatum: (node: T) => number, labels: { singular: string; plural: string; datum: string }, + footprint = [{ outer: zone.polygon, holes: zone.holes ?? [] }], ): SurfaceCoverage { - const candidates = nodes.filter( - (node) => - polygonsHaveInteriorOverlap(zone.polygon, node.polygon) && - polygonCoverageRatio(zone.polygon, [node.polygon]) > 0, - ) + const footprintArea = area(footprint) + const candidates = nodes.filter((node) => area(intersection(footprint, node.polygon)) > 1e-6) if ( - candidates.length === 0 || - polygonCoverageRatio( - zone.polygon, - candidates.map((node) => node.polygon), - ) < SURFACE_COVERAGE_THRESHOLD + !footprintArea || + area(intersection(footprint, union(candidates.map((node) => node.polygon)))) / footprintArea < + SURFACE_COVERAGE_THRESHOLD ) { return { status: 'unavailable', reason: `No ${labels.singular} coverage proves this zone.` } } @@ -438,31 +275,21 @@ function proveSurfaceCoverage( } } - let area = polygonArea(zone.polygon) - const seenHoles = new Set() + const openings: Ring[] = [] for (const node of candidates) { - for (const hole of node.holes) { - const forward = hole.map((point) => `${point[0].toFixed(6)},${point[1].toFixed(6)}`).join('|') - const reverse = [...hole] - .reverse() - .map((point) => `${point[0].toFixed(6)},${point[1].toFixed(6)}`) - .join('|') - const key = forward < reverse ? forward : reverse - if (seenHoles.has(key)) continue - seenHoles.add(key) - - if (polygonContainsRegion(hole, zone.polygon)) { + for (const hole of node.holes ?? []) { + const overlap = area(intersection(footprint, hole)) + if (overlap <= 1e-6) continue + if (area(difference(footprint, hole)) <= 1e-6) { return { status: 'unavailable', reason: 'A surface opening removes this zone.' } } - if (polygonContainsRegion(zone.polygon, hole)) { - area -= polygonArea(hole) - } else if (polygonsHaveInteriorOverlap(zone.polygon, hole)) { + if (Math.abs(overlap - area([{ outer: hole, holes: [] }])) > 1e-6) { return { status: 'unavailable', reason: 'A surface opening crosses the zone boundary.' } } + openings.push(hole) } } - - return { status: 'available', area: Math.max(0, area), datum } + return { status: 'available', area: area(difference(footprint, union(openings))), datum } } function unavailable(reason: string): ZoneQuantityValue { @@ -473,6 +300,19 @@ export function deriveZoneQuantityReport( zone: ZoneNode, sceneNodes: Readonly>, ): ZoneQuantityReport { + if (zone.autoFromWalls && zone.enclosureStatus === 'open') { + const missing = unavailable('The room enclosure is open.') + return { + classification: 'footprint', + footprintArea: 0, + perimeter: 0, + edgeLengths: [], + boundaryWallIds: [], + wallSurface: missing, + floorSurface: missing, + volume: missing, + } + } const levelId = zone.parentId const levelNodes = levelId ? Object.values(sceneNodes).filter((node) => node.parentId === levelId) @@ -480,41 +320,68 @@ export function deriveZoneQuantityReport( const walls = levelNodes.filter((node): node is WallNode => node.type === 'wall') const slabs = levelNodes.filter((node): node is SlabNode => node.type === 'slab') const wallEffectiveHeight = (wall: WallNode) => { - const support = computeWallSlabSupport(wall, slabs, walls, wall.supportSlabId) + const support = computeWallSlabSupport( + wall, + slabs, + walls, + wall.supportSlabId, + undefined, + 0, + sceneNodes, + ) const planeTop = levelId ? getWallPlaneTop(wall, levelId, sceneNodes) : DEFAULT_LEVEL_HEIGHT return resolveWallEffectiveHeight(wall, planeTop, support.elevation) } - const edgeLengths = zone.polygon.map((start, index) => { - const end = zone.polygon[(index + 1) % zone.polygon.length] - return end ? pointDistance(start, end) : 0 - }) - const footprintArea = polygonArea(zone.polygon) + const edgeLengths = [zone.polygon, ...(zone.holes ?? [])].flatMap((ring) => + ring.map((start, index) => { + const end = ring[(index + 1) % ring.length] + return end ? pointDistance(start, end) : 0 + }), + ) + const footprint = { outer: zone.polygon, holes: zone.holes ?? [] } + const footprintArea = area([footprint]) const perimeter = edgeLengths.reduce((sum, length) => sum + length, 0) + const floorPlate = roomFloorPlate(slabs, zone.id) + const clearFootprint = floorPlate?.plateRole + ? difference(footprint, levelWallCover(walls)) + : [footprint] const slabCoverage = proveSurfaceCoverage( zone, - levelNodes.filter((node): node is SlabNode => node.type === 'slab'), + slabs.filter((slab) => { + if (zone.floor?.support === 'open') return slab.zoneIds?.includes(zone.id) + if (slab.support === 'open') return false + return ( + !floorPlate?.plateRole || + !slab.plateRole || + (slab.plateRole === floorPlate.plateRole && slab.zoneIds?.includes(zone.id)) + ) + }), (node) => node.elevation, { singular: 'slab', plural: 'Slabs', datum: 'elevations' }, + clearFootprint, ) const ceilingCoverage = proveSurfaceCoverage( zone, levelNodes.filter((node): node is CeilingNode => node.type === 'ceiling'), (node) => resolveCeilingHeight(node, sceneNodes as Record), { singular: 'ceiling', plural: 'Ceilings', datum: 'heights' }, + clearFootprint, ) const spaces = levelId ? detectSpacesForLevel(levelId, walls).spaces : [] - const overlappingSpaces = spaces.filter((space) => - polygonsHaveInteriorOverlap(zone.polygon, space.polygon), + const spaceFootprint = (space: Space) => ({ outer: space.polygon, holes: space.holes ?? [] }) + const overlappingSpaces = spaces.filter( + (space) => area(intersection(footprint, spaceFootprint(space))) > 1e-6, ) const topologyEnclosesZone = + footprintArea > 0 && overlappingSpaces.length > 0 && - polygonCoverageRatio( - zone.polygon, - overlappingSpaces.map((space) => space.polygon), - ) >= SPACE_CONTAINMENT_THRESHOLD && + area(intersection(footprint, union(overlappingSpaces.map(spaceFootprint)))) / footprintArea >= + SPACE_CONTAINMENT_THRESHOLD && overlappingSpaces.every( - (space) => polygonCoverageRatio(space.polygon, [zone.polygon]) >= SPACE_CONTAINMENT_THRESHOLD, + (space) => + area(intersection(spaceFootprint(space), footprint)) / area([spaceFootprint(space)]) >= + SPACE_CONTAINMENT_THRESHOLD, ) const wallsById = new Map(walls.map((wall) => [wall.id, wall])) const wallPaths = wallPathsFor(walls) diff --git a/packages/core/src/procedural-items/query.ts b/packages/core/src/procedural-items/query.ts index a77dff46fa..b23f859d2c 100644 --- a/packages/core/src/procedural-items/query.ts +++ b/packages/core/src/procedural-items/query.ts @@ -6,7 +6,7 @@ import { polygonsOverlap, } from '../lib/polygon-relations' import { getRenderableSlabPolygon } from '../lib/slab-polygon' -import { levelBaseElevationAt } from '../lib/terrain-support' +import { levelBaseElevationAt } from '../lib/terrain-support-query' import { nodeRegistry } from '../registry/registry' import { getBlockFaceFrame } from '../schema/nodes/block' import type { ItemNode } from '../schema/nodes/item' @@ -18,7 +18,7 @@ import { resolveCeilingHeight } from '../services/level-height' import { getStoredLevelHeight } from '../services/storey' import { surfaceRegionContainsPoint } from '../services/surface-region' import { computeWallSlabSupport, pointInPolygon } from '../systems/slab/slab-support' -import { getWallThickness } from '../systems/wall/wall-footprint' +import { getWallLocalFaceZ } from '../systems/wall/wall-frame' import type { ProceduralItemNode } from './node' import { evaluateRecipe, type Surface, type Vec3 } from './recipe' import { @@ -71,7 +71,11 @@ export function proceduralLocalPose(node: ProceduralItemNode, nodes: QueryNodes) rotation[1] = sign < 0 ? Math.PI : 0 position[0] -= reference.position[0] * sign position[1] -= reference.position[1] - position[2] = sign * (getWallThickness(wall) / 2 - reference.position[2] + node.position[2]) + position[2] = + sign * + (getWallLocalFaceZ(wall, sign > 0 ? 'a' : 'b') * sign - + reference.position[2] + + node.position[2]) return { position, rotation } } /** A ceiling design's cut as a hole ring in its ceiling's local [x, z], or null. */ @@ -142,7 +146,7 @@ function floorLift(node: AnyNode | ProceduralItemNode, nodes: QueryNodes): numbe const footprint = isProceduralItem(node) ? proceduralFootprint(node) : { - position: position, + position, dimensions: node.type === 'shelf' ? ([node.width, node.height, node.depth] as Vec3) @@ -256,6 +260,7 @@ function resolveNodeLevelFrame( node.supportSlabId, undefined, ground, + nodes as Record, ) return frame( [node.start[0], support.elevation + (node.supportOffset ?? 0), node.start[1]], diff --git a/packages/core/src/registry/plugin-v1-conformance.test.ts b/packages/core/src/registry/plugin-v1-conformance.test.ts index 5f9562dd9e..e1b67fc7c2 100644 --- a/packages/core/src/registry/plugin-v1-conformance.test.ts +++ b/packages/core/src/registry/plugin-v1-conformance.test.ts @@ -357,10 +357,9 @@ describe('plugin API v1: editing and reload', () => { expect(ofType(clone.nodes, 'fixture:bench').id).not.toBe(bench.id) }) - // Known v1 gap (R1 portable clone hook, owner P-03): a plugin cannot declare - // which of its fields hold node ids, so project clone and subtree duplicate - // copy them verbatim and they keep pointing at the source scene. - test.failing('project clone remaps plugin-owned node references', async () => { + // A whole-graph clone rewrites every string that is exactly a cloned node id, + // so plugin-owned references follow the clone without a declaration. + test('project clone remaps plugin-owned node references', async () => { await loadPlugin(fixturePlugin()) const planter = asSceneNode(Planter.parse({})) loadLevel([planter, asSceneNode(Marker.parse({ targetIds: [planter.id] }))]) @@ -371,6 +370,9 @@ describe('plugin API v1: editing and reload', () => { ]) }) + // Known v1 gap (R1 portable clone hook, owner P-03): a plugin cannot declare + // which of its fields hold node ids, so subtree duplicate copies them verbatim + // and they keep pointing at the source nodes. test.failing('subtree duplicate remaps plugin-owned node references', async () => { await loadPlugin(fixturePlugin()) const sprout = asSceneNode(Sprout.parse({})) diff --git a/packages/core/src/registry/registry.ts b/packages/core/src/registry/registry.ts index ba37a2529b..ecc09fb57d 100644 --- a/packages/core/src/registry/registry.ts +++ b/packages/core/src/registry/registry.ts @@ -233,7 +233,7 @@ export function isNodeKindEnabled(kind: string, installedPlugins?: readonly stri export function getSelectableKinds(): string[] { const result: string[] = [] for (const [kind, def] of nodeRegistry.entries()) { - if (def.capabilities.selectable !== undefined) { + if (def.capabilities.selectable) { result.push(kind) } } @@ -245,7 +245,7 @@ export function getSelectableKinds(): string[] { * in expression chains like `if (node.type === 'wall' || isRegistrySelectable(node.type))`. */ export function isRegistrySelectable(kind: string): boolean { - return nodeRegistry.get(kind)?.capabilities.selectable !== undefined + return Boolean(nodeRegistry.get(kind)?.capabilities.selectable) } /** Whether `node` takes part in floor-placement collision (`FloorPlacedConfig.collides`). */ diff --git a/packages/core/src/registry/scene-api.test.ts b/packages/core/src/registry/scene-api.test.ts index fee5f175ee..7e3ca91d4c 100644 --- a/packages/core/src/registry/scene-api.test.ts +++ b/packages/core/src/registry/scene-api.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, test } from 'bun:test' +import { SlabNode } from '../schema' import type { AnyNode, AnyNodeId } from '../schema/types' import { resetSceneHistoryPauseDepth } from '../store/history-control' import { createSceneApi, type SceneStoreLike } from './scene-api' @@ -203,3 +204,54 @@ describe('SceneApi snapshot / restore', () => { api.resumeHistory() }) }) + +test('SceneApi sanitizes writes over an unguarded store, including batches', () => { + const hole: [number, number][] = [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], + ] + const plate = SlabNode.parse({ + id: 'slab_api', + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + boundary: 'auto', + zoneIds: ['zone_room'], + holes: [hole], + holeMetadata: [{ source: 'room' }], + }) + const store = makeFakeStore({ [plate.id]: plate }) + let batches = 0 + store.getState().applyNodeChanges = (changes) => { + batches++ + for (const { node } of changes.create ?? []) store.getState().createNode(node) + for (const { id, data } of changes.update ?? []) store.getState().updateNode(id, data) + } + const api = createSceneApi(store) + api.update(plate.id, { polygon: [] }) + api.upsert({ ...plate, polygon: [] }) + api.applyChanges!({ update: [{ id: plate.id, data: { holeMetadata: [{ source: 'manual' }] } }] }) + expect(store.getState().nodes[plate.id]).toBe(plate) + expect(batches).toBe(0) + api.applyChanges!({ update: [{ id: plate.id, data: { polygon: [], materialPreset: 'oak' } }] }) + expect(store.getState().nodes[plate.id]).toMatchObject({ + polygon: plate.polygon, + materialPreset: 'oak', + }) + expect(batches).toBe(1) + api.upsert({ ...plate, id: 'slab_api_created' }) + api.createMany!([{ node: { ...plate, id: 'slab_api_many' } }]) + api.applyChanges!({ create: [{ node: { ...plate, id: 'slab_api_batch' } }] }) + for (const id of ['slab_api_created', 'slab_api_many', 'slab_api_batch'] as const) { + const node = store.getState().nodes[id] as SlabNode + expect(node.polygon).toEqual(plate.polygon) + expect(node.boundary).toBeUndefined() + expect(node.zoneIds).toBeUndefined() + expect(node.autoFromWalls).not.toBe(true) + } +}) diff --git a/packages/core/src/registry/scene-api.ts b/packages/core/src/registry/scene-api.ts index e06be66e9e..4257c971a4 100644 --- a/packages/core/src/registry/scene-api.ts +++ b/packages/core/src/registry/scene-api.ts @@ -1,9 +1,11 @@ import type { AnyNode, AnyNodeId } from '../schema/types' +import { filterDerivedNodeWrites } from '../store/derived-node-guard' import { activeSceneCommitNodeIds, pauseSceneHistory, resumeSceneHistory, } from '../store/history-control' + import { type CloneNodesIntoOptions, collectSubtree, @@ -97,17 +99,31 @@ export function createSceneApi(store: SceneStoreLike): SceneApi { }, update(id, patch) { + const [update] = filterDerivedNodeWrites(store.getState().nodes, { + update: [{ id, data: patch }], + }).update + if (!update) return captureIfNeeded(id) - store.getState().updateNode(id, patch) + store.getState().updateNode(id, update.data) }, upsert(node, parentId) { + if (store.getState().nodes[node.id]) { + this.update(node.id, parentId === undefined ? node : { ...node, parentId }) + return node.id + } + const [create] = filterDerivedNodeWrites(store.getState().nodes, { + create: [{ node, parentId }], + }).create + if (!create) return node.id captureIfNeeded(node.id) - store.getState().createNode(node, parentId) + store.getState().createNode(create.node, create.parentId) return node.id }, createMany(ops) { + ops = filterDerivedNodeWrites(store.getState().nodes, { create: ops }).create + if (!ops.length) return for (const op of ops) captureIfNeeded(op.node.id) const batch = store.getState().createNodes if (batch) batch(ops) @@ -115,6 +131,8 @@ export function createSceneApi(store: SceneStoreLike): SceneApi { }, applyChanges(changes) { + changes = filterDerivedNodeWrites(store.getState().nodes, changes) + if (!changes.create?.length && !changes.update?.length && !changes.delete?.length) return for (const op of changes.create ?? []) captureIfNeeded(op.node.id) for (const op of changes.update ?? []) captureIfNeeded(op.id) for (const id of changes.delete ?? []) captureIfNeeded(id) @@ -160,9 +178,9 @@ export function createSceneApi(store: SceneStoreLike): SceneApi { if (original === null) { if (current) store.getState().deleteNode(id) } else if (!current) { - store.getState().createNode(original) + this.upsert(original) } else { - store.getState().updateNode(id, original) + this.update(id, original) } }, @@ -195,7 +213,6 @@ export function createSceneApi(store: SceneStoreLike): SceneApi { const { rootId, nodes: cloned } = runCloneNodesInto(nodes, opts) const root = cloned[0] if (!root) return null - const state = store.getState() const ops: { node: AnyNode; parentId?: AnyNodeId }[] = [] for (let i = 0; i < cloned.length; i += 1) { const node = cloned[i]! @@ -205,12 +222,7 @@ export function createSceneApi(store: SceneStoreLike): SceneApi { ops.push({ node }) } } - const batch = state.createNodes - if (batch) { - batch(ops) - } else { - for (const op of ops) state.createNode(op.node, op.parentId) - } + this.createMany!(ops) return rootId }, } diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.ts index dd719383dd..306d16d95b 100644 --- a/packages/core/src/registry/types.ts +++ b/packages/core/src/registry/types.ts @@ -1687,7 +1687,7 @@ export type Capabilities = { duplicable?: boolean | DuplicableConfig deletable?: boolean groupable?: boolean - selectable?: SelectableConfig + selectable?: SelectableConfig | false /** * Whether selecting this kind should replace its rendered mesh materials * with the editor's selection tint. Defaults to `true`. Set to `false` for @@ -1901,6 +1901,12 @@ export type PaintCapability = { * by accident, normal too oblique for an unambiguous side). */ resolveRole: (args: PaintResolveArgs) => string | null + /** + * Optional: label for a role that is NOT one of the kind's declared slots. + * A slab plate resolves per-room roles carrying a zone id, which would read + * back to the user as the raw id. Return `null` to keep the derived label. + */ + roleLabel?: (node: AnyNode, role: string) => string | null /** * Build the node-update patch that applies the new material at * `role`. Returned partial is merged into the node by the editor. @@ -2056,6 +2062,12 @@ export type PaintEffectiveMaterialArgs = { role: string /** Snapshot of the scene `nodes` map — kinds whose effective material walks the parent chain (roof-segment → roof) read parents through it. */ nodes: Record + /** + * Resolve what the surface shows, falling through to the finish an unpainted + * derived role draws with (the eyedropper). A slot role's declared `default` + * stays the caller's to apply. + */ + rendered?: boolean } /** diff --git a/packages/core/src/schema/__fixtures__/node-fixtures.ts b/packages/core/src/schema/__fixtures__/node-fixtures.ts index cce3635cbd..4883f01cb0 100644 --- a/packages/core/src/schema/__fixtures__/node-fixtures.ts +++ b/packages/core/src/schema/__fixtures__/node-fixtures.ts @@ -26,6 +26,7 @@ export const NODE_REQUIRED_FIELDS: Record> = { ], }, fence: { start: [0, 0], end: [4, 0] }, + 'floor-opening': { polygon: [[0, 0], [1, 0], [1, 1], [0, 1]] }, guide: { url: 'asset://guide.png' }, item: { asset: { @@ -71,6 +72,7 @@ export const NODE_REQUIRED_FIELDS: Record> = { [4, 4], ], }, + separator: { start: [0, 0], end: [4, 0] }, wall: { start: [0, 0], end: [4, 0] }, zone: { name: 'Kitchen', diff --git a/packages/core/src/schema/host-children.test.ts b/packages/core/src/schema/host-children.test.ts index 85e9858d7a..1ec83ca748 100644 --- a/packages/core/src/schema/host-children.test.ts +++ b/packages/core/src/schema/host-children.test.ts @@ -34,15 +34,24 @@ function load(nodes: Record, rootId: string) { return JSON.parse(JSON.stringify(useScene.getState().nodes)) } -test('frozen pre-slice corpus covers every existing kind', () => { - expect(baseline.map((n) => n.type).sort()).toEqual([...NODE_KINDS].sort()) +test('frozen pre-slice corpus covers every kind predating separators', () => { + expect(baseline.map((n) => n.type).sort()).toEqual( + NODE_KINDS.filter((kind) => kind !== 'separator' && kind !== 'floor-opening').sort(), + ) }) test.each( baseline, )('pre-slice $type parses, saves and loads without changing existing fields', (saved) => { const expected = saved.type === 'column' ? { ...saved, children: [] } : saved - expect(JSON.parse(JSON.stringify(AnyNode.parse(saved)))).toEqual(expected) - const graph = { [saved.id]: expected } + const parsedExpected = + saved.type === 'zone' + ? { ...expected, boundarySeparatorIds: [], holes: [] } + : saved.type === 'door' || saved.type === 'window' + ? { ...expected, floorThresholdVersion: 1 } + : expected + expect(JSON.parse(JSON.stringify(AnyNode.parse(saved)))).toEqual(parsedExpected) + // Loading fills the schema defaults a stored node leaves out, nothing else. + const graph = { [saved.id]: parsedExpected } expect(load({ [saved.id]: saved }, saved.id)).toEqual(graph) expect(load(graph, saved.id)).toEqual(graph) }) diff --git a/packages/core/src/schema/index.ts b/packages/core/src/schema/index.ts index 72174fbe54..059154aba8 100644 --- a/packages/core/src/schema/index.ts +++ b/packages/core/src/schema/index.ts @@ -158,6 +158,7 @@ export { } from './nodes/elevator' export { EyebrowVentMaterialRole, EyebrowVentNode } from './nodes/eyebrow-vent' export { FenceBaseStyle, FenceGuardInfill, FenceNode, FenceStyle } from './nodes/fence' +export { FloorOpeningNode } from './nodes/floor-opening' export { GuideNode, GuideScaleReference } from './nodes/guide' export { computeGutterEaveY, @@ -295,6 +296,7 @@ export { type CaptureSessionReferenceInput, ScanNode, } from './nodes/scan' +export { SeparatorNode } from './nodes/separator' export { ShelfNode } from './nodes/shelf' export { migrateSiteMetadata, @@ -314,7 +316,7 @@ export { SkylightType, type SkylightTypePreset, } from './nodes/skylight' -export { MIN_SLAB_THICKNESS, SlabNode } from './nodes/slab' +export { MIN_GROUND_FLOOR_THICKNESS, MIN_SLAB_THICKNESS, SlabNode } from './nodes/slab' export { SolarPanelMaterialRole, SolarPanelNode, @@ -333,31 +335,29 @@ export { export { AttachmentSide, StairSegmentNode, StairSegmentType } from './nodes/stair-segment' export { StructuralGridNode } from './nodes/structural-grid' export { SurfaceHoleMetadata } from './nodes/surface-hole-metadata' +export { SurfacePaintRegion } from './nodes/surface-paint-region' export { TurbineVentMaterialRole, TurbineVentNode } from './nodes/turbine-vent' export { DEFAULT_UNIT_COLOR, UNIT_KINDS, type UnitKind, UnitNode } from './nodes/unit' export type { - WallBandSurfaceSlotId, - WallFaceBand, - WallFaceBandConfig, + WallFace, WallSurfaceMaterialSpec, WallSurfaceSide, WallSurfaceSlotId, WallTrimConfig, + WallTrimKind, + WallTrimSlotId, } from './nodes/wall' export { - buildEnabledWallFaceBandPatch, - buildWallFaceBandCountPatch, + getEffectiveWallFaceMaterial, getEffectiveWallSurfaceMaterial, - getWallBandSlotId, - getWallFaceBandConfig, - getWallFaceBandForHeight, getWallSurfaceMaterialSignature, - getWallSurfaceSideFromBandSlot, + getWallTrimFaces, + getWallTrimSlotId, WALL_CHAIR_RAIL_DEFAULT, WALL_CHAIR_RAIL_SLOT_DEFAULT, WALL_CROWN_DEFAULT, WALL_CROWN_SLOT_DEFAULT, - WALL_FACE_BAND_DEFAULT, + WALL_FACE_REGION_LIMIT, WALL_SKIRTING_DEFAULT, WALL_SKIRTING_SLOT_DEFAULT, WALL_SLOT_DEFAULT, @@ -368,6 +368,7 @@ export { WallAssemblyFramingKind, WallAssemblyInteriorFinish, WallAssemblySheathingMaterial, + WallFaceRegion, WallNode, WallTreatmentSide, WallTrimProfile, diff --git a/packages/core/src/schema/node-union.test.ts b/packages/core/src/schema/node-union.test.ts index f0934dc252..cf7133f1b9 100644 --- a/packages/core/src/schema/node-union.test.ts +++ b/packages/core/src/schema/node-union.test.ts @@ -115,5 +115,6 @@ describe('AnyNode', () => { const options: AnyNodeOption[] = [...AnyNode.options] expect(new Set(options.map(nodeKindOf)).size).toBe(options.length) expect(NODE_KINDS).toContain('wall') + expect(NODE_KINDS).toContain('separator') }) }) diff --git a/packages/core/src/schema/nodes/ceiling.ts b/packages/core/src/schema/nodes/ceiling.ts index f1fc555429..180d7b7322 100644 --- a/packages/core/src/schema/nodes/ceiling.ts +++ b/packages/core/src/schema/nodes/ceiling.ts @@ -4,6 +4,7 @@ import { BaseNode, nodeType, objectId } from '../base' import { MaterialSchema } from '../material' import { ItemNode } from './item' import { SurfaceHoleMetadata } from './surface-hole-metadata' +import { SurfacePaintRegion } from './surface-paint-region' export const CeilingNode = BaseNode.extend({ id: objectId('ceiling'), @@ -18,12 +19,18 @@ export const CeilingNode = BaseNode.extend({ polygon: z.array(z.tuple([z.number(), z.number()])), holes: z.array(z.array(z.tuple([z.number(), z.number()]))).default([]), holeMetadata: z.array(SurfaceHoleMetadata).default([]), + openingIds: z.array(z.string()).optional(), // Height in meters. Absent = the ceiling follows the level top: its // effective height is the same bound its write-clamp uses — // min(storey plane, lowest covering-slab underside over the polygon) // − CEILING_CLAMP_MARGIN (see `resolveCeilingHeight`). Present = an // explicit custom height, still write-clamped under that bound. height: z.number().optional(), + // Painted parts of a manual ceiling (later wins). An automatic ceiling draws + // its room's `zone.ceiling.regions` instead: it is rebuilt from the room. + regions: z.array(SurfacePaintRegion).optional(), + boundary: z.literal('auto').optional(), + zoneId: z.string().optional(), autoFromWalls: z.boolean().default(false), }).describe( dedent` @@ -32,6 +39,7 @@ export const CeilingNode = BaseNode.extend({ - holes: array of polygons representing holes in the ceiling - holeMetadata: metadata parallel to holes, used to preserve manual and auto-managed cutouts - height: explicit height in meters; absent = follows the level top automatically + - regions: painted parts of a manual ceiling ([x, z] polygons, later wins) - autoFromWalls: whether the ceiling is automatically generated from a closed wall loop `, ) diff --git a/packages/core/src/schema/nodes/door.ts b/packages/core/src/schema/nodes/door.ts index ab0aaab995..aadfd4e66b 100644 --- a/packages/core/src/schema/nodes/door.ts +++ b/packages/core/src/schema/nodes/door.ts @@ -58,6 +58,8 @@ export const DoorNode = BaseNode.extend({ position: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), rotation: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), side: z.enum(['front', 'back']).optional(), + verticalAnchor: z.enum(['wall', 'floor']).optional(), + floorThresholdVersion: z.union([z.literal(0), z.literal(1)]).default(1), wallId: z.string().optional(), // Alternative host: a roof-segment's generated wall face (base wall // under the roof or a coplanar gable end). When set, `position` is diff --git a/packages/core/src/schema/nodes/floor-opening.ts b/packages/core/src/schema/nodes/floor-opening.ts new file mode 100644 index 0000000000..12b97c7216 --- /dev/null +++ b/packages/core/src/schema/nodes/floor-opening.ts @@ -0,0 +1,23 @@ +import { z } from 'zod' +import { BaseNode, nodeType, objectId } from '../base' + +const OpeningRing = z.array(z.tuple([z.number().finite(), z.number().finite()])).min(3) + +export const FloorOpeningNode = BaseNode.extend({ + id: objectId('floor-opening'), + type: nodeType('floor-opening'), + polygon: OpeningRing, + hostZoneId: z.string().optional(), + legacyPlateCuts: z.record(z.string(), z.array(OpeningRing)).optional(), + legacyCeilingCuts: z.record(z.string(), z.array(OpeningRing)).optional(), + source: z.string().default('manual'), + ownerId: z.string().optional(), + surfaceId: z.string().optional(), + drawnOn: z.enum(['floor', 'ceiling']).default('floor'), + cutsPrimary: z.boolean().default(true), + cutsAdjacent: z.boolean().default(true), +}).describe( + 'Level-local opening intent. Floor openings cut the floor and ceiling below; ceiling openings cut the ceiling and floor above. A hosted mezzanine opening cuts only its plate.', +) + +export type FloorOpeningNode = z.infer diff --git a/packages/core/src/schema/nodes/level.ts b/packages/core/src/schema/nodes/level.ts index ee9b935381..b6a0ce436a 100644 --- a/packages/core/src/schema/nodes/level.ts +++ b/packages/core/src/schema/nodes/level.ts @@ -10,6 +10,7 @@ import type { DuctFittingNode } from './duct-fitting' import type { DuctSegmentNode } from './duct-segment' import type { DuctTerminalNode } from './duct-terminal' import type { FenceNode } from './fence' +import type { FloorOpeningNode } from './floor-opening' import type { GuideNode } from './guide' import type { HvacEquipmentNode } from './hvac-equipment' import type { ImportedMeshNode } from './imported-mesh' @@ -22,6 +23,7 @@ import type { PipeSegmentNode } from './pipe-segment' import type { PipeTrapNode } from './pipe-trap' import type { RoofNode } from './roof' import type { ScanNode } from './scan' +import type { SeparatorNode } from './separator' import type { ShelfNode } from './shelf' import type { SlabNode } from './slab' import type { SpawnNode } from './spawn' @@ -32,6 +34,8 @@ import type { ZoneNode } from './zone' type CoreLevelChildId = | WallNode['id'] + | SeparatorNode['id'] + | FloorOpeningNode['id'] | FenceNode['id'] | ColumnNode['id'] | ConstructionDimensionNode['id'] diff --git a/packages/core/src/schema/nodes/roof-segment-walls.ts b/packages/core/src/schema/nodes/roof-segment-walls.ts index 5595a2a8b2..21bebe781b 100644 --- a/packages/core/src/schema/nodes/roof-segment-walls.ts +++ b/packages/core/src/schema/nodes/roof-segment-walls.ts @@ -1,3 +1,4 @@ +import { getWallFaceOffsets } from '../../systems/wall/wall-frame' import type { RoofSegmentNode } from './roof-segment' import { getDutchRoofMetrics, getSegmentSlopeFrame } from './roof-segment' @@ -75,7 +76,7 @@ type WallVolumeFrame = { function getWallVolumeFrame(node: SegmentWallInputs): WallVolumeFrame { const { activeRh, tanTheta } = getSegmentSlopeFrame(node) const wallThickness = node.wallThickness ?? 0.1 - const autoDrop = (wallThickness / 2) * tanTheta + const autoDrop = getWallFaceOffsets({ thickness: wallThickness }).a * tanTheta const wV = Math.max(0.01, node.width + wallThickness) const dV = Math.max(0.01, node.depth + wallThickness) const eaveY = Math.max(0.05, node.wallHeight - autoDrop) diff --git a/packages/core/src/schema/nodes/room-fields.test.ts b/packages/core/src/schema/nodes/room-fields.test.ts new file mode 100644 index 0000000000..d36a2a80d1 --- /dev/null +++ b/packages/core/src/schema/nodes/room-fields.test.ts @@ -0,0 +1,74 @@ +import { expect, test } from 'bun:test' +import { AnyNode } from '../types' +import { CeilingNode } from './ceiling' +import { SlabNode } from './slab' +import { ZoneNode } from './zone' + +const polygon = [ + [0, 0], + [4, 0], + [4, 3], +] + +test('room intent fields stay sparse while boundary arrays and holes have defaults', () => { + const zone = ZoneNode.parse({ name: 'Room', polygon }) + expect(zone.boundaryWallIds).toEqual([]) + expect(zone.boundarySeparatorIds).toEqual([]) + expect(zone.holes).toEqual([]) + for (const key of ['seed', 'floor', 'wallMaterial', 'wallOverrides', 'hasFloor', 'hasCeiling']) + expect(Object.hasOwn(zone, key)).toBe(false) + expect(ZoneNode.parse({ name: 'Room', polygon, floor: {} }).floor).toEqual({}) + for (const key of ['hasFloor', 'hasCeiling']) + expect(ZoneNode.safeParse({ name: 'Room', polygon, [key]: true }).success).toBe(false) +}) + +test('room fields round-trip through the node union without changing documentation strings', () => { + const fields = { + seed: [1, 1], + floor: { + elevation: -0.2, + finish: 'library:oak', + regions: [{ id: 'region_a', polygon, finish: 'scene:tile' }], + }, + wallMaterial: 'scene:paint', + wallOverrides: [ + { wallId: 'wall_a', face: 'a', finish: 'library:paper' }, + { wallId: 'wall_b', face: 'b', finish: 'scene:paint' }, + ], + hasFloor: false, + hasCeiling: false, + boundarySeparatorIds: ['separator_a'], + holes: [polygon], + floorFinish: 'Timber', + wallFinish: 'Paint', + ceilingFinish: 'ACT', + ceilingHeight: 3.2, + } + const zone = ZoneNode.parse({ name: 'Room', polygon, ...fields }) + expect(zone).toMatchObject(fields) + expect(AnyNode.parse(zone)).toEqual(zone) +}) + +test('ceiling and slab links stay sparse and round-trip through the node union', () => { + for (const schema of [CeilingNode, SlabNode]) { + const node = schema.parse({ polygon }) + for (const key of ['boundary', 'zoneId', 'zoneIds']) + expect(Object.hasOwn(node, key)).toBe(false) + expect(schema.safeParse({ polygon, boundary: 'manual' }).success).toBe(false) + } + const ceiling = CeilingNode.parse({ polygon, zoneId: 'zone_room', boundary: 'auto' }) + const slab = SlabNode.parse({ + polygon, + zoneIds: ['zone_room'], + boundary: 'auto', + slots: { + surface: 'library:wood', + side: '#aaa', + edge: '#bbb', + riser: '#ccc', + underside: '#ddd', + }, + }) + expect(AnyNode.parse(ceiling)).toEqual(ceiling) + expect(AnyNode.parse(slab)).toEqual(slab) +}) diff --git a/packages/core/src/schema/nodes/separator.ts b/packages/core/src/schema/nodes/separator.ts new file mode 100644 index 0000000000..c7e9f34391 --- /dev/null +++ b/packages/core/src/schema/nodes/separator.ts @@ -0,0 +1,13 @@ +import { z } from 'zod' +import { BaseNode, nodeType, objectId } from '../base' + +export const SeparatorNode = BaseNode.extend({ + id: objectId('separator'), + type: nodeType('separator'), + start: z.tuple([z.number(), z.number()]), + end: z.tuple([z.number(), z.number()]), +}).describe( + 'A virtual, zero-thickness room boundary. A level child with start and end in level-local XZ metres; no physical wall body.', +) + +export type SeparatorNode = z.infer diff --git a/packages/core/src/schema/nodes/slab.ts b/packages/core/src/schema/nodes/slab.ts index 813ba5089b..cf6629854f 100644 --- a/packages/core/src/schema/nodes/slab.ts +++ b/packages/core/src/schema/nodes/slab.ts @@ -8,6 +8,10 @@ import { SurfaceHoleMetadata } from './surface-hole-metadata' // −0.01 underside offset. Applies to edits only; migration writes legacy // intervals verbatim (including degenerate zero-thickness slabs). export const MIN_SLAB_THICKNESS = 0.02 +// A ground-bearing base plate has no ceiling under it, so it may be thinner; +// it is never zero (a zero-thickness plate renders as a hole). +export const MIN_GROUND_FLOOR_THICKNESS = 0.01 +export const DEFAULT_SLAB_ELEVATION = 0.05 export const SlabNode = BaseNode.extend({ id: objectId('slab'), @@ -21,11 +25,44 @@ export const SlabNode = BaseNode.extend({ polygon: z.array(z.tuple([z.number(), z.number()])), holes: z.array(z.array(z.tuple([z.number(), z.number()]))).default([]), holeMetadata: z.array(SurfaceHoleMetadata).default([]), - elevation: z.number().default(0.05), // Walking surface (slab top), meters above the level plane + elevation: z.number().default(DEFAULT_SLAB_ELEVATION), // Walking surface (slab top), meters above the level plane + floorHeight: z + .number() + .finite() + .optional() + .describe( + 'Ground-contact base plate only: authored floor top in level-local meters; upper floors change thickness to raise their top.', + ), + referenceFloorElevation: z + .number() + .finite() + .optional() + .describe( + 'Base plate reference walking surface in level-local meters. Absent follows terrain and support. The resolved top minus this reference is the footprint lift; only an atomic floor-reference rebase may change it.', + ), + foundation: z + .object({ + type: z.enum(['solid', 'none']), + material: z.union([z.string(), MaterialSchema]).optional(), + }) + .optional(), thickness: z.number().default(0.05), // Grows downward from the surface recessed: z.boolean().default(false), recessedRimElevation: z.number().finite().optional(), fillToTerrain: z.boolean().optional(), + boundary: z.literal('auto').optional(), + support: z.literal('open').optional(), + plateRole: z.enum(['base', 'platform', 'sunken']).optional(), + railing: z + .array( + z.object({ + start: z.tuple([z.number(), z.number()]), + end: z.tuple([z.number(), z.number()]), + }), + ) + .optional(), + zoneIds: z.array(z.string()).optional(), + associatedZoneIds: z.array(z.string()).optional(), autoFromWalls: z.boolean().default(false), }).describe( dedent` @@ -34,10 +71,14 @@ export const SlabNode = BaseNode.extend({ - holes: array of [x, z] polygons representing cutouts in the slab - holeMetadata: metadata parallel to holes, used to preserve manual and auto-managed cutouts - elevation: the walking surface (slab top), in meters above the level plane + - floorHeight: ground-contact base plate authored top in level-local meters; absent follows terrain. Upper base plates use thickness with a fixed underside. + - referenceFloorElevation: base plate reference top (level-local meters); absent follows terrain and support. Ordinary floor edits keep this datum. + - associatedZoneIds: rooms whose authored construction overlaps this manual slab, resolved once during legacy migration. + - foundation: base plate exterior support to terrain; solid or none, with its own material (default concrete). - thickness: grows downward from the surface; the solid occupies [elevation - thickness, elevation] - recessed: open recess (pool) whose floor sits at elevation - recessedRimElevation: optional rim anchor for a raised/lowered recess; absent means the level plane - - fillToTerrain: extends a solid slab's perimeter downward to terrain without changing its flat top or authored thickness + - fillToTerrain: manual slabs only; extends a solid slab's perimeter downward to terrain without changing its flat top or authored thickness - autoFromWalls: whether the slab is automatically generated from a closed wall loop `, ) diff --git a/packages/core/src/schema/nodes/surface-hole-metadata.ts b/packages/core/src/schema/nodes/surface-hole-metadata.ts index a3d560e83f..52efd4b46a 100644 --- a/packages/core/src/schema/nodes/surface-hole-metadata.ts +++ b/packages/core/src/schema/nodes/surface-hole-metadata.ts @@ -2,7 +2,8 @@ import { z } from 'zod' export const SurfaceHoleMetadata = z.object({ // Stair/elevator auto-openings use stairId/elevatorId so sync can replace only its own holes. - source: z.enum(['manual', 'stair', 'elevator']).default('manual'), + source: z.enum(['manual', 'stair', 'elevator', 'room', 'floor-opening']).default('manual'), + openingId: z.string().optional(), stairId: z.string().optional(), elevatorId: z.string().optional(), }) diff --git a/packages/core/src/schema/nodes/surface-paint-region.ts b/packages/core/src/schema/nodes/surface-paint-region.ts new file mode 100644 index 0000000000..8fff5c4c4b --- /dev/null +++ b/packages/core/src/schema/nodes/surface-paint-region.ts @@ -0,0 +1,15 @@ +import { z } from 'zod' + +/** + * A painted part of a flat surface, in level XZ: a room floor + * (`zone.floor.regions`), a room's ceiling (`zone.ceiling.regions`) or a manual + * ceiling (`ceiling.regions`). Later entries win; each surface clips its + * regions to what it covers. + */ +export const SurfacePaintRegion = z.object({ + id: z.string(), + polygon: z.array(z.tuple([z.number(), z.number()])), + finish: z.union([z.string(), z.record(z.string(), z.unknown())]), +}) + +export type SurfacePaintRegion = z.infer diff --git a/packages/core/src/schema/nodes/wall.test.ts b/packages/core/src/schema/nodes/wall.test.ts index a508b0f814..7338fffed6 100644 --- a/packages/core/src/schema/nodes/wall.test.ts +++ b/packages/core/src/schema/nodes/wall.test.ts @@ -1,20 +1,12 @@ -import { describe, expect, test } from 'bun:test' import { - buildEnabledWallFaceBandPatch, - buildWallFaceBandCountPatch, - getWallFaceBandConfig, WALL_CHAIR_RAIL_DEFAULT, WALL_CHAIR_RAIL_SLOT_DEFAULT, WALL_CROWN_DEFAULT, WALL_CROWN_SLOT_DEFAULT, - WALL_FACE_BAND_DEFAULT, - WALL_FACE_BAND_SOLID_SLOT_DEFAULTS, WALL_SKIRTING_DEFAULT, WALL_SKIRTING_SLOT_DEFAULT, WALL_SURFACE_SLOT_DEFAULTS, - WallFaceBandConfig, WallNode, - type WallNode as WallNodeType, WallTrimConfig, } from './wall' @@ -37,222 +29,36 @@ describe('wall support offset', () => { }) }) -describe('wall face bands', () => { - test('defaults to one band while preserving legacy enabled scenes as three bands', () => { - expect(WALL_FACE_BAND_DEFAULT.count).toBe(1) - expect(WALL_FACE_BAND_DEFAULT.lowerHeight).toBe(0.84) - expect(WALL_FACE_BAND_DEFAULT.middleHeight).toBe(0.61) - expect(WALL_FACE_BAND_DEFAULT.upperHeight).toBe(0.61) +describe('wall face regions', () => { + const region = (id: string, face: 'a' | 'b') => ({ id, face, v1: 0.9, finish: 'library:x' }) - expect(WallFaceBandConfig.parse({})).toEqual({ - enabled: false, - count: 1, - lowerHeight: 0.84, - middleHeight: 0.61, - upperHeight: 0.61, - }) - - expect(WallFaceBandConfig.parse({ enabled: true })).toEqual({ - enabled: true, - count: 3, - lowerHeight: 0.84, - middleHeight: 0.61, - upperHeight: 0.61, + test('stores sparse bounds and at most eight regions per face', () => { + const wall = WallNode.parse({ + start: [0, 0], + end: [4, 0], + faceRegions: [{ id: 'r', face: 'a', u0: 1, finish: 'library:x' }], }) + expect(wall.faceRegions).toEqual([{ id: 'r', face: 'a', u0: 1, finish: 'library:x' }]) + const eightPerFace = [ + ...Array.from({ length: 8 }, (_, i) => region(`a${i}`, 'a')), + ...Array.from({ length: 8 }, (_, i) => region(`b${i}`, 'b')), + ] expect( - getWallFaceBandConfig( - { - height: 2.5, - faceBands: { - enabled: true, - count: 3, - lowerHeight: 0.84, - middleHeight: 0.61, - upperHeight: 0.61, - }, - }, - 2.5, - ), - ).toMatchObject({ - count: 3, - lowerTop: 0.84, - middleTop: 1.45, - }) - }) - - test('four bands adds an upper split below the final top band', () => { + WallNode.safeParse({ start: [0, 0], end: [4, 0], faceRegions: eightPerFace }).success, + ).toBe(true) expect( - getWallFaceBandConfig( - { - height: 2.5, - faceBands: { - enabled: true, - count: 4, - lowerHeight: 0.5, - middleHeight: 0.6, - upperHeight: 0.7, - }, - }, - 2.5, - ), - ).toMatchObject({ - count: 4, - lowerTop: 0.5, - middleTop: 1.1, - upperTop: 1.8, - }) - }) - - test('enabling bands seeds visible solid-color band slots', () => { - const patch = buildEnabledWallFaceBandPatch({ - faceBands: { - enabled: false, - count: 1, - lowerHeight: 0.2, - middleHeight: 0.3, - upperHeight: 0.61, - }, - slots: { - interior: 'library:interior-finish', - exterior: 'scene:exterior-finish', - lowerInterior: 'library:stale-lower', - middleExterior: 'library:stale-middle', - }, - } as Pick) - - expect(patch.faceBands).toEqual({ - enabled: true, - count: 2, - lowerHeight: 0.2, - middleHeight: 0.3, - upperHeight: 0.61, - }) - expect(patch.slots).toMatchObject({ - interior: 'library:interior-finish', - exterior: 'scene:exterior-finish', - lowerInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - upperInterior: 'library:interior-finish', - lowerExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - upperExterior: 'scene:exterior-finish', - }) - expect(patch.slots?.middleInterior).toBeUndefined() - expect(patch.slots?.middleExterior).toBeUndefined() - }) - - test('band count patch enables only the active slots', () => { - const patch = buildWallFaceBandCountPatch( - { - faceBands: { - enabled: true, - count: 4, - lowerHeight: 0.2, - middleHeight: 0.3, - upperHeight: 0.61, - }, - slots: { - interior: 'library:interior-finish', - exterior: 'scene:exterior-finish', - topInterior: 'library:stale-top', - }, - } as Pick, - 3, - ) - - expect(patch.faceBands).toMatchObject({ enabled: true, count: 3 }) - expect(patch.slots).toMatchObject({ - lowerInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperInterior: 'library:stale-top', - lowerExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperExterior: 'scene:exterior-finish', - }) - expect(patch.slots?.topInterior).toBeUndefined() - expect(patch.slots?.topExterior).toBeUndefined() - }) - - test('enabling bands replaces stale inactive band slots with solid-color defaults', () => { - const patch = buildEnabledWallFaceBandPatch({ - slots: { - lowerInterior: 'library:stale-lower', - middleInterior: 'library:stale-middle', - upperExterior: 'library:stale-upper', - }, - } as Pick) - - expect(patch.slots).toEqual({ - lowerInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - upperInterior: WALL_SURFACE_SLOT_DEFAULTS.interior, - lowerExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - upperExterior: WALL_SURFACE_SLOT_DEFAULTS.exterior, - }) - expect(patch.slots?.middleInterior).toBeUndefined() - expect(patch.slots?.middleExterior).toBeUndefined() - }) - - test('increasing band count paints newly active bands with the solid palette', () => { - const patch = buildWallFaceBandCountPatch( - { - faceBands: { - enabled: true, - count: 2, - lowerHeight: 0.2, - middleHeight: 0.3, - upperHeight: 0.61, - }, - slots: { - lowerInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - upperInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.upper, - lowerExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - upperExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.upper, - }, - } as Pick, - 3, - ) - - expect(patch.slots).toMatchObject({ - lowerInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.upper, - lowerExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.upper, - }) + WallNode.safeParse({ + start: [0, 0], + end: [4, 0], + faceRegions: [...eightPerFace, region('a8', 'a')], + }).success, + ).toBe(false) }) - test('increasing to four bands keeps the previous top material on the new top band', () => { - const patch = buildWallFaceBandCountPatch( - { - faceBands: { - enabled: true, - count: 3, - lowerHeight: 0.2, - middleHeight: 0.3, - upperHeight: 0.61, - }, - slots: { - lowerInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperInterior: 'scene:painted-top-interior', - lowerExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperExterior: 'library:painted-top-exterior', - }, - } as Pick, - 4, - ) - - expect(patch.slots).toMatchObject({ - lowerInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperInterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.upper, - topInterior: 'scene:painted-top-interior', - lowerExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower, - middleExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle, - upperExterior: WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.upper, - topExterior: 'library:painted-top-exterior', - }) + test('drops the retired face band config on parse', () => { + const wall = WallNode.parse({ start: [0, 0], end: [4, 0], faceBands: { enabled: true } }) + expect('faceBands' in wall).toBe(false) }) }) @@ -272,11 +78,11 @@ describe('wall trim profiles', () => { expect(WALL_CROWN_SLOT_DEFAULT).toBe('library:preset-white') expect(WALL_CHAIR_RAIL_SLOT_DEFAULT).toBe('library:preset-cream') - expect(WALL_SURFACE_SLOT_DEFAULTS.skirtingInterior).toBe(WALL_SKIRTING_SLOT_DEFAULT) - expect(WALL_SURFACE_SLOT_DEFAULTS.skirtingExterior).toBe(WALL_SKIRTING_SLOT_DEFAULT) - expect(WALL_SURFACE_SLOT_DEFAULTS.crownInterior).toBe(WALL_CROWN_SLOT_DEFAULT) - expect(WALL_SURFACE_SLOT_DEFAULTS.crownExterior).toBe(WALL_CROWN_SLOT_DEFAULT) - expect(WALL_SURFACE_SLOT_DEFAULTS.chairRailInterior).toBe(WALL_CHAIR_RAIL_SLOT_DEFAULT) - expect(WALL_SURFACE_SLOT_DEFAULTS.chairRailExterior).toBe(WALL_CHAIR_RAIL_SLOT_DEFAULT) + expect(WALL_SURFACE_SLOT_DEFAULTS.aSkirting).toBe(WALL_SKIRTING_SLOT_DEFAULT) + expect(WALL_SURFACE_SLOT_DEFAULTS.bSkirting).toBe(WALL_SKIRTING_SLOT_DEFAULT) + expect(WALL_SURFACE_SLOT_DEFAULTS.aCrown).toBe(WALL_CROWN_SLOT_DEFAULT) + expect(WALL_SURFACE_SLOT_DEFAULTS.bCrown).toBe(WALL_CROWN_SLOT_DEFAULT) + expect(WALL_SURFACE_SLOT_DEFAULTS.aChairRail).toBe(WALL_CHAIR_RAIL_SLOT_DEFAULT) + expect(WALL_SURFACE_SLOT_DEFAULTS.bChairRail).toBe(WALL_CHAIR_RAIL_SLOT_DEFAULT) }) }) diff --git a/packages/core/src/schema/nodes/wall.ts b/packages/core/src/schema/nodes/wall.ts index f26c4b5684..a3f4650eca 100644 --- a/packages/core/src/schema/nodes/wall.ts +++ b/packages/core/src/schema/nodes/wall.ts @@ -9,7 +9,11 @@ import { ItemNode } from './item' import { LeanToExtensionNode } from './lean-to-extension' import { WindowNode } from './window' -export const WallTreatmentSide = z.enum(['interior', 'exterior', 'both']) +// Geometric faces: `a` is left of start → end, `b` is right (wall-frame convention). +// `interior` / `exterior` are legacy semantic values the M1 load migration maps +// onto a face; a runtime writer that still sends one renders on its canonical +// face (interior → a, exterior → b). +export const WallTreatmentSide = z.enum(['a', 'b', 'both', 'interior', 'exterior']) export type WallTreatmentSide = z.infer export const WallTrimProfile = z.enum([ @@ -74,58 +78,19 @@ export const WALL_TRIM_DEFAULTS = { chairRail: WALL_CHAIR_RAIL_DEFAULT, } as const -const WallFaceBandConfigShape = z.object({ - enabled: z.boolean().default(false), - count: z.number().int().min(1).max(4).default(1), - lowerHeight: z.number().default(0.84), - middleHeight: z.number().default(0.61), - upperHeight: z.number().default(0.61), -}) - -export const WallFaceBandConfig = z.preprocess((value) => { - if (value && typeof value === 'object' && !Array.isArray(value) && !('count' in value)) { - const enabled = (value as { enabled?: unknown }).enabled === true - return { ...value, count: enabled ? 3 : 1 } - } - return value -}, WallFaceBandConfigShape) -export type WallFaceBandConfig = z.infer - -export const WALL_FACE_BAND_DEFAULT: WallFaceBandConfig = { - enabled: false, - count: 1, - lowerHeight: 0.84, - middleHeight: 0.61, - upperHeight: 0.61, -} - export const WALL_SKIRTING_SLOT_DEFAULT = 'library:preset-softwhite' export const WALL_CROWN_SLOT_DEFAULT = 'library:preset-white' export const WALL_CHAIR_RAIL_SLOT_DEFAULT = 'library:preset-cream' -export const WALL_FACE_BAND_SOLID_SLOT_DEFAULTS = { - lower: 'library:preset-white', - middle: 'library:preset-lightgrey', - upper: 'library:preset-greige', - top: 'library:preset-softwhite', -} as const satisfies Record export const WALL_SURFACE_SLOT_DEFAULTS = { - interior: 'library:concrete-drywall', - exterior: 'library:concrete-drywall', - lowerInterior: 'library:concrete-drywall', - middleInterior: 'library:concrete-drywall', - upperInterior: 'library:concrete-drywall', - topInterior: 'library:concrete-drywall', - lowerExterior: 'library:concrete-drywall', - middleExterior: 'library:concrete-drywall', - upperExterior: 'library:concrete-drywall', - topExterior: 'library:concrete-drywall', - skirtingInterior: WALL_SKIRTING_SLOT_DEFAULT, - skirtingExterior: WALL_SKIRTING_SLOT_DEFAULT, - crownInterior: WALL_CROWN_SLOT_DEFAULT, - crownExterior: WALL_CROWN_SLOT_DEFAULT, - chairRailInterior: WALL_CHAIR_RAIL_SLOT_DEFAULT, - chairRailExterior: WALL_CHAIR_RAIL_SLOT_DEFAULT, + a: 'library:concrete-drywall', + b: 'library:concrete-drywall', + aSkirting: WALL_SKIRTING_SLOT_DEFAULT, + bSkirting: WALL_SKIRTING_SLOT_DEFAULT, + aCrown: WALL_CROWN_SLOT_DEFAULT, + bCrown: WALL_CROWN_SLOT_DEFAULT, + aChairRail: WALL_CHAIR_RAIL_SLOT_DEFAULT, + bChairRail: WALL_CHAIR_RAIL_SLOT_DEFAULT, // The foundation under a wall's underpinning (see WallNode.underpinning): // the concrete stemwall between the finish carried down over the floor // platform and the ground. @@ -133,6 +98,29 @@ export const WALL_SURFACE_SLOT_DEFAULTS = { } as const export type WallSurfaceSlotId = keyof typeof WALL_SURFACE_SLOT_DEFAULTS +export type WallFace = 'a' | 'b' + +export const WALL_FACE_REGION_LIMIT = 8 + +// A paint region overrides one face's finish inside a rectangle without cutting +// the wall. `u` is metres from the wall start along the reference line (along +// the chord for curved walls); `v` is metres above the face's own base. An +// absent bound runs to that edge, so a wainscot stretches with the wall. +export const WallFaceRegion = z.object({ + id: z.string(), + face: z.enum(['a', 'b']), + u0: z.number().finite().optional(), + u1: z.number().finite().optional(), + v0: z.number().finite().optional(), + v1: z.number().finite().optional(), + finish: z.string(), +}) +export type WallFaceRegion = z.infer + +const WallSurfaceMaterialSpecSchema = z.object({ + material: MaterialSchema.optional(), + materialPreset: z.string().optional(), +}) /** * What a wall carries BELOW its base on a house standing above the ground: @@ -263,12 +251,33 @@ export const WallNode = BaseNode.extend({ exteriorMaterial: MaterialSchema.optional(), exteriorMaterialPreset: z.string().optional(), // Per-slot material overrides on the unified slot model, mirroring - // `SlabNode.slots`. Key = slot id (`interior` / `exterior`), value = a - // `MaterialRef` (`library:` / `scene:`). Absent = the declared slot - // default (`WALL_SLOT_DEFAULT`). The legacy `*Material*` fields above are - // read only by the load migration that moves them into `slots`; delete them - // in a follow-up once migrated scenes are the norm. + // `SlabNode.slots`. Key = geometric slot id (`a` / `b` faces, `aSkirting` … + // trims), value = a `MaterialRef` (`library:` / `scene:`). Absent = + // the declared slot default (`WALL_SLOT_DEFAULT`). Legacy `interior` / + // `exterior` keys are rewritten by the M1 load migration. slots: z.record(z.string(), z.string()).optional(), + // Legacy per-face inline finish, written only by the M1 load migration from + // `interiorMaterial*` / `exteriorMaterial*` so a face keeps the fallback it + // rendered with. Read after `slots[face]`, before `material` / `materialPreset`. + legacyFaceMaterials: z + .object({ + a: WallSurfaceMaterialSpecSchema.optional(), + b: WallSurfaceMaterialSpecSchema.optional(), + }) + .optional(), + // Later entries win; at most WALL_FACE_REGION_LIMIT per face. + faceRegions: z + .array(WallFaceRegion) + .superRefine((regions, ctx) => { + for (const face of ['a', 'b'] as const) { + if (regions.filter((region) => region.face === face).length > WALL_FACE_REGION_LIMIT) + ctx.addIssue({ + code: 'custom', + message: `At most ${WALL_FACE_REGION_LIMIT} paint regions per wall face`, + }) + } + }) + .optional(), // TOTAL wall thickness in metres — the one number every consumer reads. // The sum of `assembly`'s layers whenever an assembly is present. thickness: z.number().optional(), @@ -276,6 +285,8 @@ export const WallNode = BaseNode.extend({ // slab of `thickness`. Present = the stack sets `thickness`: edit the layers // and write their sum (`wallAssemblyPatch`), never `thickness` alone. assembly: Assembly.optional(), + // Absent centers the body; a/b place it left/right of the stored start → end line. + justification: z.enum(['a', 'b']).optional(), height: z.number().optional(), curveOffset: z.number().optional(), // Persisted slab-support host — see ItemNode.supportSlabId for the rules. @@ -288,14 +299,14 @@ export const WallNode = BaseNode.extend({ fillToTerrain: z.boolean().optional(), // The finish and the foundation carried below the base — see WallUnderpinning. underpinning: WallUnderpinning.optional(), - faceBands: WallFaceBandConfig.optional(), skirting: WallTrimConfig.optional(), crown: WallTrimConfig.optional(), chairRail: WallTrimConfig.optional(), // e.g., start/end points for path start: z.tuple([z.number(), z.number()]), end: z.tuple([z.number(), z.number()]), - // Space detection for cutaway mode + // Derived room classification per face, still written by the structure + // kernel for cutaway and dimension readers. Wall finishes never read it. frontSide: z.enum(['interior', 'exterior', 'unknown']).default('unknown'), backSide: z.enum(['interior', 'exterior', 'unknown']).default('unknown'), }).describe( @@ -318,187 +329,31 @@ export const WallNode = BaseNode.extend({ ) export type WallNode = z.infer +/** Legacy semantic side, read only by load migrations. */ export type WallSurfaceSide = 'interior' | 'exterior' -export type WallFaceBand = 'lower' | 'middle' | 'upper' | 'top' -export type WallBandSurfaceSlotId = - | 'lowerInterior' - | 'middleInterior' - | 'upperInterior' - | 'topInterior' - | 'lowerExterior' - | 'middleExterior' - | 'upperExterior' - | 'topExterior' // Declared default appearance for an unpainted wall face in colored mode — // visual parity with the retired DEFAULT_WALL_MATERIAL. Lives in core so the // slot declaration (nodes) and the material resolver (viewer) share one value. // May be a `#rrggbb` colour or a `library:` ref. Textures-off still // collapses to the themed wall role (the escape hatch). -export const WALL_SLOT_DEFAULT: Record = { - interior: WALL_SURFACE_SLOT_DEFAULTS.interior, - exterior: WALL_SURFACE_SLOT_DEFAULTS.exterior, +export const WALL_SLOT_DEFAULT: Record = { + a: WALL_SURFACE_SLOT_DEFAULTS.a, + b: WALL_SURFACE_SLOT_DEFAULTS.b, } -export function getWallFaceBandConfig( - wall: Pick, - effectiveWallHeight: number, -) { - const wallHeight = Math.max(0, effectiveWallHeight) - const raw = { ...WALL_FACE_BAND_DEFAULT, ...(wall.faceBands ?? {}) } - const count = raw.enabled ? Math.max(1, Math.min(4, Math.round(raw.count ?? 3))) : 1 - const lowerHeight = count >= 2 ? Math.max(0, Math.min(wallHeight, raw.lowerHeight)) : 0 - const middleHeight = - count >= 3 ? Math.max(0, Math.min(wallHeight - lowerHeight, raw.middleHeight)) : 0 - const upperHeight = - count >= 4 ? Math.max(0, Math.min(wallHeight - lowerHeight - middleHeight, raw.upperHeight)) : 0 +export type WallTrimKind = 'skirting' | 'crown' | 'chairRail' +export type WallTrimSlotId = `${WallFace}${'Skirting' | 'Crown' | 'ChairRail'}` - return { - enabled: raw.enabled && count > 1, - count, - lowerHeight, - middleHeight, - upperHeight, - lowerTop: lowerHeight, - middleTop: lowerHeight + middleHeight, - upperTop: lowerHeight + middleHeight + upperHeight, - } +export function getWallTrimSlotId(face: WallFace, kind: WallTrimKind): WallTrimSlotId { + return `${face}${kind === 'skirting' ? 'Skirting' : kind === 'crown' ? 'Crown' : 'ChairRail'}` } -export function getWallFaceBandForHeight( - wall: Pick, - y: number, - effectiveWallHeight: number, -): WallFaceBand { - const bands = getWallFaceBandConfig(wall, effectiveWallHeight) - if (!bands.enabled) return 'upper' - if (y < bands.lowerTop) return 'lower' - if (y < bands.middleTop) return 'middle' - if (bands.count >= 4 && y < bands.upperTop) return 'upper' - if (bands.count >= 4) return 'top' - return 'upper' -} - -export function getWallBandSlotId( - side: WallSurfaceSide, - band: WallFaceBand, -): WallBandSurfaceSlotId { - const suffix = side === 'interior' ? 'Interior' : 'Exterior' - return `${band}${suffix}` as WallBandSurfaceSlotId -} - -const WALL_FACE_BAND_SLOTS_BY_SIDE = { - interior: ['lowerInterior', 'middleInterior', 'upperInterior', 'topInterior'], - exterior: ['lowerExterior', 'middleExterior', 'upperExterior', 'topExterior'], -} as const satisfies Record - -function getWallFaceBandSlotsForCount( - side: WallSurfaceSide, - count: number, -): readonly WallBandSurfaceSlotId[] { - if (count <= 1) return [] - if (side === 'interior') { - if (count === 2) return ['lowerInterior', 'upperInterior'] - if (count === 3) return ['lowerInterior', 'middleInterior', 'upperInterior'] - return ['lowerInterior', 'middleInterior', 'upperInterior', 'topInterior'] - } - - if (count === 2) return ['lowerExterior', 'upperExterior'] - if (count === 3) return ['lowerExterior', 'middleExterior', 'upperExterior'] - return ['lowerExterior', 'middleExterior', 'upperExterior', 'topExterior'] -} - -function getWallFaceBandDefaultSlot(slotId: WallBandSurfaceSlotId): string { - if (slotId.startsWith('lower')) return WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.lower - if (slotId.startsWith('middle')) return WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.middle - if (slotId.startsWith('top')) return WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.top - return WALL_FACE_BAND_SOLID_SLOT_DEFAULTS.upper -} - -function getWallFaceTopBandSlot( - side: WallSurfaceSide, - count: number, -): WallBandSurfaceSlotId | null { - const slots = getWallFaceBandSlotsForCount(side, count) - return slots[slots.length - 1] ?? null -} - -export function buildWallFaceBandCountPatch( - wall: Pick, - count: number, -): Pick { - const slots = { ...(wall.slots ?? {}) } - const nextCount = Math.max(1, Math.min(4, Math.round(count))) - const previousCount = wall.faceBands?.enabled - ? Math.max(1, Math.min(4, Math.round(wall.faceBands.count ?? 3))) - : 1 - - for (const side of ['interior', 'exterior'] as const) { - const nextSlots = getWallFaceBandSlotsForCount(side, nextCount) - const activeSlots = new Set(nextSlots) - const previouslyActiveSlots = new Set(getWallFaceBandSlotsForCount(side, previousCount)) - const previousTopSlot = getWallFaceTopBandSlot(side, previousCount) - const nextTopSlot = getWallFaceTopBandSlot(side, nextCount) - const topMaterial = - (previousTopSlot ? slots[previousTopSlot] : undefined) ?? - slots[side] ?? - WALL_SURFACE_SLOT_DEFAULTS[side] - for (const slotId of WALL_FACE_BAND_SLOTS_BY_SIDE[side]) { - if (activeSlots.has(slotId)) { - if (slotId === nextTopSlot) { - slots[slotId] = topMaterial - continue - } - const wasActive = previouslyActiveSlots.has(slotId) - const wasPreviousTop = slotId === previousTopSlot - if (!wasActive || wasPreviousTop || !slots[slotId]) { - slots[slotId] = getWallFaceBandDefaultSlot(slotId) - } - } else { - delete slots[slotId] - } - } - } - - return { - faceBands: { - ...WALL_FACE_BAND_DEFAULT, - ...(wall.faceBands ?? {}), - enabled: nextCount > 1, - count: nextCount, - lowerHeight: wall.faceBands?.lowerHeight ?? WALL_FACE_BAND_DEFAULT.lowerHeight, - middleHeight: wall.faceBands?.middleHeight ?? WALL_FACE_BAND_DEFAULT.middleHeight, - upperHeight: wall.faceBands?.upperHeight ?? WALL_FACE_BAND_DEFAULT.upperHeight, - }, - slots, - } -} - -export function buildEnabledWallFaceBandPatch( - wall: Pick, -): Pick { - return buildWallFaceBandCountPatch(wall, 2) -} - -export function getWallSurfaceSideFromBandSlot(slotId: string): WallSurfaceSide | null { - if (slotId === 'interior' || slotId === 'exterior') return slotId - if ( - slotId === 'lowerInterior' || - slotId === 'middleInterior' || - slotId === 'upperInterior' || - slotId === 'topInterior' - ) { - return 'interior' - } - if ( - slotId === 'lowerExterior' || - slotId === 'middleExterior' || - slotId === 'upperExterior' || - slotId === 'topExterior' - ) { - return 'exterior' - } - return null +/** Faces a trim config draws on. Legacy semantic values use their canonical face. */ +export function getWallTrimFaces(sides: WallTreatmentSide | undefined): WallFace[] { + if (sides === 'a' || sides === 'interior') return ['a'] + if (sides === 'b' || sides === 'exterior') return ['b'] + return ['a', 'b'] } export type WallSurfaceMaterialSpec = { @@ -551,6 +406,22 @@ export function getEffectiveWallSurfaceMaterial( } } +type WallFaceMaterialSource = WallSurfaceMaterialSource & { + legacyFaceMaterials?: WallNode['legacyFaceMaterials'] +} + +/** A face's legacy inline finish: its migrated per-face spec, else the wall-wide legacy fields. */ +export function getEffectiveWallFaceMaterial( + wall: WallFaceMaterialSource, + face: WallFace, +): WallSurfaceMaterialSpec { + const configured = wall.legacyFaceMaterials?.[face] + if (configured && hasSurfaceMaterial(configured)) { + return { material: configured.material, materialPreset: configured.materialPreset } + } + return { material: wall.material, materialPreset: wall.materialPreset } +} + export function getWallSurfaceMaterialSignature(spec: WallSurfaceMaterialSpec): string { return JSON.stringify({ material: spec.material ?? null, diff --git a/packages/core/src/schema/nodes/window.ts b/packages/core/src/schema/nodes/window.ts index 1cc3b23666..32f1b76172 100644 --- a/packages/core/src/schema/nodes/window.ts +++ b/packages/core/src/schema/nodes/window.ts @@ -39,6 +39,8 @@ export const WindowNode = BaseNode.extend({ position: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), rotation: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), side: z.enum(['front', 'back']).optional(), + verticalAnchor: z.enum(['wall', 'floor']).optional(), + floorThresholdVersion: z.union([z.literal(0), z.literal(1)]).default(1), // Wall reference wallId: z.string().optional(), diff --git a/packages/core/src/schema/nodes/zone.ts b/packages/core/src/schema/nodes/zone.ts index 3a3ba90bdb..f87247850e 100644 --- a/packages/core/src/schema/nodes/zone.ts +++ b/packages/core/src/schema/nodes/zone.ts @@ -1,6 +1,7 @@ import dedent from 'dedent' import { z } from 'zod' import { BaseNode, nodeType, objectId } from '../base' +import { SurfacePaintRegion } from './surface-paint-region' export const ZoneNode = BaseNode.extend({ id: objectId('zone'), @@ -10,8 +11,55 @@ export const ZoneNode = BaseNode.extend({ polygon: z.array(z.tuple([z.number(), z.number()])), // Procedural room zones retain the walls that prove their enclosure. The // stored polygon remains a fallback for missing or temporarily open walls. + holes: z.array(z.array(z.tuple([z.number(), z.number()]))).default([]), autoFromWalls: z.boolean().default(false), boundaryWallIds: z.array(objectId('wall')).default([]), + boundarySeparatorIds: z.array(z.string()).default([]), + hostZoneId: z.string().optional(), + seed: z.tuple([z.number(), z.number()]).optional(), + floor: z + .object({ + elevation: z.number().optional(), + support: z.literal('open').optional(), + footprint: z.string().min(1).optional(), + thickness: z.number().min(0.02).optional(), + sourceSlabId: z.templateLiteral(['slab_', z.string()]).optional(), + finish: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(), + regions: z.array(SurfacePaintRegion).optional(), + }) + .optional(), + // Painted parts of the room's ceiling. The automatic ceilings are rebuilt + // from the room, so what the user painted on them lives here. + ceiling: z + .object({ + regions: z.array(SurfacePaintRegion).optional(), + }) + .optional(), + floorStepFinish: z.string().optional(), + // Per-doorway step paint over `floorStepFinish`, keyed by the door the step + // sits under or the lower room it looks at (see `lib/floor-step-finish`). + floorStepOverrides: z + .array( + z.object({ + key: z.string(), + step: z.number().int().min(0).optional(), + finish: z.string(), + }), + ) + .optional(), + floorEdgeFinish: z.string().optional(), + wallMaterial: z.string().optional(), + wallOverrides: z + .array( + z.object({ + wallId: z.string(), + face: z.enum(['a', 'b']), + finish: z.string(), + }), + ) + .optional(), + hasFloor: z.literal(false).optional(), + hasCeiling: z.literal(false).optional(), // Generic zones remain available for sites and analysis. Architectural // room documentation is opt-in so legacy zone behavior is unchanged. spaceRole: z.enum(['generic', 'room']).default('generic'), @@ -38,6 +86,8 @@ export const ZoneNode = BaseNode.extend({ - boundaryWallIds: wall ids that prove the procedural enclosure - spaceRole: generic site/analysis zone or architectural room - roomNumber/finishes/ceilingHeight/occupancy: construction-document room metadata + - floor.regions / ceiling.regions: painted parts of the room's floor and ceiling ([x, z] polygons, later wins) + - floorStepFinish: finish of the room's steps; floorStepOverrides: per-doorway step finishes keyed by door id (or the lower room id), optional step index - enclosureStatus: auto-detected, explicitly enclosed, or open - clearDimensionPolicy: optional room clear-dimension datum preference - color: hex color for visual styling diff --git a/packages/core/src/schema/types.ts b/packages/core/src/schema/types.ts index dcdbe9b576..6668c4d05d 100644 --- a/packages/core/src/schema/types.ts +++ b/packages/core/src/schema/types.ts @@ -18,6 +18,7 @@ import { DuctTerminalNode } from './nodes/duct-terminal' import { ElevatorNode } from './nodes/elevator' import { EyebrowVentNode } from './nodes/eyebrow-vent' import { FenceNode } from './nodes/fence' +import { FloorOpeningNode } from './nodes/floor-opening' import { GuideNode } from './nodes/guide' import { GutterNode } from './nodes/gutter' import { HvacEquipmentNode } from './nodes/hvac-equipment' @@ -35,6 +36,7 @@ import { RidgeVentNode } from './nodes/ridge-vent' import { RoofNode } from './nodes/roof' import { RoofSegmentNode } from './nodes/roof-segment' import { ScanNode } from './nodes/scan' +import { SeparatorNode } from './nodes/separator' import { ShelfNode } from './nodes/shelf' import { SiteNode } from './nodes/site' import { SkylightNode } from './nodes/skylight' @@ -96,6 +98,8 @@ export const AnyNode = nodeUnion([ BlockNode, StructuralGridNode, WallNode, + SeparatorNode, + FloorOpeningNode, FenceNode, CabinetNode, CabinetModuleNode, diff --git a/packages/core/src/services/alignment-anchors.ts b/packages/core/src/services/alignment-anchors.ts index 9930f18d57..aa2d25b9e2 100644 --- a/packages/core/src/services/alignment-anchors.ts +++ b/packages/core/src/services/alignment-anchors.ts @@ -1,3 +1,4 @@ +import { getWallFaceOffsets, type WallJustification } from '../systems/wall/wall-frame' /** * Node → alignment-anchor adapters. * @@ -204,6 +205,7 @@ export function wallSegmentAnchors( start: readonly [number, number], end: readonly [number, number], thickness?: number, + justification?: WallJustification, ): AlignmentAnchor[] { const anchors: AlignmentAnchor[] = [ { nodeId: id, kind: 'corner', x: start[0], z: start[1] }, @@ -217,12 +219,14 @@ export function wallSegmentAnchors( const len = Math.hypot(dx, dz) if (len > 1e-6) { // Perpendicular to the wall axis, scaled to half-thickness. - const half = thickness / 2 - const px = (-dz / len) * half - const pz = (dx / len) * half + const { a, b } = getWallFaceOffsets({ thickness, justification }) + const px = (-dz / len) * a + const pz = (dx / len) * a + const rx = (-dz / len) * -b + const rz = (dx / len) * -b for (const [bx, bz] of [start, end] as const) { anchors.push({ nodeId: id, kind: 'corner', x: bx + px, z: bz + pz }) - anchors.push({ nodeId: id, kind: 'corner', x: bx - px, z: bz - pz }) + anchors.push({ nodeId: id, kind: 'corner', x: bx - rx, z: bz - rz }) } } } @@ -263,7 +267,13 @@ export function nodeAlignmentAnchors( } // Wall thickness is schema-optional (falls back to the geometry default); // fence always carries one. Either way, pass it through so faces align. - return wallSegmentAnchors(seg.id, seg.start, seg.end, seg.thickness ?? DEFAULT_WALL_THICKNESS) + return wallSegmentAnchors( + seg.id, + seg.start, + seg.end, + seg.thickness ?? DEFAULT_WALL_THICKNESS, + node.type === 'wall' ? node.justification : undefined, + ) } if (node.type === 'slab' || node.type === 'ceiling') { const poly = (node as { polygon?: [number, number][] }).polygon diff --git a/packages/core/src/services/level-height.ts b/packages/core/src/services/level-height.ts index 871303c41b..ef37c5a0b4 100644 --- a/packages/core/src/services/level-height.ts +++ b/packages/core/src/services/level-height.ts @@ -1,7 +1,6 @@ import type { CeilingNode, LevelNode, SlabNode, WallNode } from '../schema' import type { AnyNode, AnyNodeId } from '../schema/types' import { computeWallSlabSupport, pointInPolygon } from '../systems/slab/slab-support' -import { resolveWallTop } from '../systems/wall/wall-top' // Cycle with ./storey (it imports DEFAULT_LEVEL_HEIGHT from here) is safe: // both sides only reference the other inside function bodies. import { CEILING_CLAMP_MARGIN, getCeilingClampBound } from './storey' @@ -35,7 +34,7 @@ export function deriveLegacyLevelHeight( const level = nodes[levelId as LevelNode['id']] as LevelNode | undefined if (!level) return DEFAULT_LEVEL_HEIGHT - const levelChildren = level.children + const levelChildren = (level.children ?? []) .map((childId) => nodes[childId as keyof typeof nodes]) .filter((child): child is AnyNode => child !== undefined) const slabs = levelChildren.filter((child): child is SlabNode => child.type === 'slab') @@ -58,11 +57,19 @@ export function deriveLegacyLevelHeight( end: wall.end, curveOffset: wall.curveOffset, thickness: wall.thickness, + justification: wall.justification, }, slabs, walls, + undefined, + undefined, + 0, + nodes, ).elevation - const top = resolveWallTop(wall, level.height ?? DEFAULT_LEVEL_HEIGHT, electedElevation) + const top = + wall.height == null + ? (level.height ?? DEFAULT_LEVEL_HEIGHT) + : Math.max(0, electedElevation) + wall.height if (top > maxTop) maxTop = top } } diff --git a/packages/core/src/services/storey.ts b/packages/core/src/services/storey.ts index 7050239579..60ce246204 100644 --- a/packages/core/src/services/storey.ts +++ b/packages/core/src/services/storey.ts @@ -1,3 +1,6 @@ +import { footprintLift } from '../lib/floor-foundation-datum' +import { levelConstructionDisplacements } from '../lib/floor-foundation-stack' +import { area, intersection } from '../lib/polygon-boolean' import type { BuildingNode, LevelNode, SlabNode, WallNode } from '../schema' import type { AnyNode, AnyNodeId } from '../schema/types' import { @@ -61,9 +64,25 @@ function resolveLevelBuildingId( // frame (WallCutout), which rebuilt an identical Map 1000+ times a frame. Weakly // keyed so a closed project's node graph is not pinned by the memo. const elevationMemo = new WeakMap>() +const authoredElevationMemo = new WeakMap>() export function getLevelElevations(nodes: Record): Map { - const memoized = elevationMemo.get(nodes) + const hit = elevationMemo.get(nodes) + if (hit) return hit + const elevations = new Map(getAuthoredLevelElevations(nodes)) + if (Object.values(nodes).some((node) => node.type === 'slab' && node.plateRole === 'base')) + for (const [id, lift] of levelConstructionDisplacements(nodes)) { + const entry = elevations.get(id)! + if (lift) elevations.set(id, { ...entry, baseY: entry.baseY + lift }) + } + elevationMemo.set(nodes, elevations) + return elevations +} + +export function getAuthoredLevelElevations( + nodes: Readonly>, +): Map { + const memoized = authoredElevationMemo.get(nodes) if (memoized) return memoized const buildings = Object.values(nodes).filter( @@ -97,7 +116,7 @@ export function getLevelElevations(nodes: Record): Map } +const coveringMemo = new WeakMap< + object, + Map +>() + /** * Storey height of the queried level plus the level-above's covering * (non-recessed) slabs. `null` when `levelId` doesn't resolve to a level. @@ -217,6 +243,20 @@ function resolveCoveringSlabContext( levelId: string, nodes: Record, ): CoveringSlabContext | null { + const sources = Object.values(nodes) + let memo = coveringMemo.get(nodes) + if (!memo) { + memo = new Map() + coveringMemo.set(nodes, memo) + } + const cached = memo.get(levelId) + // Reconciliation replaces entries in its working graph before returning it. + if ( + cached && + sources.length === cached.sources.length && + sources.every((node, i) => node === cached.sources[i]) + ) + return cached.context const level = nodes[levelId as LevelNode['id']] if (level?.type !== 'level') return null @@ -235,12 +275,28 @@ function resolveCoveringSlabContext( slabs.push(slab) } - return { - floorToFloorHeight: - resolveLevelFloorToFloorHeight(levelId, elevations) ?? - getStoredLevelHeight(level as LevelNode), + const floorToFloorHeight = + resolveLevelFloorToFloorHeight(levelId, elevations) ?? getStoredLevelHeight(level) + const footprints = Object.values(nodes).flatMap((slab) => + slab.type === 'slab' && slab.parentId === levelId && slab.plateRole === 'base' + ? [{ slab, lift: footprintLift(nodes, slab) }] + : [], + ) + const authoredHeight = + resolveLevelFloorToFloorHeight(levelId, getAuthoredLevelElevations(nodes)) ?? + getStoredLevelHeight(level) + const context = { + floorToFloorHeight, + planeHeight: authoredHeight, slabs, + footprintPlanes: footprints.map(({ slab, lift }) => ({ + slab, + top: authoredHeight + lift, + })), } + + memo.set(levelId, { sources, context }) + return context } /** @@ -340,10 +396,43 @@ export function getWallPlaneTop( levelId: string, nodes: Record, ): number { + return wallPlaneTop(wall, resolveCoveringSlabContext(levelId, nodes)) +} + +export function getWallCoveringSlabUnderside( + wall: Pick & Partial>, + levelId: string, + nodes: Record, +): number | null { + const context = resolveCoveringSlabContext(levelId, nodes) + if (!context) return null + const undersides = context.slabs + .filter((slab) => wallOverlapsSlabFootprint(wall, slab.polygon, slab.holes)) + .map((slab) => coveringUndersideY(context.floorToFloorHeight, slab)) + return undersides.length ? Math.min(...undersides) : null +} + +export function getWallPlaneTops( + walls: readonly WallNode[], + levelId: string, + nodes: Record, +): Map { const context = resolveCoveringSlabContext(levelId, nodes) + return new Map(walls.map((wall) => [wall.id, wallPlaneTop(wall, context)])) +} + +function wallPlaneTop( + wall: Pick & Partial>, + context: CoveringSlabContext | null, +): number { if (!context) return DEFAULT_LEVEL_HEIGHT - let plane = context.floorToFloorHeight + const footprints = context.footprintPlanes.filter(({ slab }) => + wallOverlapsSlabFootprint(wall, slab.polygon), + ) + let plane = footprints.length + ? Math.max(...footprints.map(({ top }) => top)) + : context.planeHeight for (const slab of context.slabs) { const underside = coveringUndersideY(context.floorToFloorHeight, slab) if (underside >= plane) continue @@ -371,11 +460,18 @@ export function getCeilingClampBound( levelId: string, nodes: Record, polygon: ReadonlyArray<[number, number]>, + wallTop?: number, ): number { const context = resolveCoveringSlabContext(levelId, nodes) if (!context) return Number.POSITIVE_INFINITY - let bound = context.floorToFloorHeight + const footprints = context.footprintPlanes.filter( + ({ slab }) => area(intersection(slab.polygon, [...polygon])) > 1e-6, + ) + let bound = footprints.length + ? Math.min(...footprints.map(({ top }) => top)) + : context.planeHeight + if (wallTop !== undefined) bound = Math.max(bound, wallTop) if (polygon.length > 0) { let cx = 0 let cz = 0 diff --git a/packages/core/src/services/surface-hosting.ts b/packages/core/src/services/surface-hosting.ts index 5926f992b9..00e4921f18 100644 --- a/packages/core/src/services/surface-hosting.ts +++ b/packages/core/src/services/surface-hosting.ts @@ -85,6 +85,8 @@ export const NON_PHYSICAL_HOST_KINDS: readonly string[] = [ 'construction-dimension', 'lineset', 'structural-grid', + 'separator', + 'floor-opening', 'spawn', 'zone', 'unit', diff --git a/packages/core/src/store/actions/node-actions.ts b/packages/core/src/store/actions/node-actions.ts index f35b165f27..58ca5d0439 100644 --- a/packages/core/src/store/actions/node-actions.ts +++ b/packages/core/src/store/actions/node-actions.ts @@ -1,3 +1,7 @@ +import { planWallDeletion } from '../../commands/structure/plan-wall-deletion' +import type { StructurePlan } from '../../commands/structure/shared' +import { withoutFloorStepOverrideKeys } from '../../lib/floor-step-finish' +import { isSpaceDetectionPaused } from '../../lib/space-detection' import { nodeRegistry } from '../../registry/registry' import { validateNodeRelations } from '../../registry/validate-relations' import { @@ -33,9 +37,20 @@ import { areWallsCollinearAcrossPoint, buildMergedWallAttachmentUpdates, getWallEndpointAtPoint, + mergeWallFaceRegions, + planMergedZoneReferences, resolveMergedWallEndpoints, type WallAttachmentUpdate, } from '../../systems/wall/wall-merge' +import { + convertDerivedPlateHoleWrites, + DERIVED_WRITER_TOKEN, + type DerivedWriteOptions, + derivedDeletionIntent, + derivedDetachPatch, + filterDerivedNodeWrites, + isDerivedNode, +} from '../derived-node-guard' import { activeSceneCommitNodeIds, addActiveSceneCommitNodeIds, @@ -53,7 +68,9 @@ type WallMergePlan = { mergedStart: [number, number] mergedEnd: [number, number] mergedChildren: WallNode['children'] + mergedFaceRegions: WallNode['faceRegions'] attachmentUpdates: WallAttachmentUpdate[] + zoneUpdates: Array<{ id: AnyNodeId; data: Partial }> } const DEFAULT_RIDGE_VENT_REFRESH_FIELDS = new Set([ @@ -1092,6 +1109,10 @@ function buildWallMergePlans( } const { start, end } = resolveMergedWallEndpoints(primary, secondary, junction) + // A heal that would repaint a room or overflow a side's regions leaves the walls split. + const mergedFaceRegions = mergeWallFaceRegions([primary, secondary], start, end) + const zoneUpdates = planMergedZoneReferences(nodes, primary, secondary, start, end) + if (!(mergedFaceRegions && zoneUpdates)) continue const mergedChildren = Array.from( new Set([...(primary.children ?? []), ...(secondary.children ?? [])]), ) as WallNode['children'] @@ -1110,7 +1131,9 @@ function buildWallMergePlans( mergedStart: start, mergedEnd: end, mergedChildren, + mergedFaceRegions: mergedFaceRegions.length > 0 ? mergedFaceRegions : undefined, attachmentUpdates, + zoneUpdates, }) usedWallIds.add(primary.id) usedWallIds.add(secondary.id) @@ -1124,8 +1147,11 @@ const createNodesActionImpl = ( set: (fn: (state: SceneState) => Partial) => void, get: () => SceneState, ops: NodeCreateOp[], + options?: DerivedWriteOptions, ) => { if (get().readOnly) return + ops = filterDerivedNodeWrites(get().nodes, { create: ops }, options).create + if (!ops.length) return const extraNodesToMarkDirty = new Set() const extraNodesToClearDirty = new Set() set((state) => { @@ -1200,11 +1226,19 @@ const applyNodeChangesActionImpl = ( set: (fn: (state: SceneState) => Partial) => void, get: () => SceneState, changes: { create?: NodeCreateOp[]; update?: NodeUpdateOp[]; delete?: NodeDeleteOp[] }, + options?: DerivedWriteOptions, ) => { if (get().readOnly) return + changes = convertDerivedPlateHoleWrites(get().nodes, changes, options) + changes = filterDerivedNodeWrites(get().nodes, changes, options) + if (!changes.create?.length && !changes.update?.length && !changes.delete?.length) return const createOps = changes.create ?? [] - const updateOps = changes.update ?? [] + const deletionIntent = + options?.derivedWriter === DERIVED_WRITER_TOKEN + ? [] + : derivedDeletionIntent(get().nodes, changes.delete ?? []) + const updateOps = [...(changes.update ?? []), ...deletionIntent] const deleteOps = changes.delete ?? [] const nodesToMarkDirty = new Set() const nodesToClearDirty = new Set() @@ -1374,8 +1408,17 @@ const updateNodesActionImpl = ( set: (fn: (state: SceneState) => Partial) => void, get: () => SceneState, updates: { id: AnyNodeId; data: Partial }[], + options?: DerivedWriteOptions, + deferDirty = true, ) => { if (get().readOnly) return + const converted = convertDerivedPlateHoleWrites(get().nodes, { update: updates }, options) + if (converted.create?.length || converted.delete?.length) { + applyNodeChangesActionImpl(set, get, converted, options) + return + } + updates = filterDerivedNodeWrites(get().nodes, { update: converted.update ?? [] }, options).update + if (!updates.length) return const parentsToUpdate = new Set() const extraNodesToUpdate = new Set() const extraNodesToDelete = new Set() @@ -1473,6 +1516,12 @@ const updateNodesActionImpl = ( return { nodes: nextNodes } }) + if (!deferDirty) { + for (const id of [...updates.map((u) => u.id), ...parentsToUpdate, ...extraNodesToUpdate]) + get().markDirty(id) + for (const id of extraNodesToDelete) get().clearDirty(id) + return + } // Batch dirty-marking into a single RAF to avoid redundant callbacks during rapid updates for (const u of updates) { // Visibility is applied by React before the deferred dirty callback. Mark @@ -1522,8 +1571,10 @@ export type NodeDeletionPlan = NodeDeletionScene & { /** * The delete store action's planner, without committing: the requested ids, * their `children` subtrees and kind `onDeleteCascade` companions, collinear - * walls merged across a deleted junction, neighbour patches, support and unit - * cleanup, and the default gutter and downspout refresh. + * walls merged across a deleted junction, the separators that keep two rooms + * apart when the wall between them goes, derived-construction deletion intent, + * neighbour patches, support and unit cleanup, and the default gutter and + * downspout refresh. * * The refresh mints gutters, downspouts and outlets with random ids, and which * existing defaults it keeps can depend on them. With `mintDefaults: false` @@ -1535,13 +1586,35 @@ export type NodeDeletionPlan = NodeDeletionScene & { export function planNodeDeletion( scene: NodeDeletionScene, ids: AnyNodeId[], - { mintDefaults = true }: { mintDefaults?: boolean } = {}, + { + mintDefaults = true, + options, + wallDeletionPlan, + }: { + mintDefaults?: boolean + options?: DerivedWriteOptions + /** A caller-owned room-preserving plan; otherwise planned here unless detection is paused. */ + wallDeletionPlan?: StructurePlan + } = {}, ): NodeDeletionPlan { const parentsToMarkDirty = new Set() const nodesToMarkDirty = new Set() const deletedIds = new Set() const mergePlans = buildWallMergePlans(scene.nodes, ids) const requestedDeleteIds = new Set(ids) + // Deleting derived construction is an intent edit ("this room has no + // ceiling"), not a refusal — the reconciler must not rebuild it. + const deletionIntent = + options?.derivedWriter === DERIVED_WRITER_TOKEN ? [] : derivedDeletionIntent(scene.nodes, ids) + // A preview names the separators a room-preserving delete adds without random ids. + let previewCount = 0 + const previewId = (kind: string) => { + let id: string + do id = `${kind}_preview${++previewCount}` + while (id in scene.nodes) + return id + } + const nextNodes = { ...scene.nodes } const nextCollections = { ...scene.collections } let nextRootIds = [...scene.rootNodeIds] @@ -1566,6 +1639,34 @@ export function planNodeDeletion( } } for (const id of ids) collect(id) + if ( + wallDeletionPlan || + (options?.derivedWriter !== DERIVED_WRITER_TOKEN && !isSpaceDetectionPaused()) + ) { + const plan = + wallDeletionPlan ?? + planWallDeletion(scene.nodes, { + nodeIds: [...allIds], + mintId: mintDefaults ? generateId : previewId, + }) + for (const change of plan.changes) { + if (change.op === 'delete') collect(change.id) + else if (change.op === 'update') { + const current = nextNodes[change.id] + if (current) nextNodes[change.id] = parseUpdatedNode(current, change.data) + nodesToMarkDirty.add(change.id) + } else { + const node = change.node + nextNodes[node.id] = node + nodesToMarkDirty.add(node.id) + const parent = node.parentId ? nextNodes[node.parentId as AnyNodeId] : undefined + if (parent && 'children' in parent && Array.isArray(parent.children)) { + nextNodes[parent.id] = { ...parent, children: [...parent.children, node.id] } as AnyNode + parentsToMarkDirty.add(parent.id) + } + } + } + } for (const plan of mergePlans) { allIds.add(plan.secondaryWallId) } @@ -1603,14 +1704,22 @@ export function planNodeDeletion( continue } + const { faceRegions: _regions, ...keptWall } = primaryWall nextNodes[plan.primaryWallId] = { - ...primaryWall, + ...keptWall, + ...(plan.mergedFaceRegions ? { faceRegions: plan.mergedFaceRegions } : {}), start: plan.mergedStart, end: plan.mergedEnd, children: plan.mergedChildren, } nodesToMarkDirty.add(plan.primaryWallId) + for (const update of plan.zoneUpdates) { + if (allIds.has(update.id)) continue + const zone = nextNodes[update.id] + if (zone) nextNodes[update.id] = { ...zone, ...update.data } as AnyNode + } + for (const update of plan.attachmentUpdates) { if (allIds.has(update.id)) continue const child = nextNodes[update.id] @@ -1645,6 +1754,16 @@ export function planNodeDeletion( } } + // A deleted door takes its step paint with it, in the same undo step; every + // other doorway keeps its own. + for (const node of Object.values(nextNodes)) { + if (node.type !== 'zone' || allIds.has(node.id)) continue + const pruned = withoutFloorStepOverrideKeys(node, allIds as ReadonlySet) + if (!pruned) continue + nextNodes[node.id] = pruned + nodesToMarkDirty.add(node.id) + } + const deletedZoneIds = new Set() for (const id of allIds) { if (nextNodes[id]?.type === 'zone') deletedZoneIds.add(id) @@ -1663,8 +1782,12 @@ export function planNodeDeletion( const node = nextNodes[id] if (!node) continue - // 1. Remove reference from parent — only if the parent itself is NOT also being deleted - const parentId = node.parentId as AnyNodeId | null + // Legacy graphs can link children without a reciprocal parentId. + const parentId = (node.parentId ?? + Object.values(nextNodes).find( + (candidate) => + 'children' in candidate && candidate.children?.some((childId) => childId === id), + )?.id) as AnyNodeId | undefined if (parentId && nextNodes[parentId] && !allIds.has(parentId)) { const parent = nextNodes[parentId] as AnyContainerNode if (parent.children) { @@ -1693,6 +1816,13 @@ export function planNodeDeletion( delete nextNodes[id] } + for (const { id, data } of deletionIntent) { + const zone = nextNodes[id] + if (!zone) continue + nextNodes[id] = { ...zone, ...data } as AnyNode + nodesToMarkDirty.add(id) + } + const unsettledIds = new Set() const regeneratedHostIds = new Set() if (mintDefaults) { @@ -1752,6 +1882,8 @@ const deleteNodesActionImpl = ( set: (fn: (state: SceneState) => Partial) => void, get: () => SceneState, ids: AnyNodeId[], + options?: DerivedWriteOptions, + wallDeletionPlan?: StructurePlan, ) => { if (get().readOnly) return let deletedIds = new Set() @@ -1759,7 +1891,7 @@ const deleteNodesActionImpl = ( let nodesToMarkDirty = new Set() set((state) => { - const plan = planNodeDeletion(state, ids) + const plan = planNodeDeletion(state, ids, { options, wallDeletionPlan }) deletedIds = plan.deletedIds parentsToMarkDirty = plan.parentsToMarkDirty nodesToMarkDirty = plan.nodesToMarkDirty @@ -1800,23 +1932,56 @@ function validatedSet(set: Parameters[0]): typeof }) } +/** Runs the same deletion hooks and update constraints for headless scene owners. */ +export function planSceneNodeChanges( + snapshot: Pick, + changes: { update?: NodeUpdateOp[]; delete?: AnyNodeId[]; wallDeletionPlan?: StructurePlan }, +) { + const dirtyIds = new Set() + let state = { + ...snapshot, + readOnly: false, + markDirty: (id: AnyNodeId) => { + dirtyIds.add(id) + }, + clearDirty: (id: AnyNodeId) => { + dirtyIds.delete(id) + }, + } as SceneState + const set = (update: (state: SceneState) => Partial) => { + state = { ...state, ...update(state) } + } + if (changes.update?.length) + updateNodesActionImpl(set, () => state, changes.update, undefined, false) + if (changes.delete?.length) + deleteNodesActionImpl(set, () => state, changes.delete, undefined, changes.wallDeletionPlan) + return { + nodes: state.nodes, + rootNodeIds: state.rootNodeIds, + collections: state.collections, + dirtyIds: [...dirtyIds], + } +} + export const createNodesAction = ( set: Parameters[0], get: Parameters[1], ops: NodeCreateOp[], + options?: DerivedWriteOptions, ) => runWithSceneCommitNodeIds( ops.flatMap(({ node, parentId }) => { const effectiveParentId = parentId ?? (node.parentId as AnyNodeId | null) return effectiveParentId ? [node.id, effectiveParentId] : [node.id] }), - () => createNodesActionImpl(validatedSet(set), get, ops), + () => createNodesActionImpl(validatedSet(set), get, ops, options), ) export const applyNodeChangesAction = ( set: Parameters[0], get: Parameters[1], changes: Parameters[2], + options?: DerivedWriteOptions, ) => runWithSceneCommitNodeIds( [ @@ -1827,24 +1992,80 @@ export const applyNodeChangesAction = ( ...(changes.update ?? []).map(({ id }) => id), ...(changes.delete ?? []), ], - () => applyNodeChangesActionImpl(validatedSet(set), get, changes), + () => applyNodeChangesActionImpl(validatedSet(set), get, changes, options), ) export const updateNodesAction = ( set: Parameters[0], get: Parameters[1], updates: Parameters[2], + options?: DerivedWriteOptions, ) => runWithSceneCommitNodeIds( updates.map(({ id }) => id), - () => updateNodesActionImpl(validatedSet(set), get, updates), + () => updateNodesActionImpl(validatedSet(set), get, updates, options), ) export const deleteNodesAction = ( set: Parameters[0], get: Parameters[1], ids: AnyNodeId[], -) => runWithSceneCommitNodeIds(ids, () => deleteNodesActionImpl(validatedSet(set), get, ids)) + options?: DerivedWriteOptions, +) => + runWithSceneCommitNodeIds(ids, () => deleteNodesActionImpl(validatedSet(set), get, ids, options)) + +/** + * The sanctioned conversion from derived construction to an authored surface: + * the boundary editors' polygon edit, a 2D reshape, a manual move. Clears the + * derived markers (and the zone link) in the same update that carries the + * caller's own change, so the reconciler stops owning the surface from this + * commit on. + */ +export const detachDerivedNodeAction = ( + set: Parameters[0], + get: Parameters[1], + id: AnyNodeId, + data?: Partial, +) => { + const node = get().nodes[id] + if (!node) return + // An automatic ceiling draws its room's paint regions; once it is its own it + // keeps them on itself. + const zone = node.type === 'ceiling' && node.zoneId ? get().nodes[node.zoneId as AnyNodeId] : null + const keptRegions = + node.type === 'ceiling' && + isDerivedNode(node) && + zone?.type === 'zone' && + zone.ceiling?.regions?.length && + !(data && 'regions' in data) + ? { regions: zone.ceiling.regions } + : {} + // Spread through a plain record: merging two `Partial` unions + // explodes into a union TypeScript cannot represent. + const patch = { + ...(data as Record), + ...keptRegions, + ...(isDerivedNode(node) ? (derivedDetachPatch(node) as Record) : {}), + ...(node.type === 'slab' && isDerivedNode(node) + ? { associatedZoneIds: node.zoneIds ?? [] } + : {}), + } as Partial + if (Object.keys(patch).length === 0) return + const ownerUpdates = + node.type === 'slab' && isDerivedNode(node) + ? (node.zoneIds ?? []).flatMap((zoneId) => { + const zone = get().nodes[zoneId as AnyNodeId] + return zone?.type === 'zone' + ? [{ id: zone.id, data: { floor: { ...zone.floor, sourceSlabId: node.id } } }] + : [] + }) + : [] + runWithSceneCommitNodeIds([id, ...ownerUpdates.map(({ id }) => id)], () => + updateNodesActionImpl(validatedSet(set), get, [{ id, data: patch }, ...ownerUpdates], { + derivedWriter: DERIVED_WRITER_TOKEN, + }), + ) +} /** * What the default gutter refresh of `roofIds` would touch, without running diff --git a/packages/core/src/store/derived-node-guard.test.ts b/packages/core/src/store/derived-node-guard.test.ts new file mode 100644 index 0000000000..6d3dc02248 --- /dev/null +++ b/packages/core/src/store/derived-node-guard.test.ts @@ -0,0 +1,506 @@ +import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test' +import { initSpaceDetectionSync, type Space } from '../lib/space-detection' +import { createSceneApi } from '../registry/scene-api' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + CeilingNode, + ItemNode, + LevelNode, + SlabNode, + WallNode, + type ZoneNode, +} from '../schema' +import { DERIVED_WRITER_TOKEN, filterDerivedNodeWrites } from './derived-node-guard' +import { subscribeSceneCommits } from './history-control' +import useScene, { applySceneOperationPatch, clearSceneHistory } from './use-scene' + +const levelId = 'level_derived_guard' +const buildingId = 'building_derived_guard' +const polygon: Array<[number, number]> = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +const hole: Array<[number, number]> = [ + [2, 1], + [3, 1], + [3, 2], + [2, 2], +] +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +let previousState: ReturnType +let stopDetection = () => {} + +beforeEach(() => { + previousState = useScene.getState() + globalThis.requestAnimationFrame = (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame = () => {} +}) + +afterEach(() => { + stopDetection() + useScene.setState(previousState, true) + clearSceneHistory() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf +}) + +function startDetection() { + const editor = { + spaces: {} as Record, + setSpaces(spaces: Record) { + this.spaces = spaces + }, + } + stopDetection = initSpaceDetectionSync(useScene, { getState: () => editor }) + return editor +} + +/** Three walls in the store, the fourth returned so a test can close the loop. */ +function openRoom() { + const walls = polygon.map((start, index) => + WallNode.parse({ + id: `wall_derived_guard_${index}`, + parentId: levelId, + start, + end: polygon[(index + 1) % 4], + thickness: 0.2, + }), + ) + const initial = [ + BuildingNode.parse({ id: buildingId, children: [levelId] }), + LevelNode.parse({ + id: levelId, + parentId: buildingId, + level: 0, + height: 2.5, + children: walls.slice(0, 3).map((wall) => wall.id), + }), + ...walls.slice(0, 3), + ] + useScene.setState({ + nodes: Object.fromEntries(initial.map((node) => [node.id, node])), + rootNodeIds: [buildingId], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + installedPlugins: [], + readOnly: false, + }) + clearSceneHistory() + startDetection() + return walls +} + +function closeRoom() { + const walls = openRoom() + useScene.getState().createNode(walls[3]!, levelId) + return walls +} + +function nodesOfType(type: T) { + return Object.values(useScene.getState().nodes).filter((node) => node.type === type) +} + +function plate() { + return nodesOfType('slab')[0] as SlabNode +} + +function autoCeiling() { + return nodesOfType('ceiling')[0] as CeilingNode +} + +function room() { + return nodesOfType('zone')[0] as ZoneNode +} + +function moveRightWall(x: number) { + useScene.getState().updateNodes([ + { id: 'wall_derived_guard_0', data: { end: [x, 0] } }, + { id: 'wall_derived_guard_1', data: { start: [x, 0], end: [x, 4] } }, + { id: 'wall_derived_guard_2', data: { start: [x, 4] } }, + ]) +} + +test('non-reconciler creates become manual slabs and ceilings at every store boundary', () => { + openRoom() + stopDetection() + const scene = useScene.getState() + const slab = SlabNode.parse({ + id: 'slab_forged', + polygon, + boundary: 'auto', + zoneIds: ['zone_room'], + }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_forged', + polygon, + autoFromWalls: true, + zoneId: 'zone_room', + }) + scene.createNode(slab, levelId) + scene.createNodes([{ node: ceiling, parentId: levelId }]) + scene.applyNodeChanges({ + create: [{ node: { ...slab, id: 'slab_forged_batch' }, parentId: levelId }], + }) + for (const id of [slab.id, ceiling.id, 'slab_forged_batch'] as AnyNodeId[]) { + const node = useScene.getState().nodes[id] as unknown as { + parentId: string + polygon: unknown + autoFromWalls: boolean + boundary?: string + zoneIds?: string[] + zoneId?: string + } + expect(node).toMatchObject({ parentId: levelId, polygon, autoFromWalls: false }) + expect(node.boundary).toBeUndefined() + expect(node.zoneIds).toBeUndefined() + expect(node.zoneId).toBeUndefined() + } + expect(slab.boundary).toBe('auto') +}) + +test('reshaping, relinking and demoting derived construction is a no-op', () => { + closeRoom() + const scene = useScene.getState() + const original = scene.nodes + for (const surface of [plate(), autoCeiling()]) { + scene.updateNode(surface.id, { polygon: [], parentId: buildingId }) + scene.updateNode(surface.id, { boundary: undefined, autoFromWalls: false }) + scene.updateNodes([{ id: surface.id, data: { polygon: [] } }]) + scene.applyNodeChanges({ update: [{ id: surface.id, data: { polygon: [] } }] }) + } + scene.updateNode(plate().id, { zoneIds: [] }) + scene.updateNode(autoCeiling().id, { zoneId: 'zone_elsewhere' }) + expect(useScene.getState().nodes).toBe(original) + scene.updateNode(plate().id, { polygon: [], materialPreset: 'oak' }) + expect(plate()).toMatchObject({ + polygon: (original[plate().id] as SlabNode).polygon, + }) + expect(plate().materialPreset).toBeUndefined() +}) + +function plateWithRoomHole() { + openRoom() + stopDetection() + const node = SlabNode.parse({ + id: 'slab_room_hole', + parentId: levelId, + polygon, + boundary: 'auto', + zoneIds: ['zone_room'], + holes: [hole], + holeMetadata: [{ source: 'room' }], + }) + useScene.setState({ nodes: { ...useScene.getState().nodes, [node.id]: node } }) + clearSceneHistory() + return node +} + +test('relabeling a room hole makes no store notification, commit or node object', () => { + const node = plateWithRoomHole() + const before = useScene.getState() + let notifications = 0 + let commits = 0 + const stopStore = useScene.subscribe(() => notifications++) + const stopCommits = subscribeSceneCommits(() => commits++) + try { + const data = { holes: [hole], holeMetadata: [{ source: 'manual' as const }] } + before.updateNode(node.id, data) + before.updateNodes([{ id: node.id, data }]) + before.applyNodeChanges({ update: [{ id: node.id, data }] }) + expect(useScene.getState()).toBe(before) + expect(notifications).toBe(0) + expect(commits).toBe(0) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + } finally { + stopStore() + stopCommits() + } +}) + +test('manual derived-plate writes create opening intent, preserve room holes, and repeat writes are no-ops', () => { + const node = plateWithRoomHole() + const poolHole = hole.map(([x, z]): [number, number] => [x + 3, z]) + const data = { + holes: [poolHole, hole], + holeMetadata: [{ source: 'manual' as const }, { source: 'manual' as const }], + } + let commits = 0 + const stop = subscribeSceneCommits(() => commits++) + try { + useScene.getState().updateNode(node.id, data) + const updated = useScene.getState().nodes[node.id] as SlabNode + expect(updated.holes).toEqual([hole]) + expect(updated.holeMetadata).toEqual([{ source: 'room' }]) + expect(nodesOfType('floor-opening')).toEqual([ + expect.objectContaining({ polygon: poolHole, parentId: levelId, source: 'manual' }), + ]) + expect(commits).toBe(1) + useScene.getState().updateNode(node.id, data) + expect(useScene.getState().nodes[node.id]).toBe(updated) + expect(nodesOfType('floor-opening')).toHaveLength(1) + expect(commits).toBe(1) + } finally { + stop() + } +}) + +test('hole merging matches kernel precision, winding and start point and appends omitted rooms', () => { + const node = plateWithRoomHole() + const shifted = hole.map(([x, z]): [number, number] => [x + 0.00001, z - 0.00001]).reverse() + shifted.push(shifted.shift()!) + useScene.getState().updateNode(node.id, { + holes: [shifted, hole], + holeMetadata: [{ source: 'manual' }, { source: 'manual' }], + }) + expect(useScene.getState().nodes[node.id]).toBe(node) + useScene.getState().updateNode(node.id, { holeMetadata: [] }) + useScene.getState().updateNode(node.id, { holes: [], holeMetadata: [] }) + expect(useScene.getState().nodes[node.id]).toBe(node) + const authored = hole.map(([x, z]): [number, number] => [x + 0.0002, z]) + useScene.getState().updateNode(node.id, { + holes: [authored], + holeMetadata: [{ source: 'stair', stairId: 'stair_opening' }], + }) + expect(useScene.getState().nodes[node.id]).toMatchObject({ + holes: [authored, hole], + holeMetadata: [{ source: 'stair', stairId: 'stair_opening' }, { source: 'room' }], + }) +}) + +test('the public SceneApi filters derived writes and preserves allowed edits', () => { + closeRoom() + const api = createSceneApi(useScene) + const original = plate() + api.update(original.id, { polygon: [] }) + api.upsert({ ...original, polygon: [] }, buildingId) + api.applyChanges!({ update: [{ id: autoCeiling().id, data: { boundary: undefined } }] }) + expect(plate()).toBe(original) + api.update(autoCeiling().id, { height: 2.2 }) + expect(autoCeiling().height).toBe(2.2) +}) + +test('the derived writer capability returns the original changes untouched', () => { + const node = plateWithRoomHole() + const changes = { + create: [{ node }], + update: [{ id: node.id, data: { polygon: [], holes: [] } }], + } + expect( + filterDerivedNodeWrites({ [node.id]: node }, changes, { derivedWriter: DERIVED_WRITER_TOKEN }), + ).toBe(changes) +}) + +test('warnings are once per node and field in dev and silent in tests and production', () => { + const node = SlabNode.parse({ id: 'slab_warning', polygon, boundary: 'auto' }) + const warn = spyOn(console, 'warn').mockImplementation(() => {}) + const env = process.env.NODE_ENV + const apply = (data: Partial) => + filterDerivedNodeWrites({ [node.id]: node }, { update: [{ id: node.id, data }] }) + try { + for (const mode of ['test', 'production']) { + process.env.NODE_ENV = mode + apply({ polygon: [] }) + } + expect(warn).not.toHaveBeenCalled() + process.env.NODE_ENV = 'development' + apply({ polygon: [] }) + apply({ polygon: [] }) + apply({ polygon: [], boundary: undefined }) + expect(warn).toHaveBeenCalledTimes(2) + expect(warn.mock.calls[0]![0]).toContain('polygon on slab_warning') + expect(warn.mock.calls[1]![0]).toContain('boundary on slab_warning') + } finally { + process.env.NODE_ENV = env + warn.mockRestore() + } +}) + +// ── Allowed ────────────────────────────────────────────────────────────────── + +test('finish, ceiling height and hosted children stay editable on derived construction', () => { + closeRoom() + const scene = useScene.getState() + scene.updateNode(autoCeiling().id, { height: 2.3, materialPreset: 'plaster' }) + scene.updateNode(plate().id, { slots: { edge: 'library:oak' } }) + expect(autoCeiling()).toMatchObject({ height: 2.3, materialPreset: 'plaster' }) + expect(plate()).toMatchObject({ slots: { edge: 'library:oak' } }) + + const light = ItemNode.parse({ + id: 'item_pendant', + parentId: autoCeiling().id, + position: [4, 0, 2], + asset: { + id: 'room_light', + name: 'Room light', + category: 'lighting', + thumbnail: '', + src: '/room-light.glb', + attachTo: 'ceiling', + }, + }) + scene.createNode(light, autoCeiling().id) + expect(autoCeiling().children).toContain(light.id) + + // Plate construction is authored intent the plate builder promotes into the + // room's floor elevation, so it is not a derived write. + useScene.getState().updateNode(plate().id, { thickness: 0.2 }) + expect(plate().thickness).toBe(0.2) +}) + +test('detachDerivedNode converts a plate and a ceiling into authored surfaces', () => { + closeRoom() + const edited: Array<[number, number]> = [ + [0, 0], + [8.1, 0], + [8.1, 4], + [0, 4], + ] + const plateId = plate().id + const ceilingId = autoCeiling().id + useScene.getState().detachDerivedNode(plateId, { polygon: edited }) + useScene.getState().detachDerivedNode(ceilingId, { polygon: edited }) + for (const id of [plateId, ceilingId]) { + const node = useScene.getState().nodes[id] as SlabNode | CeilingNode + expect(node.polygon).toEqual(edited) + expect(node.autoFromWalls).toBe(false) + expect(node.boundary).toBeUndefined() + } + expect((useScene.getState().nodes[plateId] as SlabNode).zoneIds).toBeUndefined() + expect((useScene.getState().nodes[ceilingId] as CeilingNode).zoneId).toBeUndefined() + + // Detached surfaces survive the next reconciliation untouched. + moveRightWall(8.6) + expect((useScene.getState().nodes[plateId] as SlabNode).polygon).toEqual(edited) + expect((useScene.getState().nodes[ceilingId] as CeilingNode).polygon).toEqual(edited) +}) + +test('deleting a derived ceiling records hasCeiling and is not rebuilt', () => { + closeRoom() + const zoneId = room().id + const ceilingId = autoCeiling().id + useScene.getState().deleteNode(ceilingId) + expect(useScene.getState().nodes[ceilingId]).toBeUndefined() + expect(useScene.getState().nodes[zoneId]).toMatchObject({ hasCeiling: false }) + moveRightWall(8.3) + expect(nodesOfType('ceiling')).toHaveLength(0) +}) + +test('deleting a derived plate records hasFloor and is not rebuilt', () => { + closeRoom() + const zoneId = room().id + const plateId = plate().id + useScene.getState().deleteNodes([plateId]) + expect(useScene.getState().nodes[plateId]).toBeUndefined() + expect(useScene.getState().nodes[zoneId]).toMatchObject({ hasFloor: false }) + moveRightWall(8.3) + expect(nodesOfType('slab')).toEqual([]) +}) + +test('a cascading level deletion carries no room intent', () => { + closeRoom() + expect(() => useScene.getState().deleteNode(levelId)).not.toThrow() + expect(nodesOfType('slab')).toHaveLength(0) + expect(nodesOfType('ceiling')).toHaveLength(0) + expect(nodesOfType('zone')).toHaveLength(0) +}) + +// ── Capability holders ─────────────────────────────────────────────────────── + +test('the reconciler still writes derived construction', () => { + closeRoom() + expect(plate()).toMatchObject({ boundary: 'auto', autoFromWalls: true }) + expect(autoCeiling()).toMatchObject({ boundary: 'auto', autoFromWalls: true }) + moveRightWall(9) + expect(Math.max(...plate().polygon.map(([x]) => x))).toBeGreaterThan(8.5) +}) + +test('load migrations still mint derived construction from a legacy scene', () => { + const walls = polygon.map((start, index) => + WallNode.parse({ + id: `wall_legacy_${index}`, + parentId: levelId, + start, + end: polygon[(index + 1) % 4], + height: 2.5, + }), + ) + const legacySlab = SlabNode.parse({ + id: 'slab_legacy', + parentId: levelId, + polygon, + autoFromWalls: true, + }) + const legacyCeiling = CeilingNode.parse({ + id: 'ceiling_legacy', + parentId: levelId, + polygon, + autoFromWalls: true, + }) + const children = [...walls, legacySlab, legacyCeiling] + const level = LevelNode.parse({ + id: levelId, + parentId: buildingId, + children: children.map((node) => node.id), + }) + const building = BuildingNode.parse({ id: buildingId, children: [levelId] }) + useScene + .getState() + .setScene( + Object.fromEntries([building, level, ...children].map((node) => [node.id, node])) as Record< + AnyNodeId, + AnyNode + >, + [buildingId], + ) + clearSceneHistory() + startDetection() + expect(nodesOfType('zone')).toHaveLength(1) + expect(plate()).toMatchObject({ boundary: 'auto', autoFromWalls: true }) + expect(autoCeiling()).toMatchObject({ boundary: 'auto', zoneId: room().id }) +}) + +test('undo and redo restore derived construction', () => { + const walls = openRoom() + const before = useScene.getState().nodes + useScene.getState().createNode(walls[3]!, levelId) + const closed = useScene.getState().nodes + expect(nodesOfType('slab')).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(closed) +}) + +test('host patches apply derived construction minted by the originator', () => { + const walls = openRoom() + stopDetection() + const derivedCeiling = CeilingNode.parse({ + id: 'ceiling_from_host', + parentId: levelId, + polygon, + boundary: 'auto', + autoFromWalls: true, + zoneId: 'zone_from_host', + }) + expect( + applySceneOperationPatch({ + materialChanges: [], + nodeCreates: [ + { node: walls[3]!, position: 3 }, + { node: derivedCeiling, position: 4 }, + ], + nodeUpdates: [], + nodeDeletes: [], + }), + ).toBe(true) + expect(useScene.getState().nodes[derivedCeiling.id]).toMatchObject({ boundary: 'auto' }) +}) diff --git a/packages/core/src/store/derived-node-guard.ts b/packages/core/src/store/derived-node-guard.ts new file mode 100644 index 0000000000..ace57c0661 --- /dev/null +++ b/packages/core/src/store/derived-node-guard.ts @@ -0,0 +1,651 @@ +import { floorPlateHoldsUnderside } from '../lib/floor-foundation-datum' +import { expandFloorIntentChanges, floorIntentConflicts } from '../lib/floor-intent-changes' +import { ownFloorIntentChanges } from '../lib/own-floor-intent' +import { type Ring, union } from '../lib/polygon-boolean' +import type { AnyNode, AnyNodeId, CeilingNode, SlabNode, ZoneNode } from '../schema' +import { FloorOpeningNode, generateId } from '../schema' +import type { SurfaceHoleMetadata } from '../schema/nodes/surface-hole-metadata' + +/** + * Derived construction — floor plates and auto ceilings — is written by the + * structure reconciler, load migrations, history restore and host-patch + * application. Every other writer states *intent* (walls, separators, zones) + * and lets the reconciler derive the construction. + * + * The capability is this module-private token. It is deliberately NOT + * re-exported from the package index, so no caller outside `@pascal-app/core` + * can mint a write that bypasses the guard — the sanctioned entry points + * (`applyStructureReconciliation`, `detachDerivedNode`) hold it instead. + */ +export const DERIVED_WRITER_TOKEN: unique symbol = Symbol('pascal.derived-writer') + +export type DerivedWriteOptions = { + /** Internal capability. Only core's reconciler paths can supply it. */ + derivedWriter?: typeof DERIVED_WRITER_TOKEN +} + +export type DerivedSurfaceNode = SlabNode | CeilingNode + +export type DerivedWriteOperation = 'create' | 'update' | 'delete' + +/** Thrown when a caller without the derived-writer capability writes derived construction. */ +export class DerivedNodeWriteError extends Error { + readonly code = 'derived_node_write_refused' + + constructor( + readonly operation: DerivedWriteOperation, + readonly nodeId: string, + readonly fields: readonly string[], + message: string, + ) { + super(message) + this.name = 'DerivedNodeWriteError' + } +} + +/** + * A slab or ceiling the reconciler owns. `boundary: 'auto'` is the current + * marker; `autoFromWalls: true` is the legacy one still present in scenes that + * have not been through the load migrations. + */ +export function isDerivedNode(node: AnyNode | null | undefined): node is DerivedSurfaceNode { + if (!node) return false + if (node.type !== 'slab' && node.type !== 'ceiling') return false + return node.boundary === 'auto' || node.autoFromWalls === true +} + +/** Fields whose value the reconciler owns on a derived surface. */ +const PROTECTED_FIELDS: Record<'slab' | 'ceiling', readonly string[]> = { + slab: [ + 'elevation', + 'plateRole', + 'support', + 'railing', + 'polygon', + 'zoneIds', + 'boundary', + 'autoFromWalls', + 'parentId', + ], + ceiling: ['polygon', 'zoneId', 'boundary', 'autoFromWalls', 'parentId'], +} + +function equal(a: unknown, b: unknown) { + return JSON.stringify(a) === JSON.stringify(b) +} + +/** + * The holes the reconciler cut for the room face, in order. Authored holes + * (manual cut-outs, stair and elevator openings) stay editable on a derived + * surface — the kernel re-applies them on every pass — so only the `room` + * entries are protected. + */ +function roomHoles(node: { holes?: unknown; holeMetadata?: unknown }) { + const holes = (node.holes ?? []) as unknown[] + const metadata = (node.holeMetadata ?? []) as (SurfaceHoleMetadata | undefined)[] + return holes.filter((_, index) => metadata[index]?.source === 'room') +} + +/** Names the protected fields a patch would actually change on `current`. */ +export function derivedFieldViolations( + current: DerivedSurfaceNode, + data: Partial, + nodes?: Readonly>, +): string[] { + const patch = data as Record + const node = current as unknown as Record + const fixedUndersideEdit = + nodes && + current.type === 'slab' && + current.plateRole === 'base' && + floorPlateHoldsUnderside(nodes, current) && + typeof patch.elevation === 'number' && + typeof patch.thickness === 'number' && + Math.abs( + patch.elevation - + patch.thickness - + ((current.floorHeight ?? current.elevation) - current.thickness), + ) <= 1e-6 + const violations = PROTECTED_FIELDS[current.type].filter( + (field) => + Object.hasOwn(patch, field) && + !equal(patch[field], node[field]) && + !(field === 'elevation' && fixedUndersideEdit), + ) + if (current.type === 'slab') + for (const field of current.plateRole === 'base' + ? ['fillToTerrain'] + : ['floorHeight', 'foundation']) + if (Object.hasOwn(patch, field) && !equal(patch[field], node[field])) violations.push(field) + if (current.type === 'slab' && current.support === 'open') + for (const field of ['elevation', 'thickness', 'recessed', 'fillToTerrain']) + if (Object.hasOwn(patch, field) && !equal(patch[field], node[field])) violations.push(field) + if ( + current.type === 'slab' && + (current.plateRole === 'platform' || current.plateRole === 'sunken') + ) + for (const field of ['thickness', 'recessed', 'fillToTerrain', 'slots']) + if (Object.hasOwn(patch, field) && !equal(patch[field], node[field])) violations.push(field) + if (current.type === 'slab' && (current.plateRole || current.support === 'open')) { + for (const field of ['material', 'materialPreset', 'recessed']) + if (Object.hasOwn(patch, field) && !equal(patch[field], node[field])) violations.push(field) + if ( + (current.plateRole === 'base' || current.support === 'open') && + Object.hasOwn(patch, 'slots') + ) { + const slots = patch.slots as Record | undefined + if ( + [...new Set([...Object.keys(current.slots ?? {}), ...Object.keys(slots ?? {})])].some( + (key) => + !(current.support === 'open' ? ['underside'] : ['edge', 'riser', 'underside']).includes( + key, + ) && !equal(slots?.[key], current.slots?.[key]), + ) + ) + violations.push('slots') + } + } + if ( + (Object.hasOwn(patch, 'holes') || Object.hasOwn(patch, 'holeMetadata')) && + !equal(roomHoles({ ...node, ...patch }), roomHoles(node)) + ) { + violations.push('holes') + } + if ( + current.type === 'slab' && + (Object.hasOwn(patch, 'holes') || Object.hasOwn(patch, 'holeMetadata')) + ) { + const proposed = { ...current, ...data } as SlabNode + const manual = (surface: SlabNode) => + surface.holes.filter( + (_, index) => (surface.holeMetadata[index]?.source ?? 'manual') === 'manual', + ) + if (!equal(manual(current), manual(proposed)) && !violations.includes('holes')) + violations.push('holes') + } + return violations +} + +export type DerivedNodeChanges = { + create?: readonly { node: AnyNode }[] + update?: readonly { id: AnyNodeId; data: Partial }[] +} + +type MutableDerivedChanges = { + create?: Array<{ node: AnyNode; parentId?: AnyNodeId }> + update?: Array<{ id: AnyNodeId; data: Partial }> + delete?: AnyNodeId[] +} + +function managedPoolOpenings(metadata: unknown): Array<{ poolId: string; polygon: Ring }> { + const value = (metadata as Record | undefined)?.poolManagedOpenings + if (!Array.isArray(value)) return [] + return value.flatMap((entry) => { + const candidate = entry as { poolId?: unknown; polygon?: unknown } + if (typeof candidate?.poolId !== 'string' || !Array.isArray(candidate.polygon)) return [] + const polygon = candidate.polygon as unknown[] + if ( + !polygon.every( + (point) => + Array.isArray(point) && point.length >= 2 && point.slice(0, 2).every(Number.isFinite), + ) + ) + return [] + return [ + { + poolId: candidate.poolId, + polygon: polygon.map((point) => (point as number[]).slice(0, 2) as [number, number]), + }, + ] + }) +} + +export function convertDerivedPlateHoleWrites( + nodes: Readonly>, + changes: T, + options?: DerivedWriteOptions, +): T & MutableDerivedChanges { + if (options?.derivedWriter === DERIVED_WRITER_TOKEN || !changes.update?.length) return changes + const create = [...(changes.create ?? [])] + const update = [...changes.update] + const deleted = new Set(changes.delete ?? []) + const poolDesired = new Map() + const poolTouched = new Set() + const poolKey = (levelId: string, ownerId: string) => JSON.stringify([levelId, ownerId]) + for (const op of changes.update) { + const slab = nodes[op.id] + if (slab?.type !== 'slab' || !slab.parentId) continue + const patch = op.data as Partial + for (const entry of managedPoolOpenings(slab.metadata)) + poolTouched.add(poolKey(slab.parentId, entry.poolId)) + if (!Object.hasOwn(patch, 'metadata')) continue + for (const entry of managedPoolOpenings(patch.metadata)) { + const key = poolKey(slab.parentId, entry.poolId) + poolTouched.add(key) + poolDesired.set(key, { + levelId: slab.parentId, + ownerId: entry.poolId, + polygon: entry.polygon, + }) + } + } + let converted = false + for (const key of poolTouched) { + const desired = poolDesired.get(key) + const [levelId, ownerId] = JSON.parse(key) as [string, string] + const existing = Object.values(nodes) + .filter( + (node): node is FloorOpeningNode => + node.type === 'floor-opening' && + node.parentId === levelId && + node.source === 'plugin:pool' && + node.ownerId === ownerId, + ) + .sort((a, b) => a.id.localeCompare(b.id)) + for (const extra of existing.slice(desired ? 1 : 0)) deleted.add(extra.id) + if (desired) { + const old = existing[0] + if (old) { + if ( + holeKey(old.polygon) !== holeKey(desired.polygon) || + old.cutsAdjacent || + old.legacyPlateCuts + ) + update.push({ + id: old.id, + data: { polygon: desired.polygon, cutsAdjacent: false, legacyPlateCuts: undefined }, + }) + } else { + const node = FloorOpeningNode.parse({ + id: generateId('floor-opening'), + parentId: levelId, + name: 'Pool opening', + polygon: desired.polygon, + source: 'plugin:pool', + ownerId, + cutsAdjacent: false, + }) + create.push({ node, parentId: levelId as AnyNodeId }) + } + } + converted = true + } + for (const [opIndex, op] of changes.update.entries()) { + const slab = nodes[op.id] + if (!isDerivedNode(slab) || slab.type !== 'slab' || !slab.parentId) continue + const patch = op.data as Partial + if (!Object.hasOwn(patch, 'holes') && !Object.hasOwn(patch, 'holeMetadata')) continue + const holes = patch.holes ?? slab.holes + const pluginWrite = Object.hasOwn(patch, 'metadata') + const sameGeometry = + holes.length === slab.holes.length && + (equal(holes, slab.holes) || equal(holes.map(holeKey).sort(), slab.holes.map(holeKey).sort())) + const unmaterializedAuthoredOpening = + sameGeometry && + !pluginWrite && + Object.values(nodes).some( + (node) => + node.type === 'floor-opening' && + node.source === 'manual' && + (node.metadata as Record | undefined)?.plateHoleAuthoring === slab.id && + !slab.holeMetadata.some( + (entry) => entry.source === 'floor-opening' && entry.openingId === node.id, + ), + ) + if (sameGeometry && !unmaterializedAuthoredOpening) { + const data = { ...patch } + delete data.holes + delete data.holeMetadata + update[opIndex] = { ...op, data: data as Partial } + converted = true + continue + } + const ownedMetadataByHole = new Map( + slab.holes.flatMap((hole, index) => { + const entry = slab.holeMetadata[index] + return entry && entry.source !== 'manual' ? [[holeKey(hole), entry] as const] : [] + }), + ) + const proposedMetadata = patch.holeMetadata ?? slab.holeMetadata + const metadata = holes.map((hole, index) => { + const entry = proposedMetadata[index] + return (entry?.source ?? 'manual') === 'manual' + ? (ownedMetadataByHole.get(holeKey(hole)) ?? entry) + : entry + }) + if (!equal(metadata, patch.holeMetadata)) { + update[opIndex] = { + ...op, + data: { ...patch, holeMetadata: metadata } as Partial, + } + converted = true + } + const managed = managedPoolOpenings(patch.metadata ?? slab.metadata) + const managedKeys = new Set(managed.map((entry) => holeKey(entry.polygon))) + const roomKeys = new Set( + slab.holes.flatMap((hole, index) => + slab.holeMetadata[index]?.source === 'room' ? [holeKey(hole)] : [], + ), + ) + const poolWrite = + Object.hasOwn(patch, 'metadata') && + (managed.length > 0 || managedPoolOpenings(slab.metadata).length > 0) + const currentOpenings = new Map() + for (const entry of slab.holeMetadata) { + if (entry.source !== 'floor-opening' || !entry.openingId) continue + const opening = nodes[entry.openingId] + if (opening?.type === 'floor-opening' && opening.source === 'manual') + currentOpenings.set(opening.id, opening) + } + for (const node of Object.values(nodes)) { + if (node.type !== 'floor-opening' || node.source !== 'manual') continue + if ((node.metadata as Record | undefined)?.plateHoleAuthoring === slab.id) + currentOpenings.set(node.id, node) + } + const retainedIds = new Set( + metadata.flatMap((entry) => + entry?.source === 'floor-opening' && entry.openingId ? [entry.openingId] : [], + ), + ) + const pending = [...currentOpenings.values()].filter((opening) => !retainedIds.has(opening.id)) + const authored = holes.flatMap((polygon, index) => + (metadata[index]?.source ?? 'manual') === 'manual' && + !managedKeys.has(holeKey(polygon)) && + !roomKeys.has(holeKey(polygon)) + ? [{ polygon, openingId: metadata[index]?.openingId }] + : [], + ) + let manualConverted = false + for (const { polygon, openingId } of authored) { + const exact = [...currentOpenings.values()].find( + (opening) => opening.id === openingId || holeKey(opening.polygon) === holeKey(polygon), + ) + const old = exact ?? pending.shift() + if (old) { + const index = pending.findIndex((candidate) => candidate.id === old.id) + if (index >= 0) pending.splice(index, 1) + if (holeKey(old.polygon) !== holeKey(polygon)) + update.push({ id: old.id, data: { polygon, cutsAdjacent: false } }) + } else if ( + !create.some( + (entry) => + entry.node.type === 'floor-opening' && + entry.node.parentId === slab.parentId && + holeKey(entry.node.polygon) === holeKey(polygon), + ) + ) { + const hostZoneId = + slab.support === 'open' && slab.zoneIds?.length === 1 ? slab.zoneIds[0] : undefined + const node = FloorOpeningNode.parse({ + id: generateId('floor-opening'), + parentId: slab.parentId, + name: 'Floor opening', + polygon, + ...(hostZoneId ? { hostZoneId } : {}), + metadata: { plateHoleAuthoring: slab.id }, + cutsAdjacent: false, + }) + create.push({ node, parentId: slab.parentId as AnyNodeId }) + } + manualConverted = true + } + const managedHoles = (surfaceHoles: typeof holes, surfaceMetadata: typeof metadata) => + surfaceHoles.flatMap((hole, index) => + surfaceMetadata[index]?.source === 'stair' || surfaceMetadata[index]?.source === 'elevator' + ? [{ hole, metadata: surfaceMetadata[index] }] + : [], + ) + const systemWrite = !equal( + managedHoles(slab.holes, slab.holeMetadata), + managedHoles(holes, metadata), + ) + if (!pluginWrite && !poolWrite && !systemWrite) + for (const opening of pending) { + deleted.add(opening.id) + manualConverted = true + } + const hasManual = holes.some( + (polygon, index) => + (metadata[index]?.source ?? 'manual') === 'manual' && + !managedKeys.has(holeKey(polygon)) && + !roomKeys.has(holeKey(polygon)), + ) + const hasManaged = holes.some( + (polygon, index) => + (metadata[index]?.source ?? 'manual') === 'manual' && managedKeys.has(holeKey(polygon)), + ) + const preservedOpenings = + pluginWrite || poolWrite || systemWrite + ? slab.holes.flatMap((hole, index) => { + const entry = slab.holeMetadata[index] + return entry && + entry.source !== 'manual' && + !holes.some((candidate) => holeKey(candidate) === holeKey(hole)) + ? [{ hole, metadata: entry }] + : [] + }) + : [] + if (!manualConverted && !hasManual && !hasManaged && !preservedOpenings.length) continue + const retained = holes.flatMap((hole, index) => + (metadata[index]?.source ?? 'manual') === 'manual' + ? [] + : [{ hole, metadata: metadata[index] ?? { source: 'manual' as const } }], + ) + retained.push(...preservedOpenings) + update[opIndex] = { + ...op, + data: { + ...patch, + holes: retained.map((entry) => entry.hole), + holeMetadata: retained.map((entry) => entry.metadata), + } as Partial, + } + converted = true + } + return converted + ? ({ ...changes, create, update, delete: [...deleted] } as T & MutableDerivedChanges) + : changes +} + +const warnedFields = new Set() + +function warnFilteredFields(nodeId: string, fields: string[]) { + if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') return + const fresh = fields.filter((field) => !warnedFields.has(`${nodeId}:${field}`)) + if (!fresh.length) return + for (const field of fresh) warnedFields.add(`${nodeId}:${field}`) + try { + console.warn(`[Scene] Preserved derived ownership of ${fresh.join(', ')} on ${nodeId}`) + } catch { + // Diagnostics must not turn a filtered plugin write into a scene failure. + } +} + +function holeKey(hole: Ring): string { + return JSON.stringify(union([hole])) +} + +function mergeRoomHoles(current: DerivedSurfaceNode, patch: Partial) { + const rooms = current.holes.flatMap((hole, index) => { + const metadata = current.holeMetadata[index] + return metadata?.source === 'room' ? [{ hole, metadata, key: holeKey(hole) }] : [] + }) + if (!rooms.length) return patch + const holes: Ring[] = [] + const holeMetadata: SurfaceHoleMetadata[] = [] + const emitted = new Set() + const proposedHoles = Object.hasOwn(patch, 'holes') ? (patch.holes ?? []) : current.holes + const proposedMetadata = Object.hasOwn(patch, 'holeMetadata') + ? (patch.holeMetadata ?? []) + : current.holeMetadata + for (const [index, hole] of proposedHoles.entries()) { + const key = holeKey(hole) + const room = rooms.find((entry) => entry.key === key) + if (room) { + if (emitted.has(room.key)) continue + emitted.add(room.key) + holes.push(room.hole) + holeMetadata.push(room.metadata) + } else { + holes.push(hole) + holeMetadata.push(proposedMetadata[index] ?? { source: 'manual' }) + } + } + for (const room of rooms) { + if (emitted.has(room.key)) continue + emitted.add(room.key) + holes.push(room.hole) + holeMetadata.push(room.metadata) + } + return { ...patch, holes, holeMetadata } +} + +/** In-app writers retain authored edits without taking ownership from the reconciler. */ +export function filterDerivedNodeWrites( + nodes: Readonly>, + changes: T, + options?: DerivedWriteOptions, +): T { + if (options?.derivedWriter === DERIVED_WRITER_TOKEN) return changes + if (changes.update) { + const own = ownFloorIntentChanges(nodes, changes.update) + const update = own.conflicts.length ? [] : expandFloorIntentChanges(nodes, own.updates) + changes = { ...changes, update } + } + return { + ...changes, + ...(changes.create && { + create: changes.create.map((op) => { + if (!isDerivedNode(op.node)) return op + const node = { ...op.node } as Record + const fields = ['plateRole', 'boundary', 'zoneIds', 'zoneId', 'autoFromWalls'] + warnFilteredFields( + op.node.id, + fields.filter((field) => Object.hasOwn(node, field)), + ) + for (const field of fields) delete node[field] + return { ...op, node: node as AnyNode } + }), + }), + ...(changes.update && { + update: changes.update.flatMap((op) => { + const current = nodes[op.id] + if (!isDerivedNode(current)) return [op] + const fields = derivedFieldViolations(current, op.data, nodes).filter( + (field) => field !== 'holes', + ) + let data = { ...op.data } as Record + for (const field of fields) delete data[field] + if (Object.hasOwn(data, 'holes') || Object.hasOwn(data, 'holeMetadata')) { + const merged = mergeRoomHoles(current, data) + for (const field of ['holes', 'holeMetadata'] as const) { + const proposed = Object.hasOwn(data, field) ? data[field] : current[field] + if (Object.hasOwn(merged, field) && !equal(merged[field], proposed)) fields.push(field) + } + data = merged + } + warnFilteredFields(op.id, fields) + const node = current as unknown as Record + if (Object.entries(data).every(([field, value]) => equal(value, node[field]))) return [] + return [{ ...op, data: data as Partial }] + }), + }), + } +} + +/** + * State-aware refusal guard for MCP bridges. In-app mutation boundaries use + * filterDerivedNodeWrites so a plugin cannot crash the scene with a derived write. + * + * Base construction remains editable; room plate finishes and elevations are intent + * on the owning zone or level. + */ +export function assertDerivedNodeWrites( + nodes: Readonly>, + changes: DerivedNodeChanges, + options?: DerivedWriteOptions, +): void { + if (options?.derivedWriter === DERIVED_WRITER_TOKEN) return + const own = ownFloorIntentChanges(nodes, changes.update ?? []) + const conflicts = [ + ...own.conflicts, + ...floorIntentConflicts( + nodes, + expandFloorIntentChanges(nodes, own.updates), + changes.create?.map(({ node }) => node), + ), + ] + if (conflicts.length) + throw Object.assign(new Error(conflicts.map((c) => c.message).join(' ')), { + code: 'room_floor_conflict', + conflicts, + }) + for (const { node } of changes.create ?? []) { + if (!isDerivedNode(node)) continue + throw new DerivedNodeWriteError( + 'create', + node.id, + node.type === 'slab' ? ['boundary', 'zoneIds'] : ['boundary', 'zoneId'], + `Refusing to create the derived ${node.type} ${node.id}. Floor plates and auto ceilings are derived from rooms: create walls and a zone (spaceRole: "room") and the structure reconciler builds them.`, + ) + } + for (const { id, data } of changes.update ?? []) { + const current = nodes[id] + if (!isDerivedNode(current)) continue + const fields = derivedFieldViolations(current, data, nodes) + if (fields.length === 0) continue + throw new DerivedNodeWriteError( + 'update', + id, + fields, + current.type === 'slab' && current.plateRole === 'base' + ? `Refusing to change ${fields.join(', ')} on the derived slab ${id} (base plate). Use set_floor_foundation to change its floor height.` + : `Refusing to change ${fields.join(', ')} on the derived ${current.type} ${id}. The structure reconciler owns it: edit the room zone's intent instead, or convert the surface to manual with detachDerivedNode.`, + ) + } +} + +/** The patch that converts a derived surface into an ordinary authored one. */ +export function derivedDetachPatch(node: DerivedSurfaceNode): Partial { + return ( + node.type === 'slab' + ? { autoFromWalls: false, boundary: undefined, zoneIds: undefined, plateRole: undefined } + : { autoFromWalls: false, boundary: undefined, zoneId: undefined } + ) as Partial +} + +/** The zone ids whose construction intent a derived surface stands for. */ +function linkedZoneIds(node: DerivedSurfaceNode): string[] { + const ids = node.type === 'slab' ? (node.zoneIds ?? []) : node.zoneId ? [node.zoneId] : [] + return [...new Set(ids)] +} + +/** + * Explicit deletion of derived construction is an intent edit, not a refusal: + * removing a room's auto ceiling means "this room has no ceiling" + * (`hasCeiling: false`), removing its plate means "no floor" (`hasFloor: + * false`). Returns the zone updates that record it, so the reconciler does not + * simply rebuild what the user deleted. + * + * Cascaded descendants (deleting the level that owns the plate) carry no + * intent — the zone is going away with them. + */ +export function derivedDeletionIntent( + nodes: Readonly>, + ids: readonly AnyNodeId[], +): { id: AnyNodeId; data: Partial }[] { + const deleted = new Set(ids) + const intent = new Map>() + for (const id of ids) { + const node = nodes[id] + if (!isDerivedNode(node)) continue + const field = node.type === 'ceiling' ? 'hasCeiling' : 'hasFloor' + for (const zoneId of linkedZoneIds(node)) { + const zone = nodes[zoneId] + if (zone?.type !== 'zone' || deleted.has(zone.id)) continue + if (zone[field] === false) continue + intent.set(zone.id, { ...intent.get(zone.id), [field]: false }) + } + } + return [...intent].map(([id, data]) => ({ id, data: data as Partial })) +} diff --git a/packages/core/src/store/derived-writer-allowlist.test.ts b/packages/core/src/store/derived-writer-allowlist.test.ts new file mode 100644 index 0000000000..4c8141a9ae --- /dev/null +++ b/packages/core/src/store/derived-writer-allowlist.test.ts @@ -0,0 +1,64 @@ +import { expect, test } from 'bun:test' + +// Review guardrail for the writers contract (plans/editor-room-first-structure.md): +// derived construction — a slab or ceiling marked `boundary: 'auto'` or the +// legacy `autoFromWalls: true` — is written by the structure kernel and the +// load migrations, and by nobody else. A new writer anywhere under a package's +// `src` fails here instead of quietly becoming a second construction generator. +// +// The scan looks for the object-literal form; reads (`=== 'auto'`, +// `node.autoFromWalls`) are not writes and never match. Comments are stripped +// first, but a string literal that spells a marker out verbatim still trips the +// guard — prose about the contract belongs in a comment or the wiki. +const ALLOWLIST = new Set([ + // The kernel and its plate builder ARE the generator. + 'packages/core/src/lib/structure-kernel.ts', + 'packages/core/src/lib/floor-plates.ts', + // Load migrations mint the same construction for scenes saved before it. + 'packages/core/src/utils/room-zone-migration.ts', + 'packages/core/src/utils/floor-plate-migration.ts', +]) + +const MARKERS = [/\bboundary:\s*'auto'/, /\bautoFromWalls:\s*true/] + +/** Comments describe the markers; only code that writes them counts. */ +function withoutComments(source: string) { + return source.replaceAll(/\/\*[\s\S]*?\*\//g, '').replaceAll(/\/\/[^\n]*/g, '') +} + +function isFixtureOrTest(path: string) { + return ( + path.includes('.test.') || + path.includes('.bench.') || + path.includes('.fixtures.') || + path.includes('__fixtures__/') || + path.includes('__bench__/') || + path.includes('__tests__/') + ) +} + +const PACKAGE_SOURCES = 'packages/*/src/**/*.{ts,tsx}' + +function repoRoot() { + return new URL('../../../../', import.meta.url).pathname +} + +test('only the structure kernel and the load migrations author derived construction', async () => { + const root = repoRoot() + const offenders: string[] = [] + for await (const relative of new Bun.Glob(PACKAGE_SOURCES).scan({ cwd: root, onlyFiles: true })) { + const path = relative.replaceAll('\\', '/') + if (isFixtureOrTest(path) || ALLOWLIST.has(path)) continue + const source = withoutComments(await Bun.file(root + relative).text()) + if (MARKERS.some((marker) => marker.test(source))) offenders.push(path) + } + expect(offenders).toEqual([]) +}) + +test('every allowlisted file still authors derived construction', async () => { + const root = repoRoot() + for (const path of ALLOWLIST) { + const source = withoutComments(await Bun.file(root + path).text()) + expect([path, MARKERS.some((marker) => marker.test(source))]).toEqual([path, true]) + } +}) diff --git a/packages/core/src/store/floor-opening-live.test.ts b/packages/core/src/store/floor-opening-live.test.ts new file mode 100644 index 0000000000..595a3e5fbc --- /dev/null +++ b/packages/core/src/store/floor-opening-live.test.ts @@ -0,0 +1,283 @@ +import { expect, test } from 'bun:test' +import { createMezzanine } from '../commands/structure/create-mezzanine' +import { createZone } from '../commands/structure/create-zone' +import { cutFloorOpening, removeFloorOpening } from '../commands/structure/floor-opening' +import { structureChangeBatch } from '../commands/structure/shared' +import { area, difference, union } from '../lib/polygon-boolean' +import { + initSpaceDetectionSync, + pauseSpaceDetection, + resumeSpaceDetection, +} from '../lib/space-detection' +import { BuildingNode, generateId, LevelNode, StairNode, StairSegmentNode } from '../schema' +import { initializeStairOpeningSync } from '../systems/stair/stair-opening-system' +import useScene, { clearSceneHistory } from './use-scene' + +const rect = (x0: number, z0: number, x1: number, z1: number): [number, number][] => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], +] + +test.each([ + false, + true, +])('a live opening cuts both surfaces and undoes (paused: %s)', async (paused) => { + const frames = { + requestAnimationFrame: globalThis.requestAnimationFrame, + cancelAnimationFrame: globalThis.cancelAnimationFrame, + } + globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => { + callback(0) + return 1 + }) as typeof requestAnimationFrame + globalThis.cancelAnimationFrame = () => {} + const building = BuildingNode.parse({ + id: 'building_live_opening', + children: ['level_live_0', 'level_live_1'], + }) + const ground = LevelNode.parse({ id: 'level_live_0', parentId: building.id, level: 0 }) + const upper = LevelNode.parse({ id: 'level_live_1', parentId: building.id, level: 1 }) + useScene.setState({ + nodes: { [building.id]: building, [ground.id]: ground, [upper.id]: upper }, + rootNodeIds: [building.id], + dirtyNodes: new Set(), + materials: {}, + collections: {}, + readOnly: false, + }) + clearSceneHistory() + const stop = initSpaceDetectionSync(useScene, { + getState: () => ({ spaces: {}, setSpaces: () => {} }), + }) + const solid = (levelId: string, type: 'slab' | 'ceiling') => + Object.values(useScene.getState().nodes) + .filter((node) => node.parentId === levelId && node.type === type && node.boundary === 'auto') + .reduce( + (sum, node) => + sum + + area( + difference(node.polygon, union(node.holes.map((hole) => ({ outer: hole, holes: [] })))), + ), + 0, + ) + try { + let upperRoomId = '' + for (const levelId of [ground.id, upper.id]) { + const plan = createZone(useScene.getState().nodes, { + levelId, + polygon: rect(0, 0, 8, 5), + enclose: true, + mintId: generateId, + name: 'Room', + }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + if (levelId === upper.id) upperRoomId = plan.zoneId + } + clearSceneHistory() + const beforePlate = solid(upper.id, 'slab') + const beforeCeiling = solid(ground.id, 'ceiling') + const plan = cutFloorOpening(useScene.getState().nodes, { + zoneId: upperRoomId, + polygon: rect(2, 1, 4, 2), + mintId: () => 'floor-opening_live_cut', + }) + expect( + plan.changes.some( + (change) => change.op === 'update' && useScene.getState().nodes[change.id]?.type === 'slab', + ), + ).toBe(false) + if (paused) pauseSpaceDetection() + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + if (paused) resumeSpaceDetection() + expect(beforePlate - solid(upper.id, 'slab')).toBeCloseTo(2) + expect(beforeCeiling - solid(ground.id, 'ceiling')).toBeCloseTo(2) + + useScene.temporal.getState().undo() + await Promise.resolve() + expect(solid(upper.id, 'slab')).toBeCloseTo(beforePlate) + expect(solid(ground.id, 'ceiling')).toBeCloseTo(beforeCeiling) + useScene.temporal.getState().redo() + await Promise.resolve() + expect(beforePlate - solid(upper.id, 'slab')).toBeCloseTo(2) + expect(beforeCeiling - solid(ground.id, 'ceiling')).toBeCloseTo(2) + + if (paused) pauseSpaceDetection() + useScene + .getState() + .updateNodes([{ id: 'floor-opening_live_cut', data: { polygon: rect(2, 1, 5, 2) } }]) + if (paused) resumeSpaceDetection() + expect(beforePlate - solid(upper.id, 'slab')).toBeCloseTo(3) + expect(beforeCeiling - solid(ground.id, 'ceiling')).toBeCloseTo(3) + + const removal = removeFloorOpening(useScene.getState().nodes, 'floor-opening_live_cut') + if (paused) pauseSpaceDetection() + useScene.getState().applyNodeChanges(structureChangeBatch(removal.changes)) + if (paused) resumeSpaceDetection() + expect(solid(upper.id, 'slab')).toBeCloseTo(beforePlate) + expect(solid(ground.id, 'ceiling')).toBeCloseTo(beforeCeiling) + + const mezzanine = createMezzanine(useScene.getState().nodes, { + hostZoneId: upperRoomId, + polygon: rect(1, 1, 7, 4), + elevation: 1.5, + mintId: generateId, + }) + expect(mezzanine.conflicts).toBeUndefined() + useScene.getState().applyNodeChanges(structureChangeBatch(mezzanine.changes)) + const mezzArea = () => + Object.values(useScene.getState().nodes) + .filter((node) => node.type === 'slab' && node.zoneIds?.includes(mezzanine.zoneId)) + .reduce( + (sum, node) => + sum + + area( + difference( + node.polygon, + union(node.holes.map((hole) => ({ outer: hole, holes: [] }))), + ), + ), + 0, + ) + const beforeMezz = mezzArea() + const hatch = cutFloorOpening(useScene.getState().nodes, { + zoneId: mezzanine.zoneId, + polygon: rect(2, 1.5, 4, 2.5), + mintId: () => 'floor-opening_live_hatch', + }) + if (paused) pauseSpaceDetection() + useScene.getState().applyNodeChanges(structureChangeBatch(hatch.changes)) + if (paused) resumeSpaceDetection() + expect(beforeMezz - mezzArea()).toBeCloseTo(2) + expect(solid(upper.id, 'slab') - mezzArea()).toBeCloseTo(beforePlate) + } finally { + if (paused) resumeSpaceDetection() + stop() + clearSceneHistory() + Object.assign(globalThis, frames) + } +}) + +test('stair edits own the live floor and ceiling cuts in one undo step', async () => { + const previousFrame = globalThis.requestAnimationFrame + const previousCancel = globalThis.cancelAnimationFrame + globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => { + callback(0) + return 1 + }) as typeof requestAnimationFrame + globalThis.cancelAnimationFrame = () => {} + const building = BuildingNode.parse({ + id: 'building_live_stair', + children: ['level_live_stair_0', 'level_live_stair_1'], + }) + const ground = LevelNode.parse({ id: 'level_live_stair_0', parentId: building.id, level: 0 }) + const upper = LevelNode.parse({ id: 'level_live_stair_1', parentId: building.id, level: 1 }) + useScene.setState({ + nodes: { [building.id]: building, [ground.id]: ground, [upper.id]: upper }, + rootNodeIds: [building.id], + dirtyNodes: new Set(), + materials: {}, + collections: {}, + readOnly: false, + }) + clearSceneHistory() + const stopStructure = initSpaceDetectionSync(useScene, { + getState: () => ({ spaces: {}, setSpaces: () => {} }), + }) + const stopStair = initializeStairOpeningSync() + const settle = async () => { + for (let index = 0; index < 4; index++) await Promise.resolve() + } + const owned = () => + Object.values(useScene.getState().nodes).filter( + (node) => node.type === 'floor-opening' && node.ownerId === 'stair_live_owned', + ) + const cut = (levelId: string, type: 'slab' | 'ceiling') => + Object.values(useScene.getState().nodes).some( + (node) => + node.parentId === levelId && + node.type === type && + node.holeMetadata.some( + (entry) => + entry.source === 'floor-opening' && + owned().some((opening) => opening.id === entry.openingId), + ), + ) + try { + for (const levelId of [ground.id, upper.id]) { + const plan = createZone(useScene.getState().nodes, { + levelId, + polygon: rect(0, 0, 8, 5), + enclose: true, + mintId: generateId, + }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + } + await settle() + clearSceneHistory() + const stair = StairNode.parse({ + id: 'stair_live_owned', + parentId: ground.id, + fromLevelId: ground.id, + toLevelId: upper.id, + slabOpeningMode: 'destination', + position: [3, 0, 1], + children: ['sseg_live_owned'], + }) + const segment = StairSegmentNode.parse({ + id: 'sseg_live_owned', + parentId: stair.id, + length: 3, + height: 3, + width: 1, + }) + useScene.getState().applyNodeChanges( + structureChangeBatch([ + { op: 'create', node: stair }, + { op: 'create', node: segment }, + ]), + ) + await settle() + expect(owned()).toHaveLength(2) + expect(cut(upper.id, 'slab')).toBe(true) + expect(cut(ground.id, 'ceiling')).toBe(true) + useScene.getState().updateNode(stair.id, { position: [4, 0, 1] }) + await settle() + expect(owned()).toHaveLength(2) + expect( + owned().every( + (opening) => opening.type === 'floor-opening' && opening.polygon.some(([x]) => x > 4), + ), + ).toBe(true) + useScene.temporal.getState().undo() + await settle() + expect( + useScene.getState().nodes[stair.id]?.type === 'stair' && + useScene.getState().nodes[stair.id].position[0], + ).toBe(3) + expect(cut(upper.id, 'slab')).toBe(true) + useScene.temporal.getState().redo() + await settle() + expect( + useScene.getState().nodes[stair.id]?.type === 'stair' && + useScene.getState().nodes[stair.id].position[0], + ).toBe(4) + useScene.getState().deleteNodes([stair.id, segment.id]) + await settle() + expect(owned()).toHaveLength(0) + expect(cut(upper.id, 'slab')).toBe(false) + expect(cut(ground.id, 'ceiling')).toBe(false) + useScene.temporal.getState().undo() + await settle() + expect(owned()).toHaveLength(2) + expect(cut(upper.id, 'slab')).toBe(true) + expect(cut(ground.id, 'ceiling')).toBe(true) + } finally { + stopStair() + stopStructure() + clearSceneHistory() + globalThis.requestAnimationFrame = previousFrame + globalThis.cancelAnimationFrame = previousCancel + } +}) diff --git a/packages/core/src/store/floor-opening-write-conversion.test.ts b/packages/core/src/store/floor-opening-write-conversion.test.ts new file mode 100644 index 0000000000..c6bc81dd67 --- /dev/null +++ b/packages/core/src/store/floor-opening-write-conversion.test.ts @@ -0,0 +1,284 @@ +import { expect, test } from 'bun:test' +import { type AnyNode, FloorOpeningNode, SlabNode } from '../schema' +import { convertDerivedPlateHoleWrites, filterDerivedNodeWrites } from './derived-node-guard' + +const square: [number, number][] = [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], +] +const moved: [number, number][] = [ + [2, 1], + [3, 1], + [3, 2], + [2, 2], +] +const plate = SlabNode.parse({ + id: 'slab_write_base', + parentId: 'level_write', + boundary: 'auto', + autoFromWalls: true, + plateRole: 'base', + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], +}) + +function writes(nodes: Record, slab = plate) { + return convertDerivedPlateHoleWrites(nodes, { + update: [ + { + id: slab.id, + data: { + holes: [square], + holeMetadata: [{ source: 'manual' as const }], + }, + }, + ], + }) +} + +test('plate hole edits reuse and remove the opening node', () => { + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_write', + parentId: plate.parentId, + polygon: square, + metadata: { plateHoleAuthoring: plate.id }, + cutsAdjacent: false, + }) + const nodes = { [plate.id]: plate, [opening.id]: opening } + const edited = convertDerivedPlateHoleWrites(nodes, { + update: [{ id: plate.id, data: { holes: [moved], holeMetadata: [{ source: 'manual' }] } }], + }) + expect(edited.create).toEqual([]) + expect(edited.update?.some((entry) => entry.id === opening.id && 'polygon' in entry.data)).toBe( + true, + ) + const removed = convertDerivedPlateHoleWrites(nodes, { + update: [{ id: plate.id, data: { holes: [], holeMetadata: [] } }], + }) + expect(removed.delete).toContain(opening.id) +}) + +test('pool spillover dedupes by owner and keeps stair holes on the same plate', () => { + const sibling = SlabNode.parse({ ...plate, id: 'slab_write_platform', plateRole: 'platform' }) + const metadata = { poolManagedOpenings: [{ poolId: 'pool_write', polygon: square }] } + const converted = convertDerivedPlateHoleWrites( + { [plate.id]: plate, [sibling.id]: sibling }, + { + update: [plate, sibling].map((slab) => ({ + id: slab.id, + data: { + holes: [square, moved], + holeMetadata: [ + { source: 'manual' as const }, + { source: 'stair' as const, stairId: 'stair_write' }, + ], + metadata, + }, + })), + }, + ) + expect(converted.create).toHaveLength(1) + expect(converted.create?.[0]?.node).toMatchObject({ + source: 'plugin:pool', + ownerId: 'pool_write', + cutsAdjacent: false, + }) + expect(converted.update?.[0]?.data.holeMetadata).toEqual([ + { source: 'stair', stairId: 'stair_write' }, + ]) + const existing = converted.create![0]!.node + const duplicated = FloorOpeningNode.parse({ + ...existing, + id: 'floor-opening_duplicate_pool', + }) + const again = convertDerivedPlateHoleWrites( + { + [plate.id]: plate, + [sibling.id]: sibling, + [existing.id]: existing, + [duplicated.id]: duplicated, + }, + { + update: [ + { id: plate.id, data: { holes: [square], holeMetadata: [{ source: 'manual' }], metadata } }, + ], + }, + ) + expect(again.create).toEqual([]) + expect(again.delete).toHaveLength(1) +}) + +test('new stair and elevator holes pass through an existing floor opening', () => { + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_existing', + parentId: plate.parentId, + polygon: square, + }) + const current = SlabNode.parse({ + ...plate, + holes: [square], + holeMetadata: [{ source: 'floor-opening', openingId: opening.id }], + }) + for (const managed of [ + { source: 'stair' as const, stairId: 'stair_write' }, + { source: 'elevator' as const, elevatorId: 'elevator_write' }, + ]) { + const changed = convertDerivedPlateHoleWrites( + { [current.id]: current, [opening.id]: opening }, + { + update: [ + { + id: current.id, + data: { + holes: [square, moved], + holeMetadata: [{ source: 'floor-opening', openingId: opening.id }, managed], + }, + }, + ], + }, + ) + expect(changed.update?.[0]?.data.holeMetadata).toHaveLength(2) + expect(changed.delete).toBeUndefined() + } +}) + +test('managed slab writes preserve an opening cut missing from their snapshot', () => { + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_preserved', + parentId: plate.parentId, + polygon: square, + }) + const current = SlabNode.parse({ + ...plate, + holes: [square], + holeMetadata: [{ source: 'floor-opening', openingId: opening.id }], + }) + const nodes = { [current.id]: current, [opening.id]: opening } + for (const data of [ + { holes: [moved], holeMetadata: [{ source: 'stair' as const, stairId: 'stair_write' }] }, + { + holes: [] as (typeof square)[], + holeMetadata: [] as typeof current.holeMetadata, + metadata: { poolManagedOpenings: [{ poolId: 'pool_write', polygon: moved }] }, + }, + ]) { + const converted = convertDerivedPlateHoleWrites(nodes, { + update: [{ id: current.id, data }], + }) + expect(converted.delete ?? []).not.toContain(opening.id) + expect(converted.update?.[0]?.data.holeMetadata).toContainEqual({ + source: 'floor-opening', + openingId: opening.id, + }) + } +}) + +test('pool metadata relabelling is a no-op for core-owned holes', () => { + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_pool_relabel', + parentId: plate.parentId, + polygon: square, + }) + const current = SlabNode.parse({ + ...plate, + holes: [square, moved], + holeMetadata: [{ source: 'floor-opening', openingId: opening.id }, { source: 'room' }], + }) + const nodes = { [current.id]: current, [opening.id]: opening } + const converted = convertDerivedPlateHoleWrites(nodes, { + update: [ + { + id: current.id, + data: { + holes: [square, moved], + holeMetadata: [{ source: 'manual' as const }, { source: 'manual' as const }], + metadata: current.metadata, + }, + }, + ], + }) + expect(converted.create).toEqual([]) + expect(converted.delete ?? []).not.toContain(opening.id) + expect(converted.update?.[0]?.data.holes).toBeUndefined() + expect(converted.update?.[0]?.data.holeMetadata).toBeUndefined() + expect(filterDerivedNodeWrites(nodes, converted).update).toEqual([]) +}) + +test('pool geometry edits retain original opening, room, stair, and elevator tags', () => { + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_pool_geometry', + parentId: plate.parentId, + polygon: square, + }) + const stair: [number, number][] = [ + [0, 2], + [1, 2], + [1, 3], + [0, 3], + ] + const elevator: [number, number][] = [ + [2, 2], + [3, 2], + [3, 3], + [2, 3], + ] + const pool: [number, number][] = [ + [0, 0], + [1, 0], + [1, 1], + [0, 1], + ] + const holeMetadata = [ + { source: 'floor-opening' as const, openingId: opening.id }, + { source: 'room' as const }, + { source: 'stair' as const, stairId: 'stair_write' }, + { source: 'elevator' as const, elevatorId: 'elevator_write' }, + ] + const current = SlabNode.parse({ + ...plate, + holes: [square, moved, stair, elevator], + holeMetadata, + }) + const converted = convertDerivedPlateHoleWrites( + { [current.id]: current, [opening.id]: opening }, + { + update: [ + { + id: current.id, + data: { + holes: [...current.holes, pool], + holeMetadata: [ + ...current.holes.map(() => ({ source: 'manual' as const })), + { source: 'manual' as const }, + ], + metadata: { poolManagedOpenings: [{ poolId: 'pool_write', polygon: pool }] }, + }, + }, + ], + }, + ) + expect(converted.create?.[0]?.node).toMatchObject({ source: 'plugin:pool' }) + expect(converted.delete ?? []).not.toContain(opening.id) + expect(converted.update?.[0]?.data.holeMetadata).toEqual(holeMetadata) +}) + +test('legacy mezzanine plate hole authors a hosted, floor-only opening', () => { + const mezzanine = SlabNode.parse({ + ...plate, + id: 'slab_write_mezzanine', + support: 'open', + plateRole: undefined, + zoneIds: ['zone_write_mezzanine'], + }) + const converted = writes({ [mezzanine.id]: mezzanine }, mezzanine) + expect(converted.create?.[0]?.node).toMatchObject({ + hostZoneId: 'zone_write_mezzanine', + cutsAdjacent: false, + }) +}) diff --git a/packages/core/src/store/history-control.ts b/packages/core/src/store/history-control.ts index 17eaea4597..4e2689cfa4 100644 --- a/packages/core/src/store/history-control.ts +++ b/packages/core/src/store/history-control.ts @@ -3,6 +3,41 @@ import type { SceneMaterial, SceneMaterialId } from '../schema/scene-material' import type { AnyNode, AnyNodeId } from '../schema/types' import { withSceneHistoryDraftSuspended } from './history-drafts' +let sceneHistoryRestoreDepth = 0 + +export function isRestoringSceneHistory(): boolean { + return sceneHistoryRestoreDepth > 0 +} + +export function runAsSceneHistoryRestore(run: () => T): T { + sceneHistoryRestoreDepth += 1 + try { + return run() + } finally { + sceneHistoryRestoreDepth -= 1 + } +} + +let remoteSceneOperationDepth = 0 + +/** + * Whether the scene is being written by a collaborator's change (a shared + * operation or snapshot applied from the host), not by this client — what a + * live session that takes back its own writes must leave alone. + */ +export function isApplyingRemoteSceneChange(): boolean { + return remoteSceneOperationDepth > 0 +} + +export function runAsRemoteSceneChange(run: () => T): T { + remoteSceneOperationDepth += 1 + try { + return run() + } finally { + remoteSceneOperationDepth -= 1 + } +} + let sceneHistoryPauseDepth = 0 const sceneHistoryPauseLeases = new Set() diff --git a/packages/core/src/store/history-invalidation.test.ts b/packages/core/src/store/history-invalidation.test.ts index 101cc04795..49f23b8f18 100644 --- a/packages/core/src/store/history-invalidation.test.ts +++ b/packages/core/src/store/history-invalidation.test.ts @@ -75,6 +75,8 @@ describe('history dependency closure', () => { { thickness: 0.4 }, { height: 4 }, { curveOffset: 0.8 }, + { justification: 'a' as const }, + { justification: 'b' as const }, ])('host shape change %j includes opening proxies and wall-side items', (patch) => { const door = DoorNode.parse({ parentId: wall.id }) const window = WindowNode.parse({ parentId: wall.id }) @@ -238,6 +240,61 @@ describe('consecutive temporal wall moves', () => { restore() }) + test('justification-only undo and redo dirty hosted children', async () => { + const door = DoorNode.parse({ parentId: wall.id }) + const window = WindowNode.parse({ parentId: wall.id }) + const item = ItemNode.parse({ parentId: wall.id, asset: { ...asset, attachTo: 'wall-side' } }) + const other = ItemNode.parse({ parentId: remote.id, asset }) + useScene.setState({ + nodes: nodes(level, wall, remote, door, window, item, other), + rootNodeIds: [level.id], + collections: {}, + installedPlugins: [], + dirtyNodes: new Set(), + readOnly: false, + }) + clearSceneHistory() + const justified = { ...wall, justification: 'a' as const } + useScene.setState({ nodes: { ...useScene.getState().nodes, [wall.id]: justified } }) + + for (const direction of ['undo', 'redo'] as const) { + useScene.getState().dirtyNodes.clear() + useScene.temporal.getState()[direction]() + await Promise.resolve() + expect(useScene.getState().nodes[wall.id]).toBe(direction === 'undo' ? wall : justified) + expect([...useScene.getState().dirtyNodes].sort()).toEqual( + [level.id, wall.id, door.id, window.id, item.id].sort(), + ) + } + }) + + test('a new edit after an undo is an edit, not a redo', async () => { + const moved = { ...wall, start: [0, 2], end: [4, 2] } as WallNode + useScene.setState({ + nodes: nodes(level, wall, remote), + rootNodeIds: [level.id], + collections: {}, + installedPlugins: [], + dirtyNodes: new Set(), + readOnly: false, + }) + clearSceneHistory() + useScene.setState({ nodes: { ...useScene.getState().nodes, [wall.id]: moved } }) + useScene.temporal.getState().undo() + await Promise.resolve() + expect(useScene.temporal.getState().futureStates).toHaveLength(1) + + useScene.getState().dirtyNodes.clear() + // The edit drops the redo stack and grows the past, as a redo would. + useScene.setState({ + nodes: { ...useScene.getState().nodes, [remote.id]: { ...remote, end: [26, 0] } as WallNode }, + }) + await Promise.resolve() + expect(useScene.temporal.getState().futureStates).toHaveLength(0) + // Only the edit's own writer marks what it changed; no history diff ran. + expect([...useScene.getState().dirtyNodes]).toEqual([]) + }) + test('three undos and redos mark exactly the neighbours in each pre/post-jump layout', async () => { const neighbours = [0, 10, 20, 30].map((x, index) => WallNode.parse({ diff --git a/packages/core/src/store/history-invalidation.ts b/packages/core/src/store/history-invalidation.ts index 5e20d6051e..b78dcfd7c5 100644 --- a/packages/core/src/store/history-invalidation.ts +++ b/packages/core/src/store/history-invalidation.ts @@ -26,6 +26,7 @@ export function getHistoryDirtyNodeIds( previous?.type !== 'wall' || next?.type !== 'wall' || previous.thickness !== next.thickness || + previous.justification !== next.justification || previous.height !== next.height || previous.curveOffset !== next.curveOffset ) { diff --git a/packages/core/src/store/registered-node-defaults.test.ts b/packages/core/src/store/registered-node-defaults.test.ts new file mode 100644 index 0000000000..7154552f30 --- /dev/null +++ b/packages/core/src/store/registered-node-defaults.test.ts @@ -0,0 +1,117 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test' +import { z } from 'zod' +import { nodeRegistry, registerNode } from '../registry/registry' +import { AnyNode, nodeKindOf } from '../schema/types' +import { materializeRegisteredNodeDefaults } from './registered-node-defaults' +import useScene, { clearSceneHistory } from './use-scene' + +type RawNode = Record + +const node = (id: string, type: string, parentId: string | null, extra: RawNode = {}): RawNode => ({ + object: 'node', + id, + type, + parentId, + visible: true, + metadata: {}, + ...extra, +}) + +const square: Array<[number, number]> = [ + [0, 0], + [6, 0], + [6, 6], + [0, 6], +] + +// A legacy two-storey scene as production stores it: no level heights, and a +// raised first-floor slab without `thickness`, which the loader reads as a +// solid from the level base up to its top (the facade band between storeys). +function legacyScene() { + const walls = (levelId: string, prefix: string, height: number) => + square.map((start, index) => + node(`wall_${prefix}${index}`, 'wall', levelId, { + start, + end: square[(index + 1) % square.length], + children: [], + height, + }), + ) + const ground = walls('level_ground', 'g', 2.5) + const first = walls('level_first', 'f', 3) + const nodes: Record = { + site_a: node('site_a', 'site', null, { children: ['building_a'] }), + building_a: node('building_a', 'building', 'site_a', { + children: ['level_ground', 'level_first'], + }), + level_ground: node('level_ground', 'level', 'building_a', { + level: 0, + children: [...ground.map((wall) => wall.id), 'slab_ground'], + }), + level_first: node('level_first', 'level', 'building_a', { + level: 1, + children: [...first.map((wall) => wall.id), 'slab_raised'], + }), + slab_ground: node('slab_ground', 'slab', 'level_ground', { polygon: square, elevation: 0.05 }), + slab_raised: node('slab_raised', 'slab', 'level_first', { polygon: square, elevation: 0.8 }), + } + for (const wall of [...ground, ...first]) nodes[wall.id as string] = wall + return { nodes, rootNodeIds: ['site_a'] } +} + +function load(nodes: Record, rootNodeIds: string[]) { + clearSceneHistory() + useScene.getState().setScene(structuredClone(nodes) as never, rootNodeIds as never) + return structuredClone(useScene.getState().nodes) as Record +} + +describe('materializeRegisteredNodeDefaults', () => { + let restoreRegistry: () => void + beforeEach(() => { + restoreRegistry = nodeRegistry._snapshot() + }) + afterEach(() => restoreRegistry()) + + test('materializes registered schema defaults for kinds the loader does not own', () => { + registerNode({ + kind: 'test-scene-normalization', + schema: z.object({ + id: z.string(), + position: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), + rotation: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]), + type: z.literal('test-scene-normalization'), + }), + schemaVersion: 1, + } as never) + + expect( + materializeRegisteredNodeDefaults({ + test: { id: 'test', type: 'test-scene-normalization' }, + unknown: { id: 'unknown', type: 'unknown-kind', custom: true }, + }), + ).toEqual({ + test: { + id: 'test', + position: [0, 0, 0], + rotation: [0, 0, 0], + type: 'test-scene-normalization', + }, + unknown: { id: 'unknown', type: 'unknown-kind', custom: true }, + }) + }) + + test('the editor loads a legacy scene exactly like the viewer, raised slab body included', () => { + // The app registers every built-in kind with its core schema (`@pascal-app/nodes`). + for (const option of AnyNode.options) { + const kind = nodeKindOf(option) + if (!nodeRegistry.get(kind)) registerNode({ kind, schema: option, schemaVersion: 1 } as never) + } + const scene = legacyScene() + const editor = load(materializeRegisteredNodeDefaults(scene.nodes), scene.rootNodeIds) + const viewer = load(scene.nodes, scene.rootNodeIds) + + expect(editor.slab_raised.thickness).toBe(0.8) + expect(editor.slab_raised.elevation).toBe(0.8) + expect(editor).toEqual(viewer) + }) +}) diff --git a/packages/core/src/store/registered-node-defaults.ts b/packages/core/src/store/registered-node-defaults.ts new file mode 100644 index 0000000000..298b0018ca --- /dev/null +++ b/packages/core/src/store/registered-node-defaults.ts @@ -0,0 +1,29 @@ +import { nodeRegistry } from '../registry/registry' +import { AnyNode, nodeKindOf } from '../schema/types' + +let builtinKinds: Set | undefined + +/** + * Fills registered schema defaults on stored nodes before `setScene`, for kinds + * the scene loader does not own. Built-in kinds are left exactly as stored: the + * loader's migrations read what a stored node leaves out (a legacy slab without + * `thickness` occupies `[0, elevation]`, a level without `height` marks a legacy + * scene) and a zod parse would also strip legacy fields they consume. Parsing + * them here made the editor load legacy scenes differently from the viewer and + * the hosted authority. + */ +export function materializeRegisteredNodeDefaults( + nodes: Readonly>, +): Record { + builtinKinds ??= new Set(AnyNode.options.map(nodeKindOf)) + const kinds = builtinKinds + return Object.fromEntries( + Object.entries(nodes).map(([id, value]) => { + if (!value || typeof value !== 'object' || Array.isArray(value)) return [id, value] + const type = (value as { type?: unknown }).type + if (typeof type !== 'string' || kinds.has(type)) return [id, value] + const parsed = nodeRegistry.get(type)?.schema.safeParse(value) + return [id, parsed?.success ? parsed.data : value] + }), + ) +} diff --git a/packages/core/src/store/use-scene-commits.test.ts b/packages/core/src/store/use-scene-commits.test.ts index b9d5889f8d..4daba8149c 100644 --- a/packages/core/src/store/use-scene-commits.test.ts +++ b/packages/core/src/store/use-scene-commits.test.ts @@ -1,20 +1,17 @@ import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test' import { z } from 'zod' -import { - createWallBoundSurfaceFollower, - detectSpacesForLevel, - initSpaceDetectionSync, - type Space, -} from '../lib/space-detection' +import { initSpaceDetectionSync, type Space } from '../lib/space-detection' import { nodeRegistry } from '../registry/registry' import type { AnyNodeDefinition } from '../registry/types' import { BuildingNode } from '../schema/nodes/building' import { CeilingNode } from '../schema/nodes/ceiling' +import { ItemNode } from '../schema/nodes/item' import { LevelNode } from '../schema/nodes/level' import { SlabNode } from '../schema/nodes/slab' import { WallNode } from '../schema/nodes/wall' import { SceneMaterial, type SceneMaterialId } from '../schema/scene-material' import type { AnyNode, AnyNodeId } from '../schema/types' +import { migrateCeilingRoomLinks, migrateRoomZones } from '../utils/room-zone-migration' import { areSceneSnapshotsEqual, pauseSceneHistory, @@ -396,6 +393,7 @@ describe('scene commit boundary', () => { 'ceiling', 'slab', 'wall', + 'zone', ]) stopDetection() @@ -425,7 +423,7 @@ describe('scene commit boundary', () => { expect(Object.values(spaces)).toHaveLength(2) expect( receiverNodes.filter((node) => node.type === 'slab' && node.autoFromWalls), - ).toHaveLength(2) + ).toHaveLength(1) expect( receiverNodes.filter((node) => node.type === 'ceiling' && node.autoFromWalls), ).toHaveLength(2) @@ -434,74 +432,74 @@ describe('scene commit boundary', () => { } }) - describe('wall-bound surface follower', () => { - const autoSlab = (polygon: Array<[number, number]>) => - SlabNode.parse({ parentId: LEVEL_ID, polygon, autoFromWalls: true }) - const nodesOf = (entries: AnyNode[]) => - Object.fromEntries(entries.map((node) => [node.id, node])) as Record - - test('keeps a corner on the walls that bound it at a junction with a diagonal branch', () => { - // The diagonal leaves the divider's foot outside the room; it bounds no room vertex. - const diagonal = WallNode.parse({ parentId: LEVEL_ID, start: [2, 0], end: [1, -1] }) - const south = WallNode.parse({ parentId: LEVEL_ID, start: [0, 0], end: [4, 0] }) - const divider = WallNode.parse({ parentId: LEVEL_ID, start: [2, 0], end: [2, 4] }) - const north = WallNode.parse({ parentId: LEVEL_ID, start: [4, 4], end: [0, 4] }) - const west = WallNode.parse({ parentId: LEVEL_ID, start: [0, 4], end: [0, 0] }) - const slab = autoSlab([ - [0, 0], - [2, 0], - [2, 4], - [0, 4], - ]) - const follow = createWallBoundSurfaceFollower( - LEVEL_ID, - nodesOf([diagonal, south, divider, north, west, slab]), - new Set([divider.id]), - ) - - const [[, polygon]] = follow(new Map([[divider.id, { start: [2.5, 0], end: [2.5, 4] }]])) as [ - [string, Array<[number, number]>], - ] - expect(polygon).toEqual([ - [0, 0], - [2.5, 0], - [2.5, 4], - [0, 4], - ]) - }) - - test('carries the sampled arc of a curved wall with the wall', () => { - const walls = [ - WallNode.parse({ parentId: LEVEL_ID, start: [0, 0], end: [4, 0] }), - WallNode.parse({ parentId: LEVEL_ID, start: [4, 0], end: [4, 4], curveOffset: 0.8 }), - WallNode.parse({ parentId: LEVEL_ID, start: [4, 4], end: [0, 4] }), - WallNode.parse({ parentId: LEVEL_ID, start: [0, 4], end: [0, 0] }), - ] - const [room] = detectSpacesForLevel(LEVEL_ID, walls).roomPolygons - const polygon = room!.map((point) => [point.x, point.y] as [number, number]) - const arcVertices = polygon.filter(([x]) => x > 4 + 1e-6) - expect(arcVertices.length).toBeGreaterThan(0) - const slab = autoSlab(polygon) - const [south, east, north] = walls as [WallNode, WallNode, WallNode] - const follow = createWallBoundSurfaceFollower( - LEVEL_ID, - nodesOf([...walls, slab]), - new Set([east.id, south.id, north.id]), + test('host split and merge patches reparent ceiling children without deriving or losing identities', () => { + const polygon: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ] + const editor = { + spaces: {}, + setSpaces(spaces: Record) { + this.spaces = spaces + }, + } + let stop = initSpaceDetectionSync(useScene, { getState: () => editor }) + try { + useScene.getState().createNodes( + polygon.map((start, i) => ({ + node: WallNode.parse({ + id: `wall_host_${i}`, + parentId: LEVEL_ID, + start, + end: polygon[(i + 1) % 4], + }), + parentId: LEVEL_ID, + })), ) - - const [[, moved]] = follow( - new Map([ - [east.id, { start: [4.5, 0], end: [4.5, 4] }], - [south.id, { start: [0, 0], end: [4.5, 0] }], - [north.id, { start: [4.5, 4], end: [0, 4] }], - ]), - ) as [[string, Array<[number, number]>]] - polygon.forEach(([x, y], index) => { - const [mx, my] = moved[index]! - expect(my).toBeCloseTo(y, 6) - expect(mx).toBeCloseTo(x >= 4 - 1e-6 ? x + 0.5 : x, 6) + const ceiling = Object.values(useScene.getState().nodes).find( + (node): node is CeilingNode => node.type === 'ceiling', + )! + const item = ItemNode.parse({ + id: 'item_host_light', + parentId: ceiling.id, + position: [1, 0, 2], + asset: { + id: 'light', + name: 'Light', + category: 'lighting', + thumbnail: '', + src: '/light.glb', + }, }) - }) + useScene.getState().createNode(item, ceiling.id) + const commits: SceneCommit[] = [] + unsubscribe = subscribeSceneCommits((commit) => commits.push(commit)) + const divider = WallNode.parse({ + id: 'wall_host_divider', + parentId: LEVEL_ID, + start: [2, 0], + end: [2, 4], + }) + useScene.getState().createNode(divider, LEVEL_ID) + useScene.getState().deleteNode(divider.id) + const originals = [...commits] + expect(originals).toHaveLength(2) + for (const commit of originals) { + stop() + useScene.setState({ ...commit.before, readOnly: true }) + clearSceneHistory() + stop = initSpaceDetectionSync(useScene, { getState: () => editor }) + commits.length = 0 + expect(applySceneOperationPatch(operationPatchFromCommit(commit))).toBe(true) + expect(areSceneSnapshotsEqual(currentSnapshot(), commit.current)).toBe(true) + expect(commits.map((value) => value.origin)).toEqual(['host']) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + } + } finally { + stop() + } }) describe('wall move commit', () => { @@ -542,7 +540,7 @@ describe('scene commit boundary', () => { }) afterEach(() => stopDetection()) - const polygonsOf = (type: 'slab' | 'ceiling') => + const polygonsOf = (type: 'zone' | 'ceiling') => Object.values(useScene.getState().nodes).flatMap((node) => node.type === type ? [node.polygon] : [], ) @@ -566,70 +564,18 @@ describe('scene commit boundary', () => { expect(reconcilePasses).toBe(1) expect(commits).toHaveLength(1) expect(useScene.temporal.getState().pastStates).toHaveLength(1) - for (const polygons of [polygonsOf('slab'), polygonsOf('ceiling')]) { - expect(polygons.flat()).toContainEqual([2.5, 0]) - expect(polygons.flat()).not.toContainEqual([2, 0]) - } + // Rooms sit on wall centrelines, their ceilings on the wall faces. + expect(polygonsOf('zone').flat()).toContainEqual([2.5, 0]) + expect(polygonsOf('zone').flat()).not.toContainEqual([2, 0]) + const ceilingXs = polygonsOf('ceiling') + .flat() + .map(([x]) => x) + expect(ceilingXs.some((x) => Math.abs(x - 2.5) < 0.2)).toBe(true) + expect(ceilingXs.some((x) => Math.abs(x - 2) < 0.2)).toBe(false) useScene.temporal.getState().undo() expect(areSceneSnapshotsEqual(currentSnapshot(), before)).toBe(true) }) - - test('follows wall-bound automatic surfaces from membership read once', () => { - const nodes = useScene.getState().nodes - const slabIds = Object.values(nodes).flatMap((node) => - node.type === 'slab' ? [node.id] : [], - ) - const manual = SlabNode.parse({ - parentId: LEVEL_ID, - polygon: [ - [2, 0], - [3, 0], - [3, 1], - [2, 1], - ], - }) - const follow = createWallBoundSurfaceFollower( - LEVEL_ID, - { ...nodes, [manual.id]: manual }, - new Set(['wall_move_east', 'wall_move_south', 'wall_move_north']), - ) - - // The east wall moves out; its neighbours stretch along their own lines. - const polygons = new Map( - follow( - new Map([ - ['wall_move_east', { start: [5, 0], end: [5, 4] }], - ['wall_move_south', { start: [0, 0], end: [5, 0] }], - ['wall_move_north', { start: [5, 4], end: [0, 4] }], - ]), - ), - ) - - expect(polygons.has(manual.id)).toBe(false) - const eastRoom = slabIds - .map((id) => polygons.get(id)) - .find((polygon) => polygon?.some(([x]) => x === 5)) - expect(eastRoom).toEqual( - expect.arrayContaining([ - [2, 0], - [5, 0], - [5, 4], - [2, 4], - ]), - ) - const westRoom = slabIds - .map((id) => polygons.get(id)) - .find((polygon) => polygon?.some(([x]) => x === 0)) - expect(westRoom).toEqual( - expect.arrayContaining([ - [0, 0], - [2, 0], - [2, 4], - [0, 4], - ]), - ) - }) }) test('keeps a triangular room valid when an inward wall curve reaches its neighbours', () => { @@ -648,6 +594,7 @@ describe('scene commit boundary', () => { parentId: LEVEL_ID, polygon, autoFromWalls: true, + boundary: 'auto', }) const ceiling = CeilingNode.parse({ id: 'ceiling_curve_triangle', @@ -676,6 +623,11 @@ describe('scene commit boundary', () => { }, }), } + useScene.setState({ + nodes: migrateCeilingRoomLinks(migrateRoomZones(useScene.getState().nodes).nodes) + .nodes as Record, + }) + clearSceneHistory() const stopDetection = initSpaceDetectionSync(useScene, editorStore) try { @@ -714,6 +666,7 @@ describe('scene commit boundary', () => { parentId: LEVEL_ID, polygon, autoFromWalls: true, + boundary: 'auto', }) const ceiling = CeilingNode.parse({ id: 'ceiling_curve_square', @@ -734,6 +687,11 @@ describe('scene commit boundary', () => { clearSceneHistory() let spaces: Record = {} + useScene.setState({ + nodes: migrateCeilingRoomLinks(migrateRoomZones(useScene.getState().nodes).nodes) + .nodes as Record, + }) + clearSceneHistory() const stopDetection = initSpaceDetectionSync(useScene, { getState: () => ({ spaces, @@ -1359,7 +1317,7 @@ describe('scene commit boundary', () => { test('semantic equality short-circuits shared nodes in a large scene', () => { const nodes: Record = {} - for (let index = 0; index < 1_000; index += 1) { + for (let index = 0; index < 1000; index += 1) { const id = `level_${index}` as AnyNodeId nodes[id] = { id, type: 'level', level: index, children: [] } as unknown as AnyNode } diff --git a/packages/core/src/store/use-scene-dirty-tracking.test.ts b/packages/core/src/store/use-scene-dirty-tracking.test.ts index 53ddb946d7..3f19553e21 100644 --- a/packages/core/src/store/use-scene-dirty-tracking.test.ts +++ b/packages/core/src/store/use-scene-dirty-tracking.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test' import { nodeRegistry } from '../registry/registry' import type { AnyNodeDefinition } from '../registry/types' import type { AnyNode, AnyNodeId } from '../schema/types' +import useLiveNodeOverrides from './use-live-node-overrides' import useScene from './use-scene' const untrackedDef = { @@ -111,6 +112,31 @@ describe('dirty tracking', () => { expect(useScene.getState().dirtyNodes.has(TRACKED)).toBe(false) }) + test('a node drawn from a live override rebuilds once the override goes, whoever clears it', () => { + const overrides = useLiveNodeOverrides.getState() + const dirty = () => useScene.getState().dirtyNodes + overrides.set(TRACKED, { polygon: [[0, 0]], holes: [] }) + dirty().clear() + // Updating the preview is the previewer's to mark; nothing is forced here. + overrides.set(TRACKED, { polygon: [[1, 1]] }) + expect(dirty().has(TRACKED)).toBe(false) + // Dropping one field rebuilds… + overrides.clearFields(TRACKED, ['holes']) + expect(dirty().has(TRACKED)).toBe(true) + dirty().clear() + // …and so does dropping the override, alone or with every other one. + overrides.clear(TRACKED) + expect(dirty().has(TRACKED)).toBe(true) + dirty().clear() + overrides.setMany([ + [TRACKED, { polygon: [] }], + ['item_gone', { polygon: [] }], + ]) + dirty().clear() + overrides.clearAll() + expect([...dirty()]).toEqual([TRACKED]) + }) + test('visibility updates mark dirty before the batched RAF callback', () => { let scheduled: ((time: number) => void) | null = null const previousRaf = globalThis.requestAnimationFrame diff --git a/packages/core/src/store/use-scene-floor-top.test.ts b/packages/core/src/store/use-scene-floor-top.test.ts new file mode 100644 index 0000000000..bb645726c0 --- /dev/null +++ b/packages/core/src/store/use-scene-floor-top.test.ts @@ -0,0 +1,183 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { createZone, divideZone, setZoneIntent, structureChangeBatch } from '../commands/structure' +import { roomFace } from '../commands/structure/shared' +import { roomClearPolygon } from '../lib/level-footprints' +import { + computePlateSurfacePartition, + plateLevelContext, + roomFinishRole, +} from '../lib/plate-surface' +import { area, difference, type Ring, union } from '../lib/polygon-boolean' +import { createRoomTopologyIndex, initSpaceDetectionSync } from '../lib/space-detection' +import { BuildingNode, LevelNode, WallNode, type ZoneNode } from '../schema' +import useScene, { clearSceneHistory } from './use-scene' + +const rectangle: Ring = [ + [0, 0], + [6, 0], + [6, 4], + [0, 4], +] +const concave: Ring = [ + [0, 0], + [6, 0], + [6, 2], + [3, 2], + [3, 5], + [0, 5], +] +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +let stop = () => {} +let previous: ReturnType +let sequence = 0 +const mintId = (kind: string) => `${kind}_floor_probe_${sequence++}` +const levelId = 'level_floor_probe' +beforeEach(() => { + previous = useScene.getState() + globalThis.requestAnimationFrame = (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame = () => {} + const level = LevelNode.parse({ id: levelId, parentId: 'building_floor_probe', height: 3 }) + const building = BuildingNode.parse({ id: 'building_floor_probe', children: [level.id] }) + useScene.setState({ + nodes: { [level.id]: level, [building.id]: building }, + rootNodeIds: [building.id], + dirtyNodes: new Set(), + readOnly: false, + }) + clearSceneHistory() + stop = initSpaceDetectionSync(useScene, { getState: () => ({ spaces: {}, setSpaces: () => {} }) }) +}) +afterEach(() => { + stop() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf + useScene.setState(previous, true) + clearSceneHistory() +}) + +function assertRoomTops(count: number, paint = true) { + const nodes = useScene.getState().nodes + const context = plateLevelContext(nodes[levelId]!, (id) => nodes[id]) + const topology = createRoomTopologyIndex() + topology.rebuild(nodes) + const zones = context.zones.filter((zone) => zone.spaceRole === 'room') + expect(zones).toHaveLength(count) + for (const zone of zones) { + expect(zone.hasFloor).not.toBe(false) + const plates = context.slabs.filter( + (slab) => slab.boundary === 'auto' && slab.zoneIds?.includes(zone.id), + ) + expect(plates.length).toBeGreaterThan(0) + const face = roomFace(nodes, zone)! + expect(face).toBeDefined() + const clear = roomClearPolygon( + topology.getLevelTopology(levelId)!.rooms.find((room) => room.id === face.id)!, + ) + expect(area(clear)).toBeGreaterThan(1) + expect( + area( + difference( + clear, + union(plates.map((plate) => ({ outer: plate.polygon, holes: plate.holes }))), + ), + ), + ).toBeLessThan(1e-6) + const cells = plates.flatMap((plate) => { + const partition = computePlateSurfacePartition(plate, context) + expect(partition).not.toBeNull() + expect(area(partition!.masked)).toBe(0) + return partition!.cells + }) + expect(area(difference(clear, union(cells.flatMap((cell) => cell.polygons))))).toBeLessThan( + 1e-6, + ) + if (zone.floor?.finish) + expect(cells.some((cell) => cell.role === roomFinishRole(zone.id))).toBe(true) + } + if (paint) { + for (const zone of zones) + useScene.getState().applyNodeChanges( + structureChangeBatch( + setZoneIntent(useScene.getState().nodes, { + zoneId: zone.id, + patch: { floor: { finish: 'library:wood-woodplank48' } }, + }).changes, + ), + ) + assertRoomTops(count, false) + } +} + +function create(polygon: Ring, enclose: boolean) { + const plan = createZone(useScene.getState().nodes, { levelId, polygon, enclose, mintId }) + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + return plan.zoneId as ZoneNode['id'] +} + +for (const reverse of [false, true]) { + test(`L-shaped wall room has a plate and complete top cells (reversed=${reverse})`, () => { + const points = reverse ? [...concave].reverse() : concave + for (const [i, start] of points.entries()) { + useScene.getState().createNode( + WallNode.parse({ + id: mintId('wall'), + parentId: levelId, + start, + end: points[(i + 1) % points.length], + }), + levelId, + ) + } + assertRoomTops(1) + }) +} + +test('separator Divide gives both halves plate membership and complete top cells', () => { + const zoneId = create(rectangle, true) + const plan = divideZone(useScene.getState().nodes, { + zoneId, + cut: [ + [3, 0], + [3, 4], + ], + mintId, + }) + expect(plan.conflicts).toBeUndefined() + useScene.getState().applyNodeChanges(structureChangeBatch(plan.changes)) + assertRoomTops(2) +}) + +test('createZone enclose produces a plate and complete top cells', () => { + create(concave, true) + assertRoomTops(1) +}) + +test('separator-only terrace produces a plate and complete top cells', () => { + create(concave, false) + assertRoomTops(1) +}) + +test('adjacent concave, divided and separator-only rooms retain complete plate tops together', () => { + create(concave, true) + const next = rectangle.map(([x, z]): [number, number] => [x + 6, z]) + const divided = create(next, true) + const division = divideZone(useScene.getState().nodes, { + zoneId: divided, + cut: [ + [9, 0], + [9, 4], + ], + mintId, + }) + expect(division.conflicts).toBeUndefined() + useScene.getState().applyNodeChanges(structureChangeBatch(division.changes)) + create( + rectangle.map(([x, z]): [number, number] => [x + 12, z]), + false, + ) + assertRoomTops(4) +}) diff --git a/packages/core/src/store/use-scene-room-invariants.test.ts b/packages/core/src/store/use-scene-room-invariants.test.ts new file mode 100644 index 0000000000..fdedffaf6c --- /dev/null +++ b/packages/core/src/store/use-scene-room-invariants.test.ts @@ -0,0 +1,725 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { + initSpaceDetectionSync, + pauseSpaceDetection, + resumeSpaceDetection, + type Space, +} from '../lib/space-detection' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + CeilingNode, + ItemNode, + LevelNode, + SeparatorNode, + SlabNode, + StairNode, + WallNode, + type ZoneNode, +} from '../schema' +import { type SceneCommit, subscribeSceneCommits } from './history-control' +import useScene, { + applySceneOperationPatch, + clearSceneHistory, + type SceneOperationPatch, +} from './use-scene' + +const levelId = 'level_room_invariants' +const buildingId = 'building_room_invariants' +const polygon: Array<[number, number]> = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +let previousState: ReturnType +let stopDetection = () => {} +let stopCommits = () => {} + +beforeEach(() => { + previousState = useScene.getState() + globalThis.requestAnimationFrame = (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame = () => {} +}) + +afterEach(() => { + stopCommits() + stopDetection() + useScene.setState(previousState, true) + clearSceneHistory() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf +}) + +function startDetection() { + const editor = { + spaces: {} as Record, + setSpaces(spaces: Record) { + this.spaces = spaces + }, + } + stopDetection = initSpaceDetectionSync(useScene, { getState: () => editor }) + return editor +} + +function openRoom() { + const walls = polygon.map((start, index) => + WallNode.parse({ + id: `wall_room_invariants_${index}`, + parentId: levelId, + start, + end: polygon[(index + 1) % 4], + thickness: 0.2, + }), + ) + const initial = [ + BuildingNode.parse({ id: buildingId, children: [levelId] }), + LevelNode.parse({ + id: levelId, + parentId: buildingId, + level: 0, + height: 2.5, + children: walls.slice(0, 3).map((wall) => wall.id), + }), + ...walls.slice(0, 3), + ] + useScene.setState({ + nodes: Object.fromEntries(initial.map((node) => [node.id, node])), + rootNodeIds: [buildingId], + dirtyNodes: new Set(), + collections: {}, + materials: {}, + installedPlugins: [], + readOnly: false, + }) + clearSceneHistory() + startDetection() + return walls +} + +function surfaces() { + return Object.values(useScene.getState().nodes).filter( + (node): node is SlabNode | CeilingNode => node.type === 'slab' || node.type === 'ceiling', + ) +} + +function rooms() { + return Object.values(useScene.getState().nodes).filter( + (node): node is ZoneNode => node.type === 'zone', + ) +} + +function closeRoom() { + const walls = openRoom() + useScene.getState().createNode(walls[3]!, levelId) + expect(surfaces().filter((node) => node.type === 'slab')).toHaveLength(1) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(1) + return walls +} + +function moveRightWall(x: number) { + useScene.getState().updateNodes([ + { id: 'wall_room_invariants_0', data: { end: [x, 0] } }, + { id: 'wall_room_invariants_1', data: { start: [x, 0], end: [x, 4] } }, + { id: 'wall_room_invariants_2', data: { start: [x, 4] } }, + ]) +} + +test('I1/I2: closing a loop commits the complete graph once and undo/redo restores identical ids', () => { + const walls = openRoom() + const before = useScene.getState().nodes + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + useScene.getState().createNode(walls[3]!, levelId) + const after = useScene.getState().nodes + const generated = surfaces() + expect(generated.map((node) => node.type).sort()).toEqual(['ceiling', 'slab']) + expect(generated.every((node) => node.autoFromWalls)).toBe(true) + expect(commits).toHaveLength(1) + expect(commits[0]!.origin).toBe('local') + expect(commits[0]!.before.nodes).toEqual(before) + expect(commits[0]!.current.nodes).toEqual(after) + expect([...(after[levelId] as LevelNode).children].sort()).toEqual( + [...walls, ...generated, ...rooms()].map((node) => node.id).sort(), + ) + for (const wall of walls) { + expect(after[wall.id]).toMatchObject({ frontSide: 'interior', backSide: 'exterior' }) + } + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + expect(useScene.temporal.getState().futureStates).toHaveLength(1) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) +}) + +function closingPatch(commit: SceneCommit): SceneOperationPatch { + const children = (commit.current.nodes[levelId] as LevelNode).children + return { + materialChanges: [], + nodeDeletes: [], + nodeCreates: Object.values(commit.current.nodes) + .filter((node) => !commit.before.nodes[node.id]) + .map((node) => ({ node, position: children.indexOf(node.id) })), + nodeUpdates: Object.values(commit.current.nodes).flatMap((node) => { + const before = commit.before.nodes[node.id] + if (!before) return [] + const data: Record = {} + for (const [key, value] of Object.entries(node)) { + // Structural creates carry child positions; the host patch owns parent link updates. + if ( + key !== 'children' && + JSON.stringify(value) !== JSON.stringify(before[key as keyof AnyNode]) + ) + data[key] = value + } + return Object.keys(data).length + ? [{ id: node.id, data: data as Partial, removeFields: [] }] + : [] + }), + } +} + +test('I3: a read-only receiver applies the closing commit with originator ids and no local history', () => { + const walls = openRoom() + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + useScene.getState().createNode(walls[3]!, levelId) + expect(commits).toHaveLength(1) + const commit = commits[0]! + const patch = closingPatch(commit) + expect(patch.nodeCreates.map(({ node }) => node.type).sort()).toEqual([ + 'ceiling', + 'slab', + 'wall', + 'zone', + ]) + stopCommits() + stopDetection() + // useScene is a singleton: reset it to the peer's pre-edit graph, as in use-scene-commits.test.ts. + useScene.setState({ + ...structuredClone(commit.before), + dirtyNodes: new Set(), + readOnly: true, + }) + clearSceneHistory() + const editor = startDetection() + const received: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((next) => received.push(next)) + expect(applySceneOperationPatch(patch)).toBe(true) + expect(useScene.getState().nodes).toEqual(commit.current.nodes) + expect(useScene.getState().rootNodeIds).toEqual(commit.current.rootNodeIds) + expect(useScene.getState().readOnly).toBe(true) + expect(Object.values(editor.spaces)).toHaveLength(1) + expect( + surfaces() + .map((node) => node.type) + .sort(), + ).toEqual(['ceiling', 'slab']) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + expect(useScene.temporal.getState().futureStates).toHaveLength(0) + expect(useScene.temporal.getState().isTracking).toBe(true) + expect(received.map((next) => next.origin)).toEqual(['host']) +}) + +test.each([0.3, 3])('I4: moving a room wall by %s m preserves both surface ids', (distance) => { + closeRoom() + const original = surfaces() + moveRightWall(8 + distance) + expect( + surfaces() + .map((node) => node.id) + .sort(), + ).toEqual(original.map((node) => node.id).sort()) + for (const surface of surfaces()) { + expect(surface.autoFromWalls).toBe(true) + expect(Math.max(...surface.polygon.map(([x]) => x))).toBeCloseTo( + 8 + distance + (surface.type === 'ceiling' ? -0.1 : 0.1), + ) + } +}) + +test('I4/I9: split preserves larger-side ids and redistributes ceiling children; merge unions them', () => { + closeRoom() + const original = surfaces() + const ceiling = original.find((node): node is CeilingNode => node.type === 'ceiling')! + const children = [1, 6].map((x, index) => + ItemNode.parse({ + id: `item_room_light_${index}`, + parentId: ceiling.id, + position: [x, 0, 2], + asset: { + id: 'room_light', + name: 'Room light', + category: 'lighting', + thumbnail: '', + src: '/room-light.glb', + attachTo: 'ceiling', + }, + }), + ) + useScene.getState().createNodes(children.map((node) => ({ node, parentId: ceiling.id }))) + expect([...(useScene.getState().nodes[ceiling.id] as CeilingNode).children].sort()).toEqual( + children.map((node) => node.id).sort(), + ) + const divider = WallNode.parse({ + id: 'wall_room_partition', + parentId: levelId, + start: [2, 0], + end: [2, 4], + }) + useScene.getState().createNode(divider, levelId) + const split = surfaces() + expect(split).toHaveLength(3) + for (const source of original) { + const retained = useScene.getState().nodes[source.id] as SlabNode | CeilingNode + if (source.type === 'slab') { + expect(retained.polygon).toEqual(source.polygon) + expect((retained as SlabNode).zoneIds).toHaveLength(2) + continue + } + expect(Math.min(...retained.polygon.map(([x]) => x))).toBe(2.05) + expect(Math.max(...retained.polygon.map(([x]) => x))).toBe(7.9) + const created = split.filter((node) => node.type === source.type && node.id !== source.id) + expect(created).toHaveLength(1) + expect(Math.min(...created[0]!.polygon.map(([x]) => x))).toBe(0.1) + expect(Math.max(...created[0]!.polygon.map(([x]) => x))).toBe(1.95) + } + const leftCeiling = split.find( + (node): node is CeilingNode => node.type === 'ceiling' && node.id !== ceiling.id, + )! + const rightCeiling = useScene.getState().nodes[ceiling.id] as CeilingNode + expect(leftCeiling.children).toEqual([children[0]!.id]) + expect(rightCeiling.children).toEqual([children[1]!.id]) + expect(useScene.getState().nodes[children[0]!.id]).toMatchObject({ + parentId: leftCeiling.id, + position: [1, 0, 2], + }) + expect(useScene.getState().nodes[children[1]!.id]).toMatchObject({ + parentId: rightCeiling.id, + position: [6, 0, 2], + }) + useScene.getState().deleteNode(divider.id) + expect( + surfaces() + .map((node) => node.type) + .sort(), + ).toEqual(['ceiling', 'slab']) + for (const merged of surfaces()) { + expect(split.some((node) => node.id === merged.id)).toBe(true) + expect(merged.autoFromWalls).toBe(true) + expect(Math.min(...merged.polygon.map(([x]) => x))).toBe(merged.type === 'ceiling' ? 0.1 : -0.1) + expect(Math.max(...merged.polygon.map(([x]) => x))).toBe(merged.type === 'ceiling' ? 7.9 : 8.1) + } + const mergedCeiling = surfaces().find((node): node is CeilingNode => node.type === 'ceiling')! + expect([...mergedCeiling.children].sort()).toEqual(children.map((node) => node.id).sort()) + for (const child of children) { + expect(useScene.getState().nodes[child.id]).toMatchObject({ + parentId: mergedCeiling.id, + position: child.position, + }) + } +}) + +test.each([ + false, + true, +])('I5: deleting a manual cover restores the connected plate (partition=%s)', (partition) => { + closeRoom() + if (partition) { + useScene + .getState() + .createNode( + WallNode.parse({ id: 'wall_room_partition', start: [2, 0], end: [2, 4] }), + levelId, + ) + } + expect(surfaces().filter((node) => node.type === 'slab')).toHaveLength(1) + const manual = SlabNode.parse({ id: 'slab_room_manual', polygon, autoFromWalls: false }) + useScene.getState().createNode(manual, levelId) + expect( + surfaces() + .filter((node) => node.type === 'slab' && node.plateRole !== 'base') + .map((node) => node.id), + ).toEqual([manual.id]) + useScene.getState().deleteNode(manual.id) + expect(surfaces().filter((node) => node.type === 'slab')).toHaveLength(1) + moveRightWall(8.3) + expect(surfaces().filter((node) => node.type === 'slab')).toHaveLength(1) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(partition ? 2 : 1) +}) + +test('I6: a polygon-only store edit is ignored; explicit tool demotion protects later edits', () => { + closeRoom() + const slab = surfaces().find((node): node is SlabNode => node.type === 'slab')! + const edited: Array<[number, number]> = [ + [0, 0], + [8.1, 0], + [8.1, 4], + [0, 4], + ] + // Boundary tools own demotion; `updateNode` ignores a polygon patch on + // derived construction, so the sanctioned command is `detachDerivedNode`. + useScene.getState().updateNode(slab.id, { polygon: edited }) + expect(useScene.getState().nodes[slab.id]).toBe(slab) + expect((useScene.getState().nodes[slab.id] as SlabNode).autoFromWalls).toBe(true) + moveRightWall(8.3) + expect( + Math.max(...(useScene.getState().nodes[slab.id] as SlabNode).polygon.map(([x]) => x)), + ).toBeCloseTo(8.4) + useScene.getState().detachDerivedNode(slab.id, { polygon: edited }) + expect(useScene.getState().nodes[slab.id]).toMatchObject({ + polygon: edited, + autoFromWalls: false, + }) + moveRightWall(8.6) + expect(useScene.getState().nodes[slab.id]).toMatchObject({ + polygon: edited, + autoFromWalls: false, + }) +}) + +test('I6: 3D boundary patches detach both surfaces and protect manual ceiling geometry', () => { + closeRoom() + const slab = surfaces().find((node): node is SlabNode => node.type === 'slab')! + const ceiling = surfaces().find((node): node is CeilingNode => node.type === 'ceiling')! + expect(slab.autoFromWalls).toBe(true) + expect(ceiling.autoFromWalls).toBe(true) + const newPolygon: Array<[number, number]> = [ + [0, 0], + [8.1, 0], + [8.1, 4], + [0, 4], + ] + // Exact onPolygonChange commits from slab/boundary-editor.tsx and ceiling/boundary-editor.tsx. + useScene.getState().detachDerivedNode(slab.id, { polygon: newPolygon }) + useScene.getState().detachDerivedNode(ceiling.id, { polygon: newPolygon }) + expect(useScene.getState().nodes[slab.id]).toMatchObject({ + polygon: newPolygon, + autoFromWalls: false, + }) + expect(useScene.getState().nodes[ceiling.id]).toMatchObject({ + polygon: newPolygon, + autoFromWalls: false, + }) + moveRightWall(8.3) + expect(useScene.getState().nodes[slab.id]).toMatchObject({ + polygon: newPolygon, + autoFromWalls: false, + }) + const movedCeiling = useScene.getState().nodes[ceiling.id] as CeilingNode + expect(movedCeiling.autoFromWalls).toBe(false) + expect(Math.max(...movedCeiling.polygon.map(([x]) => x))).toBeCloseTo(8.1) +}) + +test('I6: floorplan boundary commits demote both generated surfaces and preserve their edited polygons', () => { + closeRoom() + const generated = surfaces() + expect(generated.every((node) => node.autoFromWalls)).toBe(true) + clearSceneHistory() + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + const newPolygon: Array<[number, number]> = [ + [0, 0], + [8.1, 0], + [8.1, 4], + [0, 4], + ] + for (const surface of generated) { + // `commitRingPatch` in polygon-vertex-affordance.ts routes a boundary + // reshape through `detachDerivedNode`. + useScene.getState().detachDerivedNode(surface.id, { polygon: newPolygon }) + expect(useScene.getState().nodes[surface.id]).toMatchObject({ + polygon: newPolygon, + autoFromWalls: false, + }) + } + expect(commits).toHaveLength(2) + expect(useScene.temporal.getState().pastStates).toHaveLength(2) + generated.forEach((surface, index) => { + expect(commits[index]!.origin).toBe('local') + expect(commits[index]!.before.nodes[surface.id]).toMatchObject({ autoFromWalls: true }) + expect(commits[index]!.current.nodes[surface.id]).toMatchObject({ + polygon: newPolygon, + autoFromWalls: false, + }) + }) + moveRightWall(8.3) + expect( + surfaces() + .map((node) => node.id) + .sort(), + ).toEqual(expect.arrayContaining(generated.map((node) => node.id).sort())) + for (const surface of generated) { + expect(useScene.getState().nodes[surface.id]).toMatchObject({ + polygon: newPolygon, + autoFromWalls: false, + }) + } +}) + +test('I7: exterior wall deletion preserves enclosure, intent, plate and ceiling', () => { + const walls = closeRoom() + const original = surfaces() + const zone = rooms()[0]! + useScene.getState().updateNode(zone.id, { name: 'Kitchen', floor: { finish: 'oak' } }) + useScene.getState().deleteNode(walls[3]!.id) + expect(surfaces()).toHaveLength(2) + expect(useScene.getState().nodes[zone.id]).toMatchObject({ + enclosureStatus: 'enclosed', + name: 'Kitchen', + floor: { finish: 'oak' }, + }) + for (const surface of original) { + expect(useScene.getState().nodes[surface.id]).toBeDefined() + expect((useScene.getState().nodes[levelId] as LevelNode).children).toContain(surface.id) + } +}) + +test('wall move retains persistent room id in one commit and undo restores it', () => { + closeRoom() + const before = useScene.getState().nodes + const zone = rooms()[0]! + clearSceneHistory() + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + moveRightWall(9) + expect(rooms().map((room) => room.id)).toEqual([zone.id]) + expect(rooms()[0]!.polygon).toContainEqual([9, 0]) + expect(commits).toHaveLength(1) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) +}) + +test('resume reconciles changes made while paused, including nested pauses', () => { + const walls = openRoom() + const before = useScene.getState().nodes + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + pauseSpaceDetection() + pauseSpaceDetection() + try { + useScene.getState().createNode(walls[3]!, levelId) + expect(rooms()).toHaveLength(0) + resumeSpaceDetection() + expect(rooms()).toHaveLength(0) + resumeSpaceDetection() + expect(rooms()).toHaveLength(1) + expect(surfaces()).toHaveLength(2) + expect(commits.at(-1)!.current.nodes).toEqual(useScene.getState().nodes) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + } finally { + resumeSpaceDetection() + resumeSpaceDetection() + } +}) + +test('zone ceiling opt-out triggers reconciliation; a derived polygon edit is re-derived, a name is kept', () => { + closeRoom() + const zone = rooms()[0]! + useScene.getState().updateNode(zone.id, { hasCeiling: false }) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(0) + moveRightWall(9) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(0) + const polygon = [ + [20, 20], + [24, 20], + [24, 24], + [20, 24], + ] as [number, number][] + const derived = (useScene.getState().nodes[zone.id] as ZoneNode).polygon + useScene.getState().updateNode(zone.id, { polygon, name: 'Changed' }) + // Hosted reconciliation re-derives the room outline from its walls; the client agrees. + expect(useScene.getState().nodes[zone.id]).toMatchObject({ polygon: derived, name: 'Changed' }) +}) + +test('separator edits and zone deletion reconcile without generating per-separator slabs', () => { + closeRoom() + const separator = SeparatorNode.parse({ + id: 'separator_intent', + parentId: levelId, + start: [2, 0], + end: [2, 4], + }) + useScene.getState().createNode(separator, levelId) + expect(rooms()).toHaveLength(2) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(2) + expect(surfaces().filter((node) => node.type === 'slab')).toHaveLength(1) + const room = rooms()[0]! + useScene.getState().deleteNode(room.id) + expect(rooms()).toHaveLength(2) + expect(rooms().some((zone) => zone.id === room.id)).toBe(false) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(2) + useScene.getState().deleteNode(separator.id) + expect(rooms()).toHaveLength(1) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(1) +}) + +test.each([ + false, + true, +])('host patches never derive, including an external temporal pause (%s)', (paused) => { + const walls = openRoom() + if (paused) useScene.temporal.getState().pause() + try { + expect( + applySceneOperationPatch({ + materialChanges: [], + nodeCreates: [{ node: walls[3]!, position: 3 }], + nodeUpdates: [], + nodeDeletes: [], + }), + ).toBe(true) + expect(rooms()).toHaveLength(0) + expect(surfaces()).toHaveLength(0) + expect(useScene.temporal.getState().pastStates).toHaveLength(0) + expect(useScene.temporal.getState().isTracking).toBe(!paused) + } finally { + useScene.temporal.getState().resume() + } +}) + +test.each([ + false, + true, +])('explicit ceiling deletion persists zone opt-out in one undo step (paused=%s)', (paused) => { + closeRoom() + const before = useScene.getState().nodes + const zone = rooms()[0]! + const ceiling = surfaces().find((node) => node.type === 'ceiling')! + clearSceneHistory() + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + if (paused) pauseSpaceDetection() + try { + useScene.getState().deleteNode(ceiling.id) + } finally { + if (paused) resumeSpaceDetection() + } + expect(rooms()[0]).toMatchObject({ id: zone.id, hasCeiling: false }) + expect(surfaces().filter((node) => node.type === 'ceiling')).toEqual([]) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + expect(commits.at(-1)!.current.nodes[zone.id]).toMatchObject({ hasCeiling: false }) + if (!paused) expect(commits).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + moveRightWall(9) + expect(surfaces().filter((node) => node.type === 'ceiling')).toEqual([]) + useScene.getState().updateNode(zone.id, { hasCeiling: true }) + expect(surfaces().filter((node) => node.type === 'ceiling')).toHaveLength(1) +}) + +test('a pre-existing manual ceiling prevents automatic ceiling creation on close', () => { + const walls = openRoom() + const manual = CeilingNode.parse({ id: 'ceiling_existing', polygon, height: 2.1 }) + useScene.getState().createNode(manual, levelId) + useScene.getState().createNode(walls[3]!, levelId) + expect( + surfaces() + .filter((node) => node.type === 'ceiling') + .map((node) => node.id), + ).toEqual([manual.id]) + moveRightWall(8.3) + expect( + surfaces() + .filter((node) => node.type === 'ceiling') + .map((node) => node.id), + ).toEqual([manual.id]) +}) + +test('a covering slab edit reclamps a manual ceiling in the same commit and undo step', () => { + closeRoom() + const ceiling = surfaces().find((node) => node.type === 'ceiling')! + useScene.getState().detachDerivedNode(ceiling.id, { height: 2.4 }) + const above = LevelNode.parse({ id: 'level_above', parentId: buildingId, level: 1 }) + useScene.getState().createNode(above, buildingId) + const slab = SlabNode.parse({ + id: 'slab_above', + parentId: above.id, + polygon, + elevation: 0, + thickness: 0.1, + }) + useScene.getState().createNode(slab, above.id) + const before = useScene.getState().nodes + clearSceneHistory() + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + useScene.getState().updateNode(slab.id, { thickness: 0.5 }) + expect(useScene.getState().nodes[ceiling.id]).toMatchObject({ height: 1.99 }) + expect(commits).toHaveLength(1) + expect(commits[0]!.current.nodes[ceiling.id]).toMatchObject({ height: 1.99 }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) +}) + +test('raising a room keeps its base id and wall hosts in one commit and undo step', () => { + const walls = closeRoom() + const zone = rooms()[0]! + const previousPlate = surfaces().find((node): node is SlabNode => node.type === 'slab')! + const stair = StairNode.parse({ id: 'stair_plate_host', deckSlabId: previousPlate.id }) + useScene.getState().createNode(stair, levelId) + useScene.getState().updateNode(walls[0]!.id, { supportSlabId: previousPlate.id }) + const before = useScene.getState().nodes + clearSceneHistory() + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + useScene.getState().updateNode(zone.id, { floor: { elevation: 0.4 } }) + const after = useScene.getState().nodes + const plate = surfaces().find((node): node is SlabNode => node.type === 'slab')! + expect(plate.id).toBe(previousPlate.id) + expect(plate.elevation).toBe(0.05) + const platform = surfaces().find( + (node): node is SlabNode => node.type === 'slab' && node.plateRole === 'platform', + )! + expect(platform.elevation).toBe(0.4) + expect(platform.thickness).toBeCloseTo(0.35) + expect(after[walls[0]!.id]).toMatchObject({ supportSlabId: plate.id }) + expect(after[stair.id]).toMatchObject({ deckSlabId: plate.id }) + expect(commits).toHaveLength(1) + expect(commits[0]!.current.nodes).toEqual(after) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) +}) + +test('zone floor intent creates platforms in one commit while retaining the base', () => { + closeRoom() + const plate = surfaces().find((node): node is SlabNode => node.type === 'slab')! + const zone = rooms()[0]! + for (const elevation of [0.4, 0.6]) { + const before = useScene.getState().nodes + clearSceneHistory() + const commits: SceneCommit[] = [] + stopCommits = subscribeSceneCommits((commit) => commits.push(commit)) + useScene.getState().updateNode(zone.id, { floor: { elevation } }) + expect(useScene.getState().nodes[plate.id]).toMatchObject({ elevation: 0.05 }) + expect( + surfaces().find((node) => node.type === 'slab' && node.plateRole === 'platform'), + ).toMatchObject({ elevation }) + expect(useScene.getState().nodes[zone.id]).toMatchObject({ floor: { elevation } }) + expect(commits).toHaveLength(1) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + stopCommits() + } + moveRightWall(9) + expect(useScene.getState().nodes[plate.id]).toMatchObject({ elevation: 0.05 }) +}) diff --git a/packages/core/src/store/use-scene-room-migration.test.ts b/packages/core/src/store/use-scene-room-migration.test.ts new file mode 100644 index 0000000000..837bd2d1c4 --- /dev/null +++ b/packages/core/src/store/use-scene-room-migration.test.ts @@ -0,0 +1,213 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { area, type Ring } from '../lib/polygon-boolean' +import { initSpaceDetectionSync, type Space } from '../lib/space-detection' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + CeilingNode, + LevelNode, + SeparatorNode, + SlabNode, + WallNode, + type ZoneNode, +} from '../schema' +import useScene, { clearSceneHistory } from './use-scene' + +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +let previousState: ReturnType +let stopDetection = () => {} + +beforeEach(() => { + previousState = useScene.getState() + globalThis.requestAnimationFrame = (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame = () => {} + useScene.setState({ readOnly: false }) + clearSceneHistory() +}) +afterEach(() => { + stopDetection() + useScene.setState(previousState, true) + clearSceneHistory() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf +}) + +const polygon: Ring = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], +] +function loadRoom(extra: AnyNode[] = []) { + const walls = polygon.map((start, i) => + WallNode.parse({ + id: `wall_outer_${i}`, + parentId: 'level_room', + start, + end: polygon[(i + 1) % 4], + height: 2.5, + }), + ) + const zone = { + id: 'zone_adopted', + type: 'zone', + parentId: 'level_room', + name: 'Kitchen', + polygon, + } as ZoneNode + const ceiling = CeilingNode.parse({ + id: 'ceiling_room', + parentId: 'level_room', + polygon, + height: 2.5, + autoFromWalls: true, + }) + const children = [...walls, zone, ceiling, ...extra] + const level = LevelNode.parse({ + id: 'level_room', + parentId: 'building_room', + children: children.map((node) => node.id), + }) + const building = BuildingNode.parse({ id: 'building_room', children: [level.id] }) + const source = Object.fromEntries( + [building, level, ...children].map((node) => [node.id, node]), + ) as Record + useScene.getState().setScene(source, [building.id]) + clearSceneHistory() + const editor = { + spaces: {} as Record, + setSpaces(spaces: Record) { + this.spaces = spaces + }, + } + stopDetection = initSpaceDetectionSync(useScene, { getState: () => editor }) +} +function moveEastWall() { + useScene.getState().updateNodes([ + { id: 'wall_outer_0', data: { end: [10, 0] } }, + { id: 'wall_outer_1', data: { start: [10, 0], end: [10, 4] } }, + { id: 'wall_outer_2', data: { start: [10, 4] } }, + ]) +} +function rooms() { + return Object.values(useScene.getState().nodes).filter( + (node): node is ZoneNode => node.type === 'zone' && node.spaceRole === 'room', + ) +} + +test('load runs vertical → M3 → M6 → M4/M5, and a wall move refits the adopted zone in one undo step', () => { + loadRoom() + const before = useScene.getState().nodes + expect(before.level_room).toMatchObject({ height: 2.5 }) + expect(before.zone_adopted).toMatchObject({ + spaceRole: 'room', + autoFromWalls: true, + seed: [4, 2], + boundarySeparatorIds: [], + holes: [], + }) + expect(before.ceiling_room).toMatchObject({ + zoneId: 'zone_adopted', + boundary: 'auto', + autoFromWalls: true, + }) + expect(Object.hasOwn(before.ceiling_room!, 'height')).toBe(false) + moveEastWall() + expect(rooms()).toHaveLength(1) + expect(rooms()[0]).toMatchObject({ + id: 'zone_adopted', + seed: [4, 2], + polygon: [ + [0, 0], + [10, 0], + [10, 4], + [0, 4], + ], + }) + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + useScene.temporal.getState().undo() + expect(rooms()[0]!.polygon).toEqual(polygon) + expect(rooms()[0]!.id).toBe('zone_adopted') +}) + +test('wall moves refit migrated nested rooms without dropping their holes or ids', () => { + const inner: Ring = [ + [2, 1], + [4, 1], + [4, 3], + [2, 3], + ] + loadRoom([ + SlabNode.parse({ parentId: 'level_room', polygon, autoFromWalls: true }), + SlabNode.parse({ parentId: 'level_room', polygon: inner, autoFromWalls: true }), + CeilingNode.parse({ parentId: 'level_room', polygon: inner, autoFromWalls: true }), + ...inner.map((start, i) => + WallNode.parse({ + id: `wall_inner_${i}`, + parentId: 'level_room', + start, + end: inner[(i + 1) % 4], + }), + ), + ]) + const manualCeilings = Object.values(useScene.getState().nodes).filter( + (node): node is CeilingNode => node.type === 'ceiling' && node.boundary !== 'auto', + ) + expect(manualCeilings).toHaveLength(1) + const ceilingIds = Object.values(useScene.getState().nodes) + .filter((node) => node.type === 'ceiling') + .map((node) => node.id) + .sort() + const before = rooms() + expect(before).toHaveLength(2) + const outer = before.find((room) => room.holes.length === 1)! + moveEastWall() + const after = rooms().find((room) => room.id === outer.id)! + expect(after.holes).toEqual(outer.holes) + expect(area([{ outer: after.polygon, holes: after.holes }])).toBe(36) + expect(rooms().map((room) => room.id)).toEqual(before.map((room) => room.id)) + const slabs = Object.values(useScene.getState().nodes).filter( + (node): node is SlabNode => node.type === 'slab', + ) + expect(slabs).toHaveLength(1) + expect(slabs[0]!.holeMetadata).toEqual([]) + expect(slabs[0]!.zoneIds).toEqual( + rooms() + .map((room) => room.id) + .sort(), + ) + expect(area([{ outer: slabs[0]!.polygon, holes: slabs[0]!.holes }])).toBeCloseTo(10.1 * 4.1) + const ceilings = Object.values(useScene.getState().nodes).filter( + (node): node is CeilingNode => node.type === 'ceiling', + ) + expect(ceilings.map((ceiling) => ceiling.id).sort()).toEqual(ceilingIds) + for (const ceiling of manualCeilings) + expect(useScene.getState().nodes[ceiling.id]).toMatchObject({ + polygon: ceiling.polygon, + holes: ceiling.holes, + }) +}) + +test('wall moves refit migrated separator-bounded rooms without changing their ids', () => { + loadRoom([ + SeparatorNode.parse({ + id: 'separator_split', + parentId: 'level_room', + start: [4, 0], + end: [4, 4], + }), + ]) + const before = rooms() + expect(before).toHaveLength(2) + const right = before.find((room) => room.seed![0] > 4)! + moveEastWall() + const after = rooms().find((room) => room.id === right.id)! + expect(after.boundarySeparatorIds).toEqual(['separator_split']) + expect(area([{ outer: after.polygon, holes: after.holes }])).toBe(24) + expect(rooms().map((room) => room.id)).toEqual(before.map((room) => room.id)) +}) diff --git a/packages/core/src/store/use-scene-temporal-reconciliation.test.ts b/packages/core/src/store/use-scene-temporal-reconciliation.test.ts index 27a66bb282..c0f7efa0e3 100644 --- a/packages/core/src/store/use-scene-temporal-reconciliation.test.ts +++ b/packages/core/src/store/use-scene-temporal-reconciliation.test.ts @@ -9,6 +9,7 @@ import { SlabNode, WallNode, } from '../schema' +import { migrateCeilingRoomLinks, migrateRoomZones } from '../utils/room-zone-migration' import fixture from './fixtures/maxi-8x-endpoint.json' import { runAsSingleSceneHistoryStep } from './history-control' import useScene, { clearSceneHistory } from './use-scene' @@ -33,7 +34,11 @@ afterEach(() => { }) function watch(nodes: Record) { - useScene.setState({ nodes, rootNodeIds: [], readOnly: false }) + useScene.setState({ + nodes: migrateCeilingRoomLinks(migrateRoomZones(nodes).nodes).nodes as Nodes, + rootNodeIds: [], + readOnly: false, + }) clearSceneHistory() const events: SpaceTopologyReconcileEvent[] = [] const editor = { @@ -83,7 +88,7 @@ function forward() { ) } -test('Maxi 8× endpoint undo/redo matches full-level graph and preserves unrelated surface identities', () => { +test('Maxi 8× endpoint undo/redo restores the saved graph without reminting identities', () => { const initial = baseline() const indexed = watch(initial) forward() @@ -92,24 +97,16 @@ test('Maxi 8× endpoint undo/redo matches full-level graph and preserves unrelat indexed.events.length = 0 useScene.temporal.getState().undo() const undone = useScene.getState().nodes - expect(indexed.events).toHaveLength(1) - expect(indexed.events[0]?.strategy).toBe('indexed') + expect(indexed.events).toHaveLength(0) const remoteSlab = 'slab_02warzosdw17ko2n' as AnyNodeId expect(undone[remoteSlab]).toBe(target[remoteSlab]) const undoGraph = graph(undone) useScene.temporal.getState().redo() const redoGraph = graph(useScene.getState().nodes) - expect(indexed.events).toHaveLength(2) + expect(indexed.events).toHaveLength(0) + expect(undoGraph).toEqual(graph(target)) + expect(redoGraph).toEqual(graph(moved)) indexed.stop() - - const fullUndo = watch(moved) - useScene.setState({ nodes: target }) - expect(undoGraph).toEqual(graph(useScene.getState().nodes)) - fullUndo.stop() - const fullRedo = watch(undone) - useScene.setState({ nodes: moved }) - expect(redoGraph).toEqual(graph(useScene.getState().nodes)) - fullRedo.stop() // The 8× fixture takes 5–6 s on the shared CI runner, past bun's 5 s default. }, 30_000) @@ -145,12 +142,12 @@ function rooms() { parentId: level.id, polygon, autoFromWalls: true, + boundary: 'auto', }) const ceiling = CeilingNode.parse({ id: `ceiling_${label}`, parentId: level.id, polygon, - height: 2.49, autoFromWalls: true, }) for (const node of [...walls, slab, ceiling]) { @@ -168,16 +165,16 @@ function surfaces(nodes: Nodes) { ) } -function assertSurfaces(nodes: Nodes, rooms: number, height = 2.49) { +function assertSurfaces(nodes: Nodes, rooms: number) { const auto = surfaces(nodes) - expect(auto.filter((node) => node.type === 'slab')).toHaveLength(rooms) + expect(auto.filter((node) => node.type === 'slab')).toHaveLength(Math.min(rooms, 2)) expect(auto.filter((node) => node.type === 'ceiling')).toHaveLength(rooms) for (const node of auto) { expect((nodes[node.parentId!] as LevelNode).children.filter((id) => id === node.id)).toEqual([ node.id, ]) expect(node.polygon.length).toBeGreaterThanOrEqual(4) - if (node.type === 'ceiling') expect(node.height).toBeCloseTo(height) + if (node.type === 'ceiling') expect(node.height).toBeUndefined() else expect(node.elevation).toBeCloseTo(0.05) } } @@ -193,23 +190,8 @@ function jump(transitions: Transition[], direction: 'undo' | 'redo', steps = 1) return actual } -function assertFullLevelOracle(transitions: Transition[]) { - for (const { before, target, actual } of transitions) { - const full = watch(before) - useScene.setState({ nodes: target }) - const expected = useScene.getState().nodes - expect( - surfaces(actual) - .map((node) => node.id) - .sort(), - ).toEqual( - surfaces(expected) - .map((node) => node.id) - .sort(), - ) - expect(graph(actual)).toEqual(graph(expected)) - full.stop() - } +function assertRestoredSnapshots(transitions: Transition[]) { + for (const { target, actual } of transitions) expect(graph(actual)).toEqual(graph(target)) } test('closing-wall deletion, undo and redo retain the full-level surface outcome', () => { @@ -220,7 +202,7 @@ test('closing-wall deletion, undo and redo retain the full-level surface outcome useScene.getState().deleteNode('wall_left_3') const deleted = useScene.getState().nodes transitions.push({ before, target: deleted, actual: deleted }) - assertSurfaces(deleted, 1) + assertSurfaces(deleted, 2) expect((deleted[level.id] as LevelNode).children).not.toContain('wall_left_3') const restored = jump(transitions, 'undo') assertSurfaces(restored, 2) @@ -234,9 +216,9 @@ test('closing-wall deletion, undo and redo retain the full-level surface outcome .sort(), ) expect((restored[level.id] as LevelNode).children).toContain('wall_left_3') - assertSurfaces(jump(transitions, 'redo'), 1) + assertSurfaces(jump(transitions, 'redo'), 2) sync.stop() - assertFullLevelOracle(transitions) + assertRestoredSnapshots(transitions) }) test('split, move and merge history preserves surfaces through the complete cycle', () => { @@ -259,14 +241,12 @@ test('split, move and merge history preserves surfaces through the complete cycl sync.events.length = 0 const unmoved = jump(transitions, 'undo') assertSurfaces(unmoved, 3) - expect(sync.events).toHaveLength(1) - expect(sync.events[0]?.strategy).toBe('indexed') - expect(sync.events[0]?.examinedWallIds.every((id) => !id.startsWith('wall_right'))).toBe(true) + expect(sync.events).toHaveLength(0) expect((unmoved[divider.id] as WallNode).start).toEqual([2, 0]) assertSurfaces(jump(transitions, 'undo'), 2) for (const count of [3, 3, 2]) assertSurfaces(jump(transitions, 'redo'), count) sync.stop() - assertFullLevelOracle(transitions) + assertRestoredSnapshots(transitions) }) test('two-step temporal jumps reconcile two distinct components against the full-level oracle', () => { @@ -287,24 +267,21 @@ test('two-step temporal jumps reconcile two distinct components against the full sync.events.length = 0 const undone = jump(transitions, 'undo', 2) assertSurfaces(undone, 2) - expect(sync.events).toHaveLength(1) - expect(sync.events[0]?.affectedBeforeRoomCount).toBe(2) - expect(sync.events[0]?.affectedCurrentRoomCount).toBe(2) + expect(sync.events).toHaveLength(0) for (const label of ['left', 'right']) { - expect(sync.events[0]?.examinedWallIds).toContain(`wall_${label}_1`) expect(canonicalPolygon((undone[`slab_${label}`] as SlabNode).polygon)).toEqual( canonicalPolygon((nodes[`slab_${label}`] as SlabNode).polygon), ) } const redone = jump(transitions, 'redo', 2) assertSurfaces(redone, 2) - expect(sync.events).toHaveLength(2) + expect(sync.events).toHaveLength(0) expect(graph(redone)).toEqual(graph(moved)) sync.stop() - assertFullLevelOracle(transitions) + assertRestoredSnapshots(transitions) }) -test('level hierarchy changes reconcile derived ceiling heights on undo and redo', () => { +test('level hierarchy changes clamp explicit ceilings; undo and redo restore their saved heights', () => { const building = BuildingNode.parse({ id: 'building_heights', children: ['level_heights'] }) const level = LevelNode.parse({ id: 'level_heights', @@ -312,8 +289,6 @@ test('level hierarchy changes reconcile derived ceiling heights on undo and redo height: 2.5, children: ['ceiling_heights', 'wall_heights'], }) - // A stale explicit ceiling in a loaded snapshot makes skipping reconciliation - // observable: native restoration alone would bring its height back to 9. const ceiling = CeilingNode.parse({ id: 'ceiling_heights', parentId: level.id, @@ -340,13 +315,13 @@ test('level hierarchy changes reconcile derived ceiling heights on undo and redo const sync = watch(nodes) const transitions: Transition[] = [] useScene.setState({ nodes: { ...nodes, [level.id]: { ...level, height: 4 } } }) - expect((useScene.getState().nodes[ceiling.id] as CeilingNode).height).toBeCloseTo(3.99) + expect((useScene.getState().nodes[ceiling.id] as CeilingNode).height).toBe(3.99) expect(useScene.getState().nodes[wall.id]).toBe(wall) const undone = jump(transitions, 'undo') - expect((undone[ceiling.id] as CeilingNode).height).toBeCloseTo(2.49) + expect((undone[ceiling.id] as CeilingNode).height).toBe(9) expect((undone[level.id] as LevelNode).children).toEqual([ceiling.id, wall.id]) const redone = jump(transitions, 'redo') - expect((redone[ceiling.id] as CeilingNode).height).toBeCloseTo(3.99) + expect((redone[ceiling.id] as CeilingNode).height).toBe(3.99) sync.stop() - assertFullLevelOracle(transitions) + assertRestoredSnapshots(transitions) }) diff --git a/packages/core/src/store/use-scene-vertical-migration.test.ts b/packages/core/src/store/use-scene-vertical-migration.test.ts index 15d34bbfbc..e3493760f6 100644 --- a/packages/core/src/store/use-scene-vertical-migration.test.ts +++ b/packages/core/src/store/use-scene-vertical-migration.test.ts @@ -357,7 +357,7 @@ describe('scene vertical model migration', () => { const deck = nodes.slab_a as SlabResult expect(deck.elevation).toBe(-0.15) expect(deck.thickness).toBe(0.3) - expect('recessed' in deck).toBe(false) + expect(deck.recessed).toBe(false) }) test('migration is idempotent', () => { diff --git a/packages/core/src/store/use-scene-wall-slot-migration.test.ts b/packages/core/src/store/use-scene-wall-slot-migration.test.ts index 976d248e5b..0fafe8aee1 100644 --- a/packages/core/src/store/use-scene-wall-slot-migration.test.ts +++ b/packages/core/src/store/use-scene-wall-slot-migration.test.ts @@ -98,9 +98,10 @@ describe('wall surface-material → slots migration', () => { ) const wall = useScene.getState().nodes.wall_test as WallNode + // Then M1 re-keys the unclassified wall's sides onto faces a (front) and b (back). expect(wall.slots).toEqual({ - interior: 'library:concrete-plate', - exterior: 'library:wood-woodplank48', + a: 'library:concrete-plate', + b: 'library:wood-woodplank48', }) expect(wall.interiorMaterialPreset).toBeUndefined() expect(wall.exteriorMaterialPreset).toBeUndefined() @@ -115,7 +116,7 @@ describe('wall surface-material → slots migration', () => { ) const wall = useScene.getState().nodes.wall_test as WallNode - const interiorRef = wall.slots?.interior + const interiorRef = wall.slots?.a expect(interiorRef?.startsWith('scene:')).toBe(true) expect(wall.interiorMaterial).toBeUndefined() @@ -135,8 +136,8 @@ describe('wall surface-material → slots migration', () => { ) const wall = useScene.getState().nodes.wall_test as WallNode - expect(wall.slots?.interior).toBeDefined() - expect(wall.slots?.interior).toBe(wall.slots?.exterior as string) + expect(wall.slots?.a).toBeDefined() + expect(wall.slots?.a).toBe(wall.slots?.b as string) expect(wall.material).toBeUndefined() // One minted datablock shared across both faces. expect(Object.keys(useScene.getState().materials)).toHaveLength(1) @@ -150,7 +151,7 @@ describe('wall surface-material → slots migration', () => { ] as never) const migratedWall = useScene.getState().nodes.wall_test as WallNode - expect(migratedWall.slots).toEqual({ interior: 'library:concrete-drywall' }) + expect(migratedWall.slots).toEqual({ a: 'library:concrete-drywall' }) expect(Object.keys(useScene.getState().materials)).toHaveLength(0) useScene.getState().setScene(sceneWithWall({}), ['site_test'] as never) diff --git a/packages/core/src/store/use-scene.ts b/packages/core/src/store/use-scene.ts index 2977f1e6ee..a211a6227b 100644 --- a/packages/core/src/store/use-scene.ts +++ b/packages/core/src/store/use-scene.ts @@ -3,7 +3,7 @@ import type { TemporalState } from 'zundo' import { temporal } from 'zundo' import { create, type StateCreator, type StoreApi, type UseBoundStore } from 'zustand' -import { parseMaterialRef, toSceneMaterialRef } from '../material-library' +import { toSceneMaterialRef } from '../material-library' import { getNodePluginId, isNodeKindEnabled, nodeRegistry } from '../registry/registry' import { BuildingNode } from '../schema' import type { Collection, CollectionId } from '../schema/collections' @@ -30,30 +30,39 @@ import { StairNode as StairNodeSchema, } from '../schema/nodes/stair' import { StairSegmentNode as StairSegmentNodeSchema } from '../schema/nodes/stair-segment' -import { getEffectiveWallSurfaceMaterial, type WallSurfaceSide } from '../schema/nodes/wall' import { WindowNode as WindowNodeSchema } from '../schema/nodes/window' -import { - generateSceneMaterialId, - SceneMaterial, - type SceneMaterialId, -} from '../schema/scene-material' +import { SceneMaterial, type SceneMaterialId } from '../schema/scene-material' import { type AnyNode, type AnyNodeId, AnyNode as AnyNodeSchema } from '../schema/types' -import { syncAutoElevatorOpenings } from '../systems/elevator/elevator-opening-sync' -import { syncAutoStairOpenings } from '../systems/stair/stair-opening-sync' -import { syncStairRises } from '../systems/stair/stair-rise' +import { ensureSceneOpenings } from '../utils/ensure-scene-openings' +import { migrateFloorPlates, migrateSlabSlots } from '../utils/floor-plate-migration' import { healSceneNodes } from '../utils/heal-scene-graph' +import { + legacySpecToMaterialRef, + migrateSingleMaterialSlots, + migrateWallSurfaceMaterials, +} from '../utils/legacy-material-slots' +import { materializeNodeDefaults } from '../utils/node-defaults' +import { normalizeLegacyStructure } from '../utils/normalize-legacy-structure' +import { materializeLegacyAutoOpenings } from '../utils/owned-floor-opening-migration' +import { reconcileStructureOnLoad } from '../utils/reconcile-structure-on-load' import { removeRetiredDrawingSheetNodes } from '../utils/retired-scene-nodes' +import { migrateCeilingRoomLinks, migrateRoomZones } from '../utils/room-zone-migration' import { migrateVerticalSceneNodes } from '../utils/vertical-scene-migration' import { migrateLegacyWallAssemblies } from '../utils/wall-assembly-migration' +import { migrateWallFaceBands, migrateWallFaceKeys } from '../utils/wall-face-migration' import * as nodeActions from './actions/node-actions' +import type { DerivedWriteOptions } from './derived-node-guard' import { areSceneSnapshotsEqual, beginSceneHistoryPauseSession, getSceneHistoryPauseDepth, + isRestoringSceneHistory, notifySceneCommit, pauseSceneHistory, resetSceneHistoryPauseDepth, resumeSceneHistory, + runAsRemoteSceneChange, + runAsSceneHistoryRestore, runWithSceneCommitNodeIds, type SceneCommitOrigin, type SceneSnapshot, @@ -300,117 +309,6 @@ function migrateElevatorParent( } } -// Reuse an already-minted scene material for an identical inline legacy -// material so a whole building painted one custom colour collapses to one -// shared datablock (mirrors `commitSlotPaint`'s dedupe-on-match). -function findMintedSceneMaterialRef( - material: unknown, - mintedMaterials: Record, -): string | undefined { - const target = JSON.stringify(material) - for (const sceneMaterial of Object.values(mintedMaterials)) { - if (JSON.stringify(sceneMaterial.material) === target) { - return toSceneMaterialRef(sceneMaterial.id) - } - } - return undefined -} - -// Turn a legacy surface spec (`{ material, materialPreset }`) into a -// `MaterialRef`: a preset that's already a `library:`/`scene:` ref is used -// as-is; an inline material mints (or reuses) a scene material. Returns -// undefined when the spec carries no material. Shared by every legacy→slots -// migration below. -function legacySpecToMaterialRef( - spec: { material?: unknown; materialPreset?: unknown }, - mintedMaterials: Record, -): string | undefined { - if (typeof spec.materialPreset === 'string' && parseMaterialRef(spec.materialPreset)) { - return spec.materialPreset - } - if (spec.material !== undefined) { - const existing = findMintedSceneMaterialRef(spec.material, mintedMaterials) - if (existing) return existing - const id = generateSceneMaterialId() - mintedMaterials[id] = { - id, - name: `Material ${Object.keys(mintedMaterials).length + 1}`, - material: spec.material as SceneMaterial['material'], - } - return toSceneMaterialRef(id) - } - return undefined -} - -// Move the retired inline `material*` / `interiorMaterial*` / `exteriorMaterial*` -// fields onto the unified `node.slots` model (interior / exterior → a -// `library:`/`scene:` ref), minting scene materials for inline customs into -// `mintedMaterials` (merged into the scene material map by the caller). Already -// slot-modelled walls and walls with no legacy material are left untouched. -function migrateWallSurfaceMaterials( - node: Record, - mintedMaterials: Record, -) { - if (node.slots && (node.slots.interior !== undefined || node.slots.exterior !== undefined)) { - return node - } - - const slots: Record = { ...(node.slots ?? {}) } - for (const side of ['interior', 'exterior'] as WallSurfaceSide[]) { - const spec = getEffectiveWallSurfaceMaterial( - node as Parameters[0], - side, - ) - const ref = legacySpecToMaterialRef(spec, mintedMaterials) - if (ref) slots[side] = ref - } - - if (Object.keys(slots).length === 0) { - return node - } - - return { - ...node, - slots, - material: undefined, - materialPreset: undefined, - interiorMaterial: undefined, - interiorMaterialPreset: undefined, - exteriorMaterial: undefined, - exteriorMaterialPreset: undefined, - } -} - -// Move a kind's single legacy `material` / `materialPreset` onto its declared -// slots. A pre-slot-model node painted one material rendered that material on -// every part (each slot resolves `node.slots[slot]` → legacy → default), so the -// migration writes the same ref to every slot id the kind can expose — unused -// conditional slots are harmless. Already slot-modelled or unpainted nodes are -// left untouched. Mirrors `migrateWallSurfaceMaterials` for single-surface and -// whole-object kinds (slab, ceiling, fence, column, shelf). -function migrateSingleMaterialSlots( - node: Record, - slotIds: readonly string[], - mintedMaterials: Record, -) { - if (node.slots && Object.keys(node.slots).length > 0) { - return node - } - - const ref = legacySpecToMaterialRef( - { material: node.material, materialPreset: node.materialPreset }, - mintedMaterials, - ) - if (!ref) { - return node - } - - const slots: Record = {} - for (const slotId of slotIds) slots[slotId] = ref - - return { ...node, slots, material: undefined, materialPreset: undefined } -} - function migrateRoleMaterialSlots( node: Record, roles: readonly string[], @@ -663,22 +561,6 @@ function migrateConstructionDimension(node: Record) { } } -function migrateWallAssembly(node: Record) { - if (!Object.hasOwn(node, 'assemblyLayers')) return node - - const assemblyThickness = Array.isArray(node.assemblyLayers) - ? node.assemblyLayers.reduce((total: number, layer: unknown) => { - if (!(layer && typeof layer === 'object')) return total - const thickness = (layer as { thickness?: unknown }).thickness - return typeof thickness === 'number' && Number.isFinite(thickness) && thickness > 0 - ? total + thickness - : total - }, 0) - : 0 - const { assemblyLayers: _assemblyLayers, ...wall } = node - return assemblyThickness > 0 ? { ...wall, thickness: assemblyThickness } : wall -} - function migrateBlockRename( id: string, node: Record, @@ -729,7 +611,7 @@ function migrateNodes(nodes: Record): { } { // Repair pre-existing corruption (null children, zero-length walls) before // any per-type migration runs, so already-saved scenes load cleanly. - const { nodes: healed } = healSceneNodes(nodes) + const { nodes: healed } = healSceneNodes(normalizeLegacyStructure(nodes)) const { nodes: patchedNodes } = removeRetiredDrawingSheetNodes(healed as Record) // Scene materials minted while moving legacy wall fields onto `node.slots`; @@ -893,10 +775,7 @@ function migrateNodes(nodes: Record): { } if (node.type === 'wall') { - patchedNodes[id] = migrateWallSurfaceMaterials( - migrateWallAssembly(patchedNodes[id]), - mintedMaterials, - ) + patchedNodes[id] = migrateWallSurfaceMaterials(patchedNodes[id], mintedMaterials) } // Cabinet v2→v3: node-level `doorStyle` was dead (geometry reads only the @@ -1065,30 +944,6 @@ function migrateNodes(nodes: Record): { patchedNodes[id] = migrateRoofSurfaceMaterials(patchedNodes[id]) } - // Legacy: site.children used to hold nested BuildingNode / ItemNode - // objects (see the SiteNode schema before the children-as-ids fix). - // Flatten any leftover nested children into ids, and absorb the - // embedded nodes into the flat map so the rest of the loader can - // treat the site like every other parent. - if (node.type === 'site' && Array.isArray(node.children)) { - let needsFlatten = false - const flattened: string[] = [] - for (const child of node.children) { - if (typeof child === 'string') { - flattened.push(child) - } else if (child && typeof child === 'object' && typeof child.id === 'string') { - needsFlatten = true - flattened.push(child.id) - if (!patchedNodes[child.id]) { - patchedNodes[child.id] = { ...child, parentId: id } - } - } - } - if (needsFlatten) { - patchedNodes[id] = { ...node, children: flattened } - } - } - // Level children normalization. // Pre-0.9.1 JSONs may carry child IDs that no longer exist in the node // map (e.g. elevator IDs that lived under a level before the elevator @@ -1152,7 +1007,31 @@ function migrateNodes(nodes: Record): { const walls = migrateLegacyWallAssemblies(patchedNodes) const vertical = migrateVerticalSceneNodes(walls.nodes) - return { nodes: vertical.nodes as Record, mintedMaterials } + const rooms = migrateRoomZones(vertical.nodes) + const ceilings = migrateCeilingRoomLinks(rooms.nodes) + const legacyOpeningsPrepared = + Object.values(ceilings.nodes).some((value) => { + const node = value as AnyNode + return node.type === 'slab' && node.autoFromWalls && !node.plateRole + }) && + Object.values(ceilings.nodes).some((value) => { + const node = value as AnyNode + return node.type === 'stair' || node.type === 'elevator' + }) + const plates = migrateFloorPlates(materializeLegacyAutoOpenings(ceilings.nodes, true)) + const slots = migrateSlabSlots(plates.nodes) + const openings = ensureSceneOpenings(slots.nodes).nodes + // M1 before M2: bands move onto geometric faces, then become paint regions. + const wallFaces = migrateWallFaceKeys(openings) + const structure = reconcileStructureOnLoad( + migrateWallFaceBands(wallFaces.nodes).nodes, + vertical.nodes, + { legacyOpeningsPrepared }, + ) + return { + nodes: materializeNodeDefaults(structure.nodes).nodes as Record, + mintedMaterials, + } } function getNodeChildIds(node: AnyNode): AnyNodeId[] { @@ -1260,19 +1139,31 @@ export type SceneState = { markDirty: (id: AnyNodeId) => void clearDirty: (id: AnyNodeId) => void - createNode: (node: AnyNode, parentId?: AnyNodeId) => void - createNodes: (ops: { node: AnyNode; parentId?: AnyNodeId }[]) => void - applyNodeChanges: (changes: { - create?: { node: AnyNode; parentId?: AnyNodeId }[] - update?: { id: AnyNodeId; data: Partial }[] - delete?: AnyNodeId[] - }) => void + createNode: (node: AnyNode, parentId?: AnyNodeId, options?: DerivedWriteOptions) => void + createNodes: ( + ops: { node: AnyNode; parentId?: AnyNodeId }[], + options?: DerivedWriteOptions, + ) => void + applyNodeChanges: ( + changes: { + create?: { node: AnyNode; parentId?: AnyNodeId }[] + update?: { id: AnyNodeId; data: Partial }[] + delete?: AnyNodeId[] + }, + options?: DerivedWriteOptions, + ) => void + + updateNode: (id: AnyNodeId, data: Partial, options?: DerivedWriteOptions) => void + updateNodes: ( + updates: { id: AnyNodeId; data: Partial }[], + options?: DerivedWriteOptions, + ) => void - updateNode: (id: AnyNodeId, data: Partial) => void - updateNodes: (updates: { id: AnyNodeId; data: Partial }[]) => void + deleteNode: (id: AnyNodeId, options?: DerivedWriteOptions) => void + deleteNodes: (ids: AnyNodeId[], options?: DerivedWriteOptions) => void - deleteNode: (id: AnyNodeId) => void - deleteNodes: (ids: AnyNodeId[]) => void + /** Convert a reconciler-owned slab or ceiling into an authored one. */ + detachDerivedNode: (id: AnyNodeId, data?: Partial) => void // Collection actions createCollection: (name: string, nodeIds?: AnyNodeId[]) => CollectionId @@ -1463,7 +1354,7 @@ function createSceneStore(config: TemporalSceneCreator): UseSceneStore { return create()(hydratedConfig) } -function runTemporalJump(target: Partial | undefined, jump: () => void): void { +function runTemporalJump(target: Partial | undefined, restore: () => void): void { const draftsBefore = useScene.getState().nodes const restoreDrafts = () => { const nodes = withDraftsRestored(draftsBefore, useScene.getState().nodes) @@ -1476,7 +1367,7 @@ function runTemporalJump(target: Partial | undefined, jump: () => pause.end() } } - runTemporalJumpOnly(target, jump) + runTemporalJumpOnly(target, () => runAsSceneHistoryRestore(restore)) restoreDrafts() } @@ -1492,7 +1383,6 @@ function runTemporalJumpOnly(target: Partial | undefined, jump: ( const previous = before[nodeId] const next = target.nodes[nodeId] if (previous === next) continue - // Structural hierarchy changes keep the full-level reconciliation fallback. if ( [previous, next].some((node) => node && ['site', 'building', 'level'].includes(node.type)) ) { @@ -1559,9 +1449,9 @@ const useScene: UseSceneStore = createSceneStore( setScene: (nodes, rootNodeIds, extra) => { // Apply backward compatibility migrations const { nodes: patchedNodes, mintedMaterials } = migrateNodes(nodes) - // Scene materials minted by the wall legacy→slots migration join the - // loaded palette (existing refs win on id collision — there are none, - // ids are freshly generated). + // Scene materials minted by the legacy→slots migrations join the + // loaded palette. Their ids are content-derived, so an existing entry + // with the same id (the hosted authority minted it) is the same material. const materials = { ...mintedMaterials, ...(extra?.materials ?? {}) } // Remove orphans: nodes whose parentId points to a non-existent node @@ -1607,33 +1497,21 @@ const useScene: UseSceneStore = createSceneStore( installedPlugins: Array.from(new Set(extra?.installedPlugins ?? [])), hasExplicitPluginInstallState: extra?.hasExplicitPluginInstallState ?? false, }) - const applyNormalization = (updates: { id: AnyNodeId; data: Partial }[]) => { - if (updates.length > 0) get().updateNodes(updates) - } - const hydratedNodes = Object.values(get().nodes) - if (!get().readOnly) { - pauseSceneHistory(useScene) - try { - if (hydratedNodes.some((node) => node.type === 'elevator')) { - applyNormalization(syncAutoElevatorOpenings(get().nodes)) + if ( + !get().readOnly && + Object.values(get().nodes).some((node) => node.type === 'stair') + ) { + queueSceneNormalization(() => { + if (get().hydrationId !== hydrationId) return + const { updates } = ensureSceneOpenings(get().nodes) + if (!updates.length) return + pauseSceneHistory(useScene) + try { + get().updateNodes(updates) + } finally { + resumeSceneHistory(useScene) } - } finally { - resumeSceneHistory(useScene) - } - if (hydratedNodes.some((node) => node.type === 'stair')) { - // Spatial-grid subscribers must settle first. Owning this pass - // here also covers opening systems that mount after the load. - queueSceneNormalization(() => { - if (get().hydrationId !== hydrationId) return - pauseSceneHistory(useScene) - try { - applyNormalization(syncStairRises(get().nodes)) - applyNormalization(syncAutoStairOpenings(get().nodes)) - } finally { - resumeSceneHistory(useScene) - } - }) - } + }) } // Mark all nodes as dirty to trigger re-validation Object.values(get().nodes).forEach((node) => { @@ -1717,18 +1595,23 @@ const useScene: UseSceneStore = createSceneStore( get().dirtyNodes.delete(id) }, - createNodes: (ops) => nodeActions.createNodesAction(set, get, ops), - createNode: (node, parentId) => nodeActions.createNodesAction(set, get, [{ node, parentId }]), - applyNodeChanges: (changes) => nodeActions.applyNodeChangesAction(set, get, changes), + createNodes: (ops, options) => nodeActions.createNodesAction(set, get, ops, options), + createNode: (node, parentId, options) => + nodeActions.createNodesAction(set, get, [{ node, parentId }], options), + applyNodeChanges: (changes, options) => + nodeActions.applyNodeChangesAction(set, get, changes, options), - updateNodes: (updates) => nodeActions.updateNodesAction(set, get, updates), - updateNode: (id, data) => nodeActions.updateNodesAction(set, get, [{ id, data }]), + updateNodes: (updates, options) => nodeActions.updateNodesAction(set, get, updates, options), + updateNode: (id, data, options) => + nodeActions.updateNodesAction(set, get, [{ id, data }], options), + + detachDerivedNode: (id, data) => nodeActions.detachDerivedNodeAction(set, get, id, data), // --- DELETE --- - deleteNodes: (ids) => nodeActions.deleteNodesAction(set, get, ids), + deleteNodes: (ids, options) => nodeActions.deleteNodesAction(set, get, ids, options), - deleteNode: (id) => nodeActions.deleteNodesAction(set, get, [id]), + deleteNode: (id, options) => nodeActions.deleteNodesAction(set, get, [id], options), // --- COLLECTIONS --- @@ -1894,6 +1777,21 @@ useLiveNodeOverrides.subscribe(invalidateForLiveState) useLiveTransforms.subscribe(invalidateForLiveState) useScene.subscribe(invalidateForLiveState) +// Systems rebuild a node's geometry only when it is dirty, so a preview that +// drops its override without marking the node left it drawn at the preview +// (a cancelled wall move's floor still pushed out). Whoever clears an +// override, or one of its fields, the node rebuilds from the scene. +useLiveNodeOverrides.subscribe(function markClearedOverridesDirty(state, previous) { + if (state.overrides === previous.overrides) return + let scene: SceneState | null = null + for (const [id, before] of previous.overrides) { + const after = state.overrides.get(id) + if (after === before || (after && Object.keys(before).every((key) => key in after))) continue + scene ??= useScene.getState() + if (scene.nodes[id as AnyNodeId]) scene.markDirty(id as AnyNodeId) + } +}) + export default useScene let sceneReadOnlyLeaseCount = 0 @@ -1985,7 +1883,8 @@ function sceneOperationPatchHasLiveConflict( } function areScenePatchValuesEqual(left: unknown, right: unknown): boolean { - if (Object.is(left, right)) return true + // Compensation crosses JSON, which serializes both signed zeros as 0. + if (left === right) return true if (typeof left !== typeof right || left === null || right === null) return false if (Array.isArray(left) || Array.isArray(right)) { return ( @@ -1998,8 +1897,10 @@ function areScenePatchValuesEqual(left: unknown, right: unknown): boolean { if (typeof left !== 'object' || typeof right !== 'object') return false const leftRecord = left as Record const rightRecord = right as Record - const leftKeys = Object.keys(leftRecord) - if (leftKeys.length !== Object.keys(rightRecord).length) return false + // Recorded compensation nodes have crossed JSON, which omits undefined properties. + const leftKeys = Object.keys(leftRecord).filter((key) => leftRecord[key] !== undefined) + const rightKeys = Object.keys(rightRecord).filter((key) => rightRecord[key] !== undefined) + if (leftKeys.length !== rightKeys.length) return false return leftKeys.every( (key) => Object.hasOwn(rightRecord, key) && @@ -2105,10 +2006,6 @@ function sceneOperationPatchNextState( for (const id of createIds) { if (deleteIds.has(id)) return null } - for (const node of Object.values(beforeState.nodes)) { - const parentId = (node.parentId as AnyNodeId | null | undefined) ?? null - if (parentId && deleteIds.has(parentId) && !deleteIds.has(node.id)) return null - } const nextNodes = { ...beforeState.nodes } let nextRootNodeIds = @@ -2143,8 +2040,7 @@ function sceneOperationPatchNextState( if (!parent) return null if (createIds.has(parentId)) { if ( - !('children' in parent) || - !Array.isArray(parent.children) || + !('children' in parent && Array.isArray(parent.children)) || parent.children[change.position] !== change.node.id ) { return null @@ -2165,15 +2061,6 @@ function sceneOperationPatchNextState( if (!children) return null nextNodes[parentId] = { ...parent, children } as AnyNode } - for (const change of parsedCreates) { - const parentId = (change.node.parentId as AnyNodeId | null | undefined) ?? null - const siblings = structuralSiblingIds(nextNodes, nextRootNodeIds, parentId) - if (siblings?.[change.position] !== change.node.id) return null - if (!('children' in change.node && Array.isArray(change.node.children))) continue - for (const childId of change.node.children as AnyNodeId[]) { - if (nextNodes[childId]?.parentId !== change.node.id) return null - } - } for (const { id, data, removeFields } of changes.nodeUpdates) { const node = nextNodes[id] @@ -2207,6 +2094,38 @@ function sceneOperationPatchNextState( nextNodes[id] = candidate as AnyNode } + for (const id of updateIds) { + const previousParent = beforeState.nodes[id]?.parentId as AnyNodeId | null | undefined + const parentId = nextNodes[id]?.parentId as AnyNodeId | null | undefined + if (previousParent === parentId) continue + if (previousParent) { + const parent = nextNodes[previousParent] + if (parent && 'children' in parent && Array.isArray(parent.children)) + nextNodes[previousParent] = { + ...parent, + children: parent.children.filter((child) => child !== id), + } as AnyNode + } else nextRootNodeIds = nextRootNodeIds.filter((child) => child !== id) + if (parentId) { + const parent = nextNodes[parentId] + if (!(parent && 'children' in parent && Array.isArray(parent.children))) return null + if (!parent.children.includes(id as never)) + nextNodes[parentId] = { ...parent, children: [...parent.children, id] } as AnyNode + } else if (!nextRootNodeIds.includes(id)) nextRootNodeIds = [...nextRootNodeIds, id] + } + for (const node of Object.values(nextNodes)) { + if (node.parentId && deleteIds.has(node.parentId as AnyNodeId)) return null + } + for (const change of parsedCreates) { + const parentId = (change.node.parentId as AnyNodeId | null | undefined) ?? null + const siblings = structuralSiblingIds(nextNodes, nextRootNodeIds, parentId) + if (siblings?.[change.position] !== change.node.id) return null + if (!('children' in change.node && Array.isArray(change.node.children))) continue + for (const childId of change.node.children as AnyNodeId[]) { + if (nextNodes[childId]?.parentId !== change.node.id) return null + } + } + const materials = changes.materialChanges.length > 0 ? { ...beforeState.materials } : beforeState.materials for (const { id, material } of changes.materialChanges) { @@ -2264,7 +2183,7 @@ export function applySceneOperationPatch(changes: SceneOperationPatch): boolean useScene.temporal.getState().isTracking || getSceneHistoryPauseDepth() > 0 if (shouldScopeHistoryPause) pauseSceneHistory(useScene) try { - useScene.setState(next) + runAsRemoteSceneChange(() => useScene.setState(next)) } finally { if (shouldScopeHistoryPause) resumeSceneHistory(useScene) } @@ -2359,12 +2278,14 @@ export function applySceneSnapshot( pauseSceneHistory(useScene) try { - useScene.getState().setScene(snapshot.nodes, snapshot.rootNodeIds, { - collections: snapshot.collections, - installedPlugins: snapshot.installedPlugins, - hasExplicitPluginInstallState: options.explicitPluginInstallState, - materials: snapshot.materials, - }) + runAsRemoteSceneChange(() => + useScene.getState().setScene(snapshot.nodes, snapshot.rootNodeIds, { + collections: snapshot.collections, + installedPlugins: snapshot.installedPlugins, + hasExplicitPluginInstallState: options.explicitPluginInstallState, + materials: snapshot.materials, + }), + ) useScene.temporal.getState().clear() } finally { resumeSceneHistory(useScene) @@ -2438,10 +2359,14 @@ useScene.temporal.subscribe((state, previousState) => { const currentPastLength = state.pastStates.length const currentFutureLength = state.futureStates.length + // Only the store's own undo / redo jump history: a new edit after an undo also + // grows the past and drops the redo stack, and is not a redo. // Undo: futureStates increases (state moved from past to future) // Redo: pastStates increases while futureStates decreases (state moved from future to past) - const didUndo = currentFutureLength > prevFutureLength - const didRedo = currentPastLength > prevPastLength && currentFutureLength < prevFutureLength + const jumping = isRestoringSceneHistory() + const didUndo = jumping && currentFutureLength > prevFutureLength + const didRedo = + jumping && currentPastLength > prevPastLength && currentFutureLength < prevFutureLength if (didUndo || didRedo) { // Capture both layouts before another synchronous jump can replace them. diff --git a/packages/core/src/systems/elevator/elevator-opening-sync.ts b/packages/core/src/systems/elevator/elevator-opening-sync.ts index 9fe4adf911..1c42e873ae 100644 --- a/packages/core/src/systems/elevator/elevator-opening-sync.ts +++ b/packages/core/src/systems/elevator/elevator-opening-sync.ts @@ -1,4 +1,4 @@ -import { resolveLevelId } from '../../hooks/spatial-grid/spatial-grid-sync' +import { resolveLevelId } from '../../lib/node-ancestry' import type { AnyNode, AnyNodeId, @@ -103,7 +103,7 @@ function getServedLevelRange(elevator: ElevatorNode, nodes: Record) { - if (!levelId) return undefined + if (!levelId) return const node = nodes[levelId as AnyNodeId] return node?.type === 'level' ? node.level : undefined } @@ -209,8 +209,7 @@ export function syncAutoElevatorOpenings(nodes: Record) { ] if ( - !polygonsEqual(existingHoles, nextHoles) || - !metadataEqual(existingMetadata, nextMetadata) + !(polygonsEqual(existingHoles, nextHoles) && metadataEqual(existingMetadata, nextMetadata)) ) { updates.push({ id: slab.id, @@ -257,8 +256,7 @@ export function syncAutoElevatorOpenings(nodes: Record) { ] if ( - !polygonsEqual(existingHoles, nextHoles) || - !metadataEqual(existingMetadata, nextMetadata) + !(polygonsEqual(existingHoles, nextHoles) && metadataEqual(existingMetadata, nextMetadata)) ) { updates.push({ id: ceiling.id, diff --git a/packages/core/src/systems/elevator/elevator-opening-system.test.ts b/packages/core/src/systems/elevator/elevator-opening-system.test.ts index cab6d2b17c..e8fdc5ad34 100644 --- a/packages/core/src/systems/elevator/elevator-opening-system.test.ts +++ b/packages/core/src/systems/elevator/elevator-opening-system.test.ts @@ -83,12 +83,16 @@ function resetScene() { } function getOpeningCenter(nodes: Record): [number, number] | null { - const slab = nodes[UPPER_SLAB_ID] as { holes?: [number, number][][] } - const opening = slab.holes?.[0] + const opening = Object.values(nodes).find( + (node) => node.type === 'floor-opening' && node.ownerId === ELEVATOR_ID, + )?.polygon if (!opening || opening.length === 0) return null const [x, z] = opening.reduce(([sumX, sumZ], point) => [sumX + point[0], sumZ + point[1]], [0, 0]) - return [x / opening.length, z / opening.length] + return [ + Math.round((x / opening.length) * 1e6) / 1e6, + Math.round((z / opening.length) * 1e6) / 1e6, + ] } function getElevatorPosition(nodes: Record) { @@ -111,7 +115,7 @@ describe('ElevatorOpeningSystem scene commit boundary', () => { stopCommitSubscription = () => {} }) - test('includes the elevator edit and derived slab opening in one commit and undo step', () => { + test('includes the elevator edit and owned opening intent in one commit and undo step', () => { const commits: SceneCommit[] = [] stopOpeningSync = initializeElevatorOpeningSync() stopCommitSubscription = subscribeSceneCommits((commit) => commits.push(commit)) @@ -123,18 +127,19 @@ describe('ElevatorOpeningSystem scene commit boundary', () => { expect(commits[0]?.before.nodes[ELEVATOR_ID]?.visible).toBe(false) expect(commits[0]?.current.nodes[ELEVATOR_ID]?.visible).toBe(true) expect((commits[0]?.before.nodes[UPPER_SLAB_ID] as { holes?: unknown[] }).holes).toEqual([]) - expect((commits[0]?.current.nodes[UPPER_SLAB_ID] as { holes?: unknown[] }).holes).toHaveLength( - 1, - ) + expect(getOpeningCenter(commits[0]!.current.nodes)).toEqual([2, 1.5]) expect( - (commits[0]?.current.nodes[UPPER_SLAB_ID] as { holeMetadata?: unknown[] }).holeMetadata, - ).toEqual([{ elevatorId: ELEVATOR_ID, source: 'elevator' }]) + Object.values(commits[0]!.current.nodes).some( + (node) => node.type === 'floor-opening' && node.ownerId === ELEVATOR_ID, + ), + ).toBe(true) expect(useScene.temporal.getState().pastStates).toHaveLength(1) useScene.temporal.getState().undo() expect(useScene.getState().nodes[ELEVATOR_ID]?.visible).toBe(false) expect((useScene.getState().nodes[UPPER_SLAB_ID] as { holes?: unknown[] }).holes).toEqual([]) + expect(getOpeningCenter(useScene.getState().nodes)).toBeNull() }) test('processes a second relevant elevator mutation in the same turn', () => { diff --git a/packages/core/src/systems/elevator/elevator-opening-system.tsx b/packages/core/src/systems/elevator/elevator-opening-system.tsx index d2ac128f6f..8d147cdd84 100644 --- a/packages/core/src/systems/elevator/elevator-opening-system.tsx +++ b/packages/core/src/systems/elevator/elevator-opening-system.tsx @@ -1,10 +1,13 @@ 'use client' import { useEffect } from 'react' +import { structureChangeBatch } from '../../commands/structure/shared' import type { AnyNode } from '../../schema' import { pauseSceneHistory, resumeSceneHistory } from '../../store/history-control' +import { isHydrationNormalization } from '../../store/scene-hydration' import useScene from '../../store/use-scene' -import { syncAutoElevatorOpenings } from './elevator-opening-sync' +import { planOwnedFloorOpenings } from '../owned-floor-openings' +import { reconcileOwnedFloorOpeningChanges } from '../reconcile-owned-floor-openings' function isOpeningRelevantNode(node: AnyNode | undefined) { return ( @@ -36,24 +39,27 @@ function hasOpeningRelevantNodeChange( export function initializeElevatorOpeningSync() { let syncingAutoOpenings = false - const applyUpdates = (updates: ReturnType) => { - if (updates.length === 0) return + const applyChanges = (skipExistingSurfaces = false) => { + const changes = planOwnedFloorOpenings(useScene.getState().nodes, { skipExistingSurfaces }) + if (changes.length === 0) return syncingAutoOpenings = true pauseSceneHistory(useScene) try { - useScene.getState().updateNodes(updates) + const before = useScene.getState().nodes + useScene.getState().applyNodeChanges(structureChangeBatch(changes)) + reconcileOwnedFloorOpeningChanges(before, changes) } finally { resumeSceneHistory(useScene) syncingAutoOpenings = false } } - applyUpdates(syncAutoElevatorOpenings(useScene.getState().nodes)) + applyChanges(true) return useScene.subscribe((state, prevState) => { if (syncingAutoOpenings) return if (!hasOpeningRelevantNodeChange(state.nodes, prevState.nodes)) return - applyUpdates(syncAutoElevatorOpenings(state.nodes)) + applyChanges(isHydrationNormalization() || state.hydrationId !== prevState.hydrationId) }) } diff --git a/packages/core/src/systems/elevator/elevator-service.ts b/packages/core/src/systems/elevator/elevator-service.ts index 1c4390d2a7..6dd227d9b8 100644 --- a/packages/core/src/systems/elevator/elevator-service.ts +++ b/packages/core/src/systems/elevator/elevator-service.ts @@ -8,10 +8,17 @@ export type ElevatorLevelEntry = { } function getBuildingLevels(elevator: ElevatorNode, nodes: Record): LevelNode[] { + const parent = elevator.parentId ? nodes[elevator.parentId as AnyNodeId] : undefined + // Older saves attach elevators to a level. Opening queries must agree before + // and after client hydration reparents them to the owning building. const building = - elevator.parentId && nodes[elevator.parentId as AnyNodeId]?.type === 'building' - ? nodes[elevator.parentId as AnyNodeId] - : null + parent?.type === 'level' + ? parent.parentId && nodes[parent.parentId]?.type === 'building' + ? nodes[parent.parentId] + : Object.values(nodes).find( + (node) => node.type === 'building' && node.children.includes(parent.id), + ) + : parent if (building?.type !== 'building') return [] diff --git a/packages/core/src/systems/owned-floor-openings.test.ts b/packages/core/src/systems/owned-floor-openings.test.ts new file mode 100644 index 0000000000..f1685d58b8 --- /dev/null +++ b/packages/core/src/systems/owned-floor-openings.test.ts @@ -0,0 +1,435 @@ +import { expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + CeilingNode, + ElevatorNode, + FloorOpeningNode, + LevelNode, + SlabNode, + StairNode, +} from '../schema' +import { migrateOwnedFloorOpenings } from '../utils/owned-floor-opening-migration' +import { reconcileStructureOnLoad } from '../utils/reconcile-structure-on-load' +import { reconcileStructureWithStableIds } from '../utils/structure-id' +import { planOwnedFloorOpenings } from './owned-floor-openings' + +const square: [number, number][] = [ + [0, 0], + [6, 0], + [6, 6], + [0, 6], +] + +function fixture() { + const building = BuildingNode.parse({ id: 'building_owned_test' }) + const ground = LevelNode.parse({ + id: 'level_owned_ground', + parentId: building.id, + level: 0, + height: 4.5, + }) + const upper = LevelNode.parse({ id: 'level_owned_upper', parentId: building.id, level: 1 }) + building.children = [ground.id, upper.id] + const plate = SlabNode.parse({ + id: 'slab_owned_upper', + parentId: upper.id, + polygon: square, + boundary: 'auto', + }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_owned_ground', + parentId: ground.id, + polygon: square, + boundary: 'auto', + }) + const stair = StairNode.parse({ + id: 'stair_owned_a', + parentId: ground.id, + position: [3, 0, 3], + stairType: 'spiral', + totalRise: 4.5, + fromLevelId: ground.id, + toLevelId: upper.id, + slabOpeningMode: 'destination', + }) + ground.children = [ceiling.id, stair.id] + upper.children = [plate.id] + const nodes = Object.fromEntries( + [building, ground, upper, plate, ceiling, stair].map((node) => [node.id, node]), + ) as Record + return { nodes, building, ground, upper, plate, ceiling, stair } +} + +function apply(nodes: Record, changes: ReturnType) { + const next = { ...nodes } + for (const change of changes) { + if (change.op === 'create') next[change.node.id] = change.node + else if (change.op === 'delete') delete next[change.id] + else next[change.id] = { ...next[change.id], ...change.data } as AnyNode + } + return next +} + +test('a reaching spiral owns both cuts; move and delete update the same intent nodes', () => { + const { nodes, plate, ceiling, stair } = fixture() + const first = planOwnedFloorOpenings(nodes) + expect( + first.every( + (change) => change.op !== 'update' || (change.id !== plate.id && change.id !== ceiling.id), + ), + ).toBe(true) + const owned = first.filter( + (change) => change.op === 'create' && change.node.type === 'floor-opening', + ) + expect(owned).toHaveLength(2) + expect( + owned.map((entry) => + entry.op === 'create' && entry.node.type === 'floor-opening' ? entry.node.surfaceId : '', + ), + ).toEqual([plate.id, ceiling.id].sort().reverse()) + const withOpenings = apply(nodes, first) + expect(planOwnedFloorOpenings(withOpenings)).toEqual([]) + const moved = { ...withOpenings, [stair.id]: { ...stair, position: [2, 0, 2] } as AnyNode } + const changes = planOwnedFloorOpenings(moved) + expect( + changes.filter( + (change) => change.op === 'update' && withOpenings[change.id]?.type === 'floor-opening', + ), + ).toHaveLength(2) + expect(changes.some((change) => change.op === 'create' || change.op === 'delete')).toBe(false) + const deleted = { ...apply(moved, changes) } + delete deleted[stair.id] + expect(planOwnedFloorOpenings(deleted).filter((change) => change.op === 'delete')).toHaveLength(2) +}) + +test('two stairs sharing a void keep independent owners, and a short spiral creates no cut', () => { + const { nodes, stair, plate } = fixture() + const second = StairNode.parse({ ...stair, id: 'stair_owned_b' }) + const both = { ...nodes, [second.id]: second } + const changes = planOwnedFloorOpenings(both) + const openings = changes.flatMap((change) => + change.op === 'create' && change.node.type === 'floor-opening' ? [change.node] : [], + ) + expect(openings).toHaveLength(4) + expect(new Set(openings.map((opening) => opening.ownerId))).toEqual( + new Set([stair.id, second.id]), + ) + const short = { ...nodes, [stair.id]: { ...stair, totalRise: 2 } as AnyNode } + expect(planOwnedFloorOpenings(short).filter((change) => change.op === 'create')).toEqual([]) + const manualPlate = { ...plate, boundary: undefined } + const authored = { ...both, [plate.id]: manualPlate } + const opened = apply(authored, planOwnedFloorOpenings(authored)) + const first = reconcileStructureWithStableIds({ nodes: opened }).nodes + expect((first[plate.id] as SlabNode).holes).toHaveLength(1) + const oneOwner = { ...first } + delete oneOwner[second.id] + const reduced = apply(oneOwner, planOwnedFloorOpenings(oneOwner)) + const secondPass = reconcileStructureWithStableIds({ nodes: reduced }).nodes + expect((secondPass[plate.id] as SlabNode).holes).toHaveLength(1) +}) + +test('migration adopts exact legacy stair/elevator holes, preserves orphans, and is idempotent', () => { + const { nodes, plate, ceiling, stair, ground } = fixture() + const elevator = ElevatorNode.parse({ + id: 'elevator_owned', + parentId: ground.id, + fromLevelId: ground.id, + toLevelId: plate.parentId, + }) + const stairHole: [number, number][] = [ + [1.123456789, 1], + [2, 1], + [2, 2], + [1.123456789, 2], + ] + const liftHole: [number, number][] = [ + [3, 3], + [4, 3], + [4, 4], + [3, 4], + ] + const orphan: [number, number][] = [ + [4.5, 4.5], + [5, 4.5], + [5, 5], + [4.5, 5], + ] + const legacy = { + ...nodes, + [elevator.id]: elevator, + [plate.id]: { + ...plate, + holes: [stairHole, [...stairHole.slice(1), stairHole[0]!], liftHole, orphan], + holeMetadata: [ + { source: 'stair', stairId: stair.id }, + { source: 'stair', stairId: stair.id }, + { source: 'elevator', elevatorId: elevator.id }, + { source: 'stair', stairId: 'stair_deleted' }, + ], + } as AnyNode, + [ceiling.id]: { + ...ceiling, + holes: [stairHole], + holeMetadata: [{ source: 'stair', stairId: stair.id }], + } as AnyNode, + } + const first = migrateOwnedFloorOpenings(legacy) + const openings = Object.values(first.nodes).filter( + (node): node is Extract => + (node as AnyNode).type === 'floor-opening', + ) + expect(openings).toHaveLength(4) + expect(openings.find((opening) => opening.source === 'manual')?.polygon).toEqual(orphan) + expect(openings.find((opening) => opening.source === 'elevator')?.ownerId).toBe(elevator.id) + expect(openings.filter((opening) => opening.ownerId === stair.id)).toHaveLength(2) + expect(migrateOwnedFloorOpenings(first.nodes).nodes).toBe(first.nodes) +}) + +test('an authored stair opening follows its owner pose and level, then retires with it', () => { + const { nodes, stair, ground, upper } = fixture() + const authoredStair = { ...stair, slabOpeningMode: 'none' as const } + const polygon: [number, number][] = [ + [2, 2], + [3, 2], + [3, 3], + [2, 3], + ] + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_authored_stair', + parentId: upper.id, + polygon, + source: 'stair', + ownerId: stair.id, + metadata: { + ownerPose: { position: stair.position, rotation: 0, width: stair.width, runLength: 3 }, + ownerOpeningTarget: 'destination', + }, + }) + const initial = { ...nodes, [stair.id]: authoredStair, [opening.id]: opening } + expect(planOwnedFloorOpenings(initial)).toEqual([]) + const moved = { + ...initial, + [stair.id]: { ...authoredStair, position: [4, 0, 3], rotation: Math.PI / 2 }, + } + const plan = planOwnedFloorOpenings(moved) + expect(plan.filter((change) => change.op === 'update' && change.id === opening.id)).toHaveLength( + 1, + ) + const result = apply(moved, plan)[opening.id] as FloorOpeningNode + expect(result.polygon.some(([x, z]) => Math.abs(x - 3) < 0.005 && Math.abs(z - 4) < 0.005)).toBe( + true, + ) + expect(planOwnedFloorOpenings(apply(moved, plan))).toEqual([]) + const changedLevel = { + ...apply(moved, plan), + [stair.id]: { ...moved[stair.id], toLevelId: ground.id } as AnyNode, + } + expect(planOwnedFloorOpenings(changedLevel)).toContainEqual({ + op: 'update', + id: opening.id, + data: { parentId: ground.id }, + }) + const deleted = { ...initial } + delete deleted[stair.id] + expect(planOwnedFloorOpenings(deleted)).toContainEqual({ op: 'delete', id: opening.id }) +}) + +test('an automatic stair opening keeps its node id when the stair moves to another storey', () => { + const { nodes, stair, building, upper, plate } = fixture() + const first = apply(nodes, planOwnedFloorOpenings(nodes)) + const original = Object.values(first).find( + (node) => node.type === 'floor-opening' && node.surfaceId === plate.id, + ) as FloorOpeningNode + const third = LevelNode.parse({ id: 'level_owned_third', parentId: building.id, level: 2 }) + const thirdPlate = SlabNode.parse({ + id: 'slab_owned_third', + parentId: third.id, + polygon: square, + boundary: 'auto', + }) + third.children = [thirdPlate.id] + const moved = { + ...first, + [third.id]: third, + [thirdPlate.id]: thirdPlate, + [building.id]: { ...building, children: [...building.children, third.id] }, + [stair.id]: { ...stair, parentId: upper.id, fromLevelId: upper.id, toLevelId: third.id }, + } as Record + const plan = planOwnedFloorOpenings(moved) + expect(plan).toContainEqual({ + op: 'update', + id: original.id, + data: expect.objectContaining({ surfaceId: thirdPlate.id, parentId: third.id }), + }) + expect(plan.some((change) => change.op === 'delete' && change.id === original.id)).toBe(false) +}) + +test('a migrated manual ceiling keeps its old void until its stair is deleted', () => { + const { nodes, stair, ceiling } = fixture() + const hole: [number, number][] = [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], + ] + const legacy = { + ...nodes, + [ceiling.id]: { + ...ceiling, + boundary: undefined, + holes: [hole], + holeMetadata: [{ source: 'stair', stairId: stair.id }], + } as AnyNode, + } + const migrated = migrateOwnedFloorOpenings(legacy).nodes as Record + expect((migrated[ceiling.id] as CeilingNode).holes).toEqual([hole]) + const deleted = { ...migrated } + delete deleted[stair.id] + const settled = reconcileStructureWithStableIds({ + nodes: apply(deleted, planOwnedFloorOpenings(deleted)), + }).nodes + expect((settled[ceiling.id] as CeilingNode).holes).toEqual([]) +}) + +test('one stair owns one opening per level across stacked plates, including saved duplicates', () => { + const { nodes, plate, stair, upper } = fixture() + const platform = SlabNode.parse({ + ...plate, + id: 'slab_owned_platform', + plateRole: 'platform', + elevation: 0.35, + thickness: 0.3, + }) + const stacked = { + ...nodes, + [platform.id]: platform, + [upper.id]: { ...upper, children: [...upper.children, platform.id] }, + } + const planned = planOwnedFloorOpenings(stacked) + const upperOpenings = planned.flatMap((change) => + change.op === 'create' && + change.node.type === 'floor-opening' && + change.node.parentId === upper.id + ? [change.node] + : [], + ) + expect(upperOpenings).toHaveLength(1) + expect(Object.keys(upperOpenings[0]!.legacyPlateCuts ?? {}).sort()).toEqual( + [plate.id, platform.id].sort(), + ) + + const first = upperOpenings[0]! + const duplicate = FloorOpeningNode.parse({ + ...first, + id: 'floor-opening_duplicate_stair', + surfaceId: platform.id, + legacyPlateCuts: { [platform.id]: [first.polygon] }, + }) + const authoredDuplicate = FloorOpeningNode.parse({ + ...first, + id: 'floor-opening_duplicate_authored', + surfaceId: undefined, + }) + const saved = { + ...stacked, + [first.id]: { ...first, legacyPlateCuts: { [plate.id]: [first.polygon] } }, + [duplicate.id]: duplicate, + [authoredDuplicate.id]: authoredDuplicate, + [upper.id]: { + ...upper, + children: [...upper.children, platform.id, first.id, duplicate.id, authoredDuplicate.id], + }, + [plate.id]: { + ...plate, + holes: [first.polygon, first.polygon], + holeMetadata: [ + { source: 'floor-opening' as const, openingId: first.id }, + { source: 'floor-opening' as const, openingId: authoredDuplicate.id }, + ], + }, + [platform.id]: { + ...platform, + holes: [first.polygon], + holeMetadata: [{ source: 'floor-opening' as const, openingId: duplicate.id }], + }, + } + const synced = apply(saved, planOwnedFloorOpenings(saved)) + expect( + Object.values(synced).filter( + (node) => + node.type === 'floor-opening' && node.ownerId === stair.id && node.parentId === upper.id, + ), + ).toHaveLength(1) + expect(planOwnedFloorOpenings(synced)).toEqual([]) + const migrated = migrateOwnedFloorOpenings(saved) + const surviving = Object.values(migrated.nodes).filter( + (node): node is FloorOpeningNode => + (node as AnyNode).type === 'floor-opening' && + (node as FloorOpeningNode).ownerId === stair.id && + (node as FloorOpeningNode).parentId === upper.id, + ) + expect(surviving).toHaveLength(1) + expect(Object.keys(surviving[0]!.legacyPlateCuts ?? {}).sort()).toEqual( + [plate.id, platform.id].sort(), + ) + expect((migrated.nodes[plate.id] as SlabNode).holes).toHaveLength(1) + expect((migrated.nodes[plate.id] as SlabNode).holeMetadata[0]?.openingId).toBe(surviving[0]!.id) + expect((migrated.nodes[platform.id] as SlabNode).holeMetadata[0]?.openingId).toBe( + surviving[0]!.id, + ) + expect((migrated.nodes[upper.id] as LevelNode).children).not.toContain(duplicate.id) + expect(migrateOwnedFloorOpenings(migrated.nodes).nodes).toBe(migrated.nodes) + const loaded = reconcileStructureOnLoad(saved).nodes + expect( + Object.values(loaded).filter( + (node) => + node.type === 'floor-opening' && node.ownerId === stair.id && node.parentId === upper.id, + ), + ).toHaveLength(1) + expect(reconcileStructureOnLoad(loaded).nodes).toEqual(loaded) +}) + +test('legacy stair clearance is shared by near-identical cuts on stacked slabs', () => { + const { nodes, plate, stair, upper } = fixture() + const plain: [number, number][] = [ + [2, 2], + [3, 2], + [3, 3], + [2, 3], + ] + const clearance: [number, number][] = [ + [1.999, 1.999], + [3.001, 1.999], + [3.001, 3.001], + [1.999, 3.001], + ] + const second = SlabNode.parse({ ...plate, id: 'slab_owned_second', boundary: undefined }) + const legacy = { + ...nodes, + [upper.id]: { ...upper, children: [...upper.children, second.id] }, + [plate.id]: { + ...plate, + boundary: undefined, + holes: [plain], + holeMetadata: [{ source: 'stair' as const, stairId: stair.id }], + }, + [second.id]: { + ...second, + holes: [clearance], + holeMetadata: [{ source: 'stair' as const, stairId: stair.id }], + }, + } + const migrated = migrateOwnedFloorOpenings(legacy) + const opening = Object.values(migrated.nodes).find( + (node): node is FloorOpeningNode => + (node as AnyNode).type === 'floor-opening' && (node as FloorOpeningNode).ownerId === stair.id, + )! + expect(opening.legacyPlateCuts).toEqual({ + [plate.id]: [clearance], + [second.id]: [clearance], + }) + const reconciled = reconcileStructureWithStableIds({ nodes: migrated.nodes }).nodes + expect((reconciled[plate.id] as SlabNode).holes).toEqual([clearance]) + expect((reconciled[second.id] as SlabNode).holes).toEqual([clearance]) +}) diff --git a/packages/core/src/systems/owned-floor-openings.ts b/packages/core/src/systems/owned-floor-openings.ts new file mode 100644 index 0000000000..e3235b470c --- /dev/null +++ b/packages/core/src/systems/owned-floor-openings.ts @@ -0,0 +1,387 @@ +import { canonicalOpeningRing } from '../lib/canonical-opening-ring' +import type { NodePatch } from '../lib/structure-kernel' +import type { AnyNode, AnyNodeId, FloorOpeningNode, SurfaceHoleMetadata } from '../schema' +import { FloorOpeningNode as FloorOpeningSchema } from '../schema/nodes/floor-opening' +import { resolveCeilingHeight } from '../services/level-height' +import { getLevelElevations } from '../services/storey' +import { syncAutoElevatorOpenings } from './elevator/elevator-opening-sync' +import { syncAutoStairOpenings } from './stair/stair-opening-sync' +import { resolveStairTotalRise } from './stair/stair-rise-query' + +type Source = 'stair' | 'elevator' +type Surface = Extract +type DesiredCut = { source: Source; ownerId: string; surface: Surface; polygon: [number, number][] } +type OwnerPose = { + position: [number, number, number] + rotation: number + width: number + runLength: number +} + +function ownerPose(value: unknown): OwnerPose | undefined { + if (!value || typeof value !== 'object') return + const pose = value as Partial + if ( + !Array.isArray(pose.position) || + pose.position.length !== 3 || + !pose.position.every( + (coordinate) => typeof coordinate === 'number' && Number.isFinite(coordinate), + ) || + typeof pose.rotation !== 'number' || + !Number.isFinite(pose.rotation) || + typeof pose.width !== 'number' || + !Number.isFinite(pose.width) || + !(pose.width > 0) || + typeof pose.runLength !== 'number' || + !Number.isFinite(pose.runLength) || + !(pose.runLength > 0) + ) + return + return pose as OwnerPose +} + +function hashKey(key: string) { + let hash = 0xcbf2_9ce4_8422_2325n + for (const byte of new TextEncoder().encode(key)) + hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100_0000_01b3n) + return `floor-opening_${hash.toString(36).padStart(16, '0')}` +} + +function ownerFor(metadata: SurfaceHoleMetadata) { + return metadata.source === 'stair' + ? metadata.stairId + : metadata.source === 'elevator' + ? metadata.elevatorId + : undefined +} + +function withoutOwnedCuts(nodes: Record) { + const stripped = { ...nodes } + for (const node of Object.values(nodes)) { + if (node.type !== 'slab' && node.type !== 'ceiling') continue + const kept = (node.holes ?? []).flatMap((hole, index) => { + const metadata = node.holeMetadata?.[index] + if (metadata?.source === 'stair' || metadata?.source === 'elevator') return [] + if (metadata?.source === 'floor-opening' && metadata.openingId) { + const opening = nodes[metadata.openingId] + if ( + !opening || + (opening.type === 'floor-opening' && + (opening.source === 'stair' || opening.source === 'elevator')) + ) + return [] + } + return [{ hole, metadata: metadata ?? { source: 'manual' as const } }] + }) + if (kept.length !== (node.holes ?? []).length) + stripped[node.id] = { + ...node, + holes: kept.map((entry) => entry.hole), + holeMetadata: kept.map((entry) => entry.metadata), + } as Surface + } + return stripped +} + +function desiredCuts(nodes: Record) { + let draft = withoutOwnedCuts(nodes) + for (const derive of [syncAutoElevatorOpenings, syncAutoStairOpenings]) { + const updates = derive(draft) + if (!updates.length) continue + draft = { ...draft } + for (const { id, data } of updates) draft[id] = { ...draft[id], ...data } as AnyNode + } + return cutsFromSurfaces(draft, nodes) +} + +function cutsFromSurfaces(surfaces: Record, owners: Record) { + const cuts: DesiredCut[] = [] + for (const surface of Object.values(surfaces)) { + if (surface.type !== 'slab' && surface.type !== 'ceiling') continue + for (const [index, polygon] of (surface.holes ?? []).entries()) { + const metadata = surface.holeMetadata?.[index] + if (metadata?.source !== 'stair' && metadata?.source !== 'elevator') continue + const ownerId = ownerFor(metadata) + if (ownerId && owners[ownerId]?.type === metadata.source) + cuts.push({ source: metadata.source, ownerId, surface, polygon }) + } + } + return cuts +} + +export function planOwnedFloorOpenings( + nodes: Record, + options: { + ownerIds?: ReadonlySet + skipExistingSurfaces?: boolean + enforceReach?: boolean + materializedNodes?: Record + } = {}, +): NodePatch[] { + const values = Object.values(nodes) + if ( + !values.some( + (node) => + node.type === 'stair' || + node.type === 'elevator' || + (node.type === 'floor-opening' && (node.source === 'stair' || node.source === 'elevator')), + ) + ) + return [] + const existing = values.filter( + (node): node is FloorOpeningNode => + node.type === 'floor-opening' && + (node.source === 'stair' || node.source === 'elevator') && + !!node.ownerId && + !!node.surfaceId, + ) + const authored = values.filter( + (node): node is FloorOpeningNode => + node.type === 'floor-opening' && + (node.source === 'stair' || node.source === 'elevator') && + !!node.ownerId && + !node.surfaceId, + ) + const eligible = (ownerId: string) => !options.ownerIds || options.ownerIds.has(ownerId) + const byLevel = new Map() + const elevations = options.enforceReach === false ? undefined : getLevelElevations(nodes) + for (const cut of options.materializedNodes + ? cutsFromSurfaces(options.materializedNodes, nodes) + : desiredCuts(nodes)) { + const owner = nodes[cut.ownerId] + if (!eligible(cut.ownerId)) continue + const level = cut.surface.parentId ? nodes[cut.surface.parentId] : undefined + if ( + options.skipExistingSurfaces && + level?.type === 'level' && + level.metadata?.legacyAutoOpeningsMigrated === true && + !existing.some( + (opening) => opening.ownerId === cut.ownerId && opening.source === cut.source, + ) && + !(nodes[cut.surface.id]?.type === 'slab' || nodes[cut.surface.id]?.type === 'ceiling' + ? (nodes[cut.surface.id] as Surface).holeMetadata?.some( + (metadata) => metadata.source === cut.source && ownerFor(metadata) === cut.ownerId, + ) + : false) + ) + continue + if (owner?.type === 'stair' && elevations) { + const from = elevations.get(owner.fromLevelId ?? owner.parentId ?? '') + const target = elevations.get(cut.surface.parentId ?? '') + if (from && target && from.buildingId === target.buildingId) { + const rise = resolveStairTotalRise(owner, nodes) + const surfaceHeight = + cut.surface.type === 'slab' + ? (cut.surface.elevation ?? 0.05) + : resolveCeilingHeight(cut.surface, nodes) + const targetRise = target.baseY - from.baseY + surfaceHeight - owner.position[1] + if (rise + Math.max(0.35, (rise / Math.max(owner.stepCount, 1)) * 2) < targetRise) continue + } + } + if ( + options.skipExistingSurfaces && + existing.some((opening) => opening.ownerId === cut.ownerId && opening.source === cut.source) + ) + continue + if ( + authored.some( + (opening) => + opening.source === cut.source && + opening.ownerId === cut.ownerId && + opening.parentId === cut.surface.parentId, + ) && + !existing.some( + (opening) => + opening.source === cut.source && + opening.ownerId === cut.ownerId && + opening.parentId === cut.surface.parentId, + ) + ) + continue + if (owner?.type === 'stair' && (owner.slabOpeningMode ?? 'none') !== 'destination') continue + if (!cut.surface.parentId) continue + const key = JSON.stringify([cut.source, cut.ownerId, cut.surface.parentId]) + byLevel.set(key, [...(byLevel.get(key) ?? []), cut]) + } + const patches: NodePatch[] = [] + const retained = new Set() + const addedByLevel = new Map() + const deletedByLevel = new Map>() + for (const opening of authored) { + if (!eligible(opening.ownerId!)) continue + const owner = nodes[opening.ownerId!] + if ( + !owner || + owner.type !== opening.source || + existing.some( + (candidate) => + candidate.source === opening.source && + candidate.ownerId === opening.ownerId && + candidate.parentId === opening.parentId, + ) + ) { + patches.push({ op: 'delete', id: opening.id }) + if (opening.parentId) { + const removed = deletedByLevel.get(opening.parentId) ?? new Set() + removed.add(opening.id) + deletedByLevel.set(opening.parentId, removed) + } + continue + } + if (owner.type !== 'stair') continue + const oldPose = ownerPose(opening.metadata.ownerPose) + const segment = owner.children + .map((id) => nodes[id]) + .find((node) => node?.type === 'stair-segment') + const runLength = segment?.type === 'stair-segment' ? segment.length : (oldPose?.runLength ?? 1) + const pose = { + position: owner.position, + rotation: owner.rotation, + width: owner.width, + runLength, + } + const target = + opening.metadata.ownerOpeningTarget === 'source' || opening.drawnOn === 'ceiling' + ? owner.fromLevelId + : owner.toLevelId + const parentId = target && nodes[target]?.type === 'level' ? target : opening.parentId + const poseChanged = oldPose && JSON.stringify(oldPose) !== JSON.stringify(pose) + const polygon = poseChanged + ? canonicalOpeningRing( + opening.polygon.map(([x, z]): [number, number] => { + const dx = x - oldPose.position[0] + const dz = z - oldPose.position[2] + const cosOld = Math.cos(oldPose.rotation) + const sinOld = Math.sin(oldPose.rotation) + const localX = (dx * cosOld - dz * sinOld) * (owner.width / oldPose.width) + const localZ = (dx * sinOld + dz * cosOld) * (runLength / oldPose.runLength) + const cos = Math.cos(owner.rotation) + const sin = Math.sin(owner.rotation) + return [ + owner.position[0] + localX * cos + localZ * sin, + owner.position[2] - localX * sin + localZ * cos, + ] + }), + ) + : opening.polygon + const metadata = { ...opening.metadata, ownerPose: pose } + const data: Partial = {} + if (JSON.stringify(polygon) !== JSON.stringify(opening.polygon)) data.polygon = polygon + if (parentId !== opening.parentId) { + data.parentId = parentId + if (opening.parentId) { + const removed = deletedByLevel.get(opening.parentId) ?? new Set() + removed.add(opening.id) + deletedByLevel.set(opening.parentId, removed) + } + if (parentId) addedByLevel.set(parentId, [...(addedByLevel.get(parentId) ?? []), opening.id]) + } + if (JSON.stringify(metadata) !== JSON.stringify(opening.metadata)) data.metadata = metadata + if (Object.keys(data).length) patches.push({ op: 'update', id: opening.id, data }) + } + for (const [key, cuts] of byLevel) { + const [source, ownerId, levelId] = JSON.parse(key) as [Source, string, string] + const siblings = existing + .filter( + (node) => node.source === source && node.ownerId === ownerId && node.parentId === levelId, + ) + .sort((a, b) => a.id.localeCompare(b.id)) + cuts.sort( + (a, b) => + Number(b.surface.type === 'slab') - Number(a.surface.type === 'slab') || + a.surface.id.localeCompare(b.surface.id) || + JSON.stringify(a.polygon).localeCompare(JSON.stringify(b.polygon)), + ) + const old = + siblings[0] ?? + existing.find( + (node) => + node.source === source && + node.ownerId === ownerId && + node.drawnOn === (cuts[0]!.surface.type === 'slab' ? 'floor' : 'ceiling') && + !retained.has(node.id) && + !byLevel.has(JSON.stringify([source, ownerId, node.parentId])), + ) + const id = old?.id ?? hashKey(JSON.stringify([source, ownerId, levelId])) + const legacyPlateCuts: Record = {} + const legacyCeilingCuts: Record = {} + for (const cut of cuts) { + const map = cut.surface.type === 'slab' ? legacyPlateCuts : legacyCeilingCuts + const rings = map[cut.surface.id] ?? [] + if (!rings.some((ring) => JSON.stringify(ring) === JSON.stringify(cut.polygon))) + map[cut.surface.id] = [...rings, cut.polygon] + } + const primary = cuts[0]! + const candidate = FloorOpeningSchema.parse({ + ...old, + id, + parentId: levelId, + name: source === 'stair' ? 'Stair opening' : 'Elevator opening', + polygon: canonicalOpeningRing(primary.polygon), + source, + ownerId, + surfaceId: primary.surface.id, + drawnOn: primary.surface.type === 'slab' ? 'floor' : 'ceiling', + cutsPrimary: true, + cutsAdjacent: false, + legacyPlateCuts: Object.keys(legacyPlateCuts).length ? legacyPlateCuts : undefined, + legacyCeilingCuts: Object.keys(legacyCeilingCuts).length ? legacyCeilingCuts : undefined, + }) + retained.add(id) + if (old) { + const data: Record = {} + for (const property of [ + 'parentId', + 'surfaceId', + 'polygon', + 'legacyPlateCuts', + 'legacyCeilingCuts', + 'drawnOn', + ]) + if ( + JSON.stringify(old[property as keyof FloorOpeningNode]) !== + JSON.stringify(candidate[property as keyof FloorOpeningNode]) + ) + data[property] = candidate[property as keyof FloorOpeningNode] + if (Object.keys(data).length) + patches.push({ op: 'update', id: old.id, data: data as Partial }) + if (old.parentId !== candidate.parentId) { + if (old.parentId) { + const removed = deletedByLevel.get(old.parentId) ?? new Set() + removed.add(old.id) + deletedByLevel.set(old.parentId, removed) + } + if (candidate.parentId) + addedByLevel.set(candidate.parentId, [ + ...(addedByLevel.get(candidate.parentId) ?? []), + old.id, + ]) + } + } else { + patches.push({ op: 'create', node: candidate }) + if (candidate.parentId) + addedByLevel.set(candidate.parentId, [...(addedByLevel.get(candidate.parentId) ?? []), id]) + } + } + for (const opening of existing) { + if (!eligible(opening.ownerId!) || retained.has(opening.id) || options.skipExistingSurfaces) + continue + patches.push({ op: 'delete', id: opening.id }) + if (opening.parentId) { + const removed = deletedByLevel.get(opening.parentId) ?? new Set() + removed.add(opening.id) + deletedByLevel.set(opening.parentId, removed) + } + } + for (const levelId of new Set([...addedByLevel.keys(), ...deletedByLevel.keys()])) { + const level = nodes[levelId] + if (level?.type !== 'level') continue + const children = [ + ...level.children.filter((id) => !deletedByLevel.get(levelId)?.has(id)), + ...(addedByLevel.get(levelId) ?? []), + ] as AnyNodeId[] + if (JSON.stringify(children) !== JSON.stringify(level.children)) + patches.push({ op: 'update', id: level.id, data: { children } }) + } + return patches +} diff --git a/packages/core/src/systems/reconcile-owned-floor-openings.ts b/packages/core/src/systems/reconcile-owned-floor-openings.ts new file mode 100644 index 0000000000..de0c626b9d --- /dev/null +++ b/packages/core/src/systems/reconcile-owned-floor-openings.ts @@ -0,0 +1,26 @@ +import { createFloorOpeningIndex, floorOpeningTargets } from '../lib/floor-opening-intent' +import { applyStructureReconciliation } from '../lib/structure-commit' +import type { NodePatch, SceneNodes } from '../lib/structure-kernel' +import type { AnyNode } from '../schema' +import { generateId } from '../schema/base' +import useScene from '../store/use-scene' + +export function reconcileOwnedFloorOpeningChanges(before: SceneNodes, changes: NodePatch[]) { + const after = useScene.getState().nodes + const oldIndex = createFloorOpeningIndex(before) + const newIndex = createFloorOpeningIndex(after) + const levels = new Set() + for (const change of changes) { + const id = change.op === 'create' ? change.node.id : change.id + for (const [nodes, index] of [ + [before, oldIndex], + [after, newIndex], + ] as const) { + const opening = (nodes as Record)[id] + if (opening?.type !== 'floor-opening') continue + for (const target of floorOpeningTargets(nodes, opening, index)) levels.add(target.levelId) + } + } + if (levels.size) + applyStructureReconciliation(useScene, { levelIds: [...levels], mintId: generateId }) +} diff --git a/packages/core/src/systems/slab/__fixtures__/doorway-steps.ts b/packages/core/src/systems/slab/__fixtures__/doorway-steps.ts new file mode 100644 index 0000000000..b202087d9c --- /dev/null +++ b/packages/core/src/systems/slab/__fixtures__/doorway-steps.ts @@ -0,0 +1,83 @@ +import { + type AnyNode, + DoorNode, + LevelNode, + SeparatorNode, + WallNode, + ZoneNode, +} from '../../../schema' +import { reconcileStructureWithStableIds } from '../../../utils/structure-id' + +/** + * Three rooms in a row, A | B | C, a door in each dividing wall. B is raised, + * so it owns a step at each door: one toward A, one toward C. `open` divides B + * from C with a separator instead of a wall and door. + */ +export function doorwayStepsFixture( + elevations: [number, number, number] = [0.05, 0.3, 0.05], + open = false, +) { + const ring = (x0: number, x1: number): [number, number][] => [ + [x0, 0], + [x1, 0], + [x1, 4], + [x0, 4], + ] + const outline = ring(0, 12) + const walls = outline.map((start, i) => + WallNode.parse({ + id: `wall_row_${i}`, + parentId: 'level_row', + start, + end: outline[(i + 1) % 4], + thickness: 0.2, + }), + ) + const doors = (['ab', 'bc'] as const).map((pair) => + DoorNode.parse({ + id: `door_${pair}`, + parentId: `wall_row_${pair}`, + wallId: `wall_row_${pair}`, + width: 1, + height: 2, + position: [2, 1, 0], + }), + ) + const dividers = ([4, 8] as const).map((x, i) => + WallNode.parse({ + id: `wall_row_${i ? 'bc' : 'ab'}`, + parentId: 'level_row', + start: [x, 0], + end: [x, 4], + thickness: 0.2, + children: [doors[i]!.id], + }), + ) + const zones = (['a', 'b', 'c'] as const).map((name, i) => + ZoneNode.parse({ + id: `zone_${name}`, + parentId: 'level_row', + name: name.toUpperCase(), + spaceRole: 'room', + enclosureStatus: 'enclosed', + polygon: ring(i * 4, (i + 1) * 4), + floor: { elevation: elevations[i] }, + }), + ) + const separator = SeparatorNode.parse({ + id: 'separator_bc', + parentId: 'level_row', + start: [8, 0], + end: [8, 4], + }) + const children = [...walls, ...(open ? [dividers[0]!, separator] : dividers), ...zones] + const level = LevelNode.parse({ + id: 'level_row', + height: 3, + children: children.map((node) => node.id), + }) + const nodes: Record = Object.fromEntries( + [level, ...children, ...(open ? doors.slice(0, 1) : doors)].map((node) => [node.id, node]), + ) + return reconcileStructureWithStableIds({ nodes }).nodes as Record +} diff --git a/packages/core/src/systems/slab/__fixtures__/floor-step.ts b/packages/core/src/systems/slab/__fixtures__/floor-step.ts new file mode 100644 index 0000000000..3904c392bd --- /dev/null +++ b/packages/core/src/systems/slab/__fixtures__/floor-step.ts @@ -0,0 +1,82 @@ +import { + type AnyNode, + DoorNode, + LevelNode, + SeparatorNode, + SlabNode, + WallNode, + ZoneNode, +} from '../../../schema' + +export function floorStepFixture(separator = false) { + const ring = (x0: number, z0: number, x1: number, z1: number): [number, number][] => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], + ] + const outline = ring(0, 0, 8, 4) + const walls = outline.map((start, i) => + WallNode.parse({ + id: `wall_step_${i}`, + parentId: 'level_step', + start, + end: outline[(i + 1) % 4], + thickness: 0.2, + }), + ) + const divider = WallNode.parse({ + id: 'wall_step_divider', + parentId: 'level_step', + start: [4, 0], + end: [4, 4], + thickness: 0.2, + frontSide: 'interior', + backSide: 'exterior', + }) + const boundary = separator + ? SeparatorNode.parse({ + id: 'separator_step', + parentId: 'level_step', + start: divider.start, + end: divider.end, + }) + : divider + if (!separator) walls.push(divider) + const zones = [0.05, -0.4].map((elevation, i) => + ZoneNode.parse({ + id: `zone_step_${i}`, + parentId: 'level_step', + name: 'Room', + spaceRole: 'room', + enclosureStatus: 'enclosed', + polygon: ring(i * 4, 0, (i + 1) * 4, 4), + floor: { elevation }, + }), + ) + const slabs = zones.map((zone, i) => + SlabNode.parse({ + id: `slab_step_${i}`, + parentId: 'level_step', + boundary: 'auto', + zoneIds: [zone.id], + elevation: zone.floor!.elevation, + thickness: i ? 0.05 : 0.45, + polygon: ring(i ? (separator ? 4 : 3.9) : -0.1, -0.1, i ? 8.1 : separator ? 4 : 4.1, 4.1), + }), + ) + const door = DoorNode.parse({ + id: 'door_step', + parentId: divider.id, + wallId: divider.id, + width: 1, + height: 2, + position: [2, 1, 0], + }) + const children = [...walls, ...(separator ? [boundary] : []), ...zones, ...slabs] + const level = LevelNode.parse({ id: 'level_step', children: children.map((node) => node.id) }) + const nodes: Record = Object.fromEntries( + [level, ...children].map((node) => [node.id, node]), + ) + return { walls, divider, boundary, zones, slabs, door, level, nodes } +} diff --git a/packages/core/src/systems/slab/__fixtures__/raised-room.ts b/packages/core/src/systems/slab/__fixtures__/raised-room.ts new file mode 100644 index 0000000000..3e70d847b4 --- /dev/null +++ b/packages/core/src/systems/slab/__fixtures__/raised-room.ts @@ -0,0 +1,56 @@ +import { encodeTerrainField } from '../../../lib/terrain-codec' +import { createTerrainField } from '../../../lib/terrain-field' +import { type AnyNode, BuildingNode, SiteNode } from '../../../schema' +import { floorStepFixture } from './floor-step' + +export function raisedRoomFixture(neighbor = false, terrain = false) { + const fixture = floorStepFixture() + const walls = neighbor ? fixture.walls : fixture.walls.slice(0, 4) + const zones = (neighbor ? fixture.zones : fixture.zones.slice(0, 1)).map((zone, i) => ({ + ...zone, + floor: { elevation: i ? 0.05 : 0.6 }, + polygon: !neighbor + ? ([ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ] as [number, number][]) + : zone.polygon, + })) + const slabs = (neighbor ? fixture.slabs : fixture.slabs.slice(0, 1)).map((slab, i) => ({ + ...slab, + elevation: i ? 0.05 : 0.6, + thickness: 0.05, + polygon: !neighbor + ? ([ + [-0.1, -0.1], + [8.1, -0.1], + [8.1, 4.1], + [-0.1, 4.1], + ] as [number, number][]) + : slab.polygon, + })) + const field = createTerrainField({ origin: [-1, -1], cols: 12, rows: 8, spacing: 1 }) + for (let r = 0; r < field.rows; r++) + for (let c = 0; c < field.cols; c++) field.heights[r * field.cols + c] = 10 + c * 2 + const site = SiteNode.parse({ + id: 'site_platform', + children: ['building_platform'], + ...(terrain ? { terrain: encodeTerrainField(field) } : {}), + }) + const building = BuildingNode.parse({ + id: 'building_platform', + parentId: site.id, + children: [fixture.level.id], + }) + const level = { + ...fixture.level, + parentId: building.id, + children: [...walls, ...zones, ...slabs].map((node) => node.id), + } + const nodes: Record = Object.fromEntries( + [site, building, level, ...walls, ...zones, ...slabs].map((node) => [node.id, node]), + ) + return { ...fixture, walls, zones, slabs, nodes, site, building, level } +} diff --git a/packages/core/src/systems/slab/ensure-slab-openings.ts b/packages/core/src/systems/slab/ensure-slab-openings.ts new file mode 100644 index 0000000000..d38661e53b --- /dev/null +++ b/packages/core/src/systems/slab/ensure-slab-openings.ts @@ -0,0 +1,44 @@ +import { area, difference, union } from '../../lib/polygon-boolean' +import type { AnyNode, AnyNodeId, SlabNode, SurfaceHoleMetadata } from '../../schema' + +function sameOwner(left: SurfaceHoleMetadata, right: SurfaceHoleMetadata) { + return ( + left.source === right.source && + ((right.source === 'stair' && !!right.stairId && left.stairId === right.stairId) || + (right.source === 'elevator' && !!right.elevatorId && left.elevatorId === right.elevatorId)) + ) +} + +export function ensureMissingSlabOpenings( + nodes: Record, + updates: Array<{ id: AnyNodeId; data: Partial }>, +): Array<{ id: AnyNodeId; data: Partial }> { + return updates.flatMap((update) => { + const slab = nodes[update.id] + if (slab?.type !== 'slab') return [update] + const data = update.data as Partial + const holes = slab.holes ?? [] + const metadata = holes.map((_, i) => slab.holeMetadata?.[i] ?? { source: 'manual' as const }) + const existing = union(holes) + const additions = (data.holes ?? []).flatMap((polygon, i) => { + const owner = data.holeMetadata?.[i] + if (!owner || (owner.source !== 'stair' && owner.source !== 'elevator')) return [] + // Ownership preserves deliberately edited openings; geometric coverage also + // recognizes older saves whose holes have no ownership metadata. + if (metadata.some((entry) => sameOwner(entry, owner))) return [] + const proposed = union([polygon]) + if (area(difference(proposed, existing)) <= Math.max(1e-8, area(proposed) * 1e-3)) return [] + return [{ polygon, owner }] + }) + if (!additions.length) return [] + return [ + { + id: slab.id, + data: { + holes: [...holes, ...additions.map(({ polygon }) => polygon)], + holeMetadata: [...metadata, ...additions.map(({ owner }) => owner)], + }, + }, + ] + }) +} diff --git a/packages/core/src/systems/slab/floor-step.test.ts b/packages/core/src/systems/slab/floor-step.test.ts new file mode 100644 index 0000000000..f3618557ab --- /dev/null +++ b/packages/core/src/systems/slab/floor-step.test.ts @@ -0,0 +1,185 @@ +import { expect, test } from 'bun:test' +import { + classifyPlateSideAt, + computePlateSurfacePartition, + plateSideRuns, +} from '../../lib/plate-surface' +import { floorStepFixture } from './__fixtures__/floor-step' +import { computeWallSlabSupport } from './slab-support' + +test('room faces follow 0.05 / -0.40 floors without changing hosted support', () => { + const { divider, walls, slabs, nodes } = floorStepFixture() + const support = computeWallSlabSupport(divider, slabs, walls, undefined, undefined, 0, nodes) + expect(support.faceDatum).toEqual({ + a: [{ start: 0, end: 1, elevation: 0.05 }], + b: [{ start: 0, end: 1, elevation: -0.4 }], + }) + const legacy = computeWallSlabSupport( + divider, + slabs, + walls, + undefined, + undefined, + 0, + Object.fromEntries( + Object.entries(nodes).map(([id, node]) => [ + id, + node.type === 'zone' ? { ...node, spaceRole: 'generic' } : node, + ]), + ), + ) + expect(support.elevation).toBe(0.05) + expect(support.baseElevation).toBe(legacy.baseElevation) + expect(support.baseSegments).toEqual(legacy.baseSegments) + const again = computeWallSlabSupport(divider, slabs, walls, undefined, undefined, 0, nodes) + expect(computeWallSlabSupport(divider, slabs, walls, undefined, undefined, 0, nodes)).toBe(again) +}) + +test('one wall face changes floor at the topology span station', () => { + const { walls, slabs, nodes } = floorStepFixture() + const support = computeWallSlabSupport(walls[0]!, slabs, walls, undefined, undefined, 0, nodes) + expect(support.faceDatum.a).toEqual([ + { start: 0, end: 0.5, elevation: 0.05 }, + { start: 0.5, end: 1, elevation: -0.4 }, + ]) +}) + +test('plate riser is hidden under the wall and exposed only under its floor opening', () => { + const { walls, zones, slabs, door } = floorStepFixture() + const context = { walls, zones, slabs } + const plate = slabs[0]! + const closed = computePlateSurfacePartition(plate, context)! + expect(classifyPlateSideAt(closed, [4.1, 2])).toBe('hidden') + const opened = computePlateSurfacePartition(plate, { ...context, openings: [door] })! + expect(plateSideRuns(opened, [4.1, 0.2], [4.1, 3.8]).map((run) => run.role)).toEqual([ + 'hidden', + 'riser', + 'hidden', + ]) + expect(classifyPlateSideAt(opened, [4.1, 2])).toBe('riser') + expect(classifyPlateSideAt(opened, [4.1, 1])).toBe('hidden') + const raised = computePlateSurfacePartition(plate, { + ...context, + openings: [{ ...door, position: [2, 2, 0] }], + })! + expect(classifyPlateSideAt(raised, [4.1, 2])).toBe('hidden') +}) + +test('a separator between different room floors exposes the step', () => { + const { walls, zones, slabs } = floorStepFixture(true) + const partition = computePlateSurfacePartition(slabs[0]!, { walls, zones, slabs })! + expect(classifyPlateSideAt(partition, [4, 2])).toBe('riser') +}) + +test('room face bases are lazy and cached without changing the enumerable support contract', () => { + const { divider, walls, slabs, nodes } = floorStepFixture() + let scans = 0 + const tracked = new Proxy(nodes, { + ownKeys(target) { + scans++ + return Reflect.ownKeys(target) + }, + }) + const support = computeWallSlabSupport(divider, slabs, walls, undefined, undefined, 0, tracked) + expect(support.elevation).toBe(0.05) + expect(Object.keys({ ...support })).not.toContain('faceBase') + expect(scans).toBe(0) + const bases = support.faceDatum + expect(scans).toBeGreaterThan(0) + const roomScans = scans + expect(support.faceDatum).toBe(bases) + expect(scans).toBe(roomScans) + // The first exterior face initializes terrain lookup; room-only queries do not. + expect( + computeWallSlabSupport(walls[0]!, slabs, walls, undefined, undefined, 0, tracked).faceDatum, + ).toBeDefined() + const after = scans + for (const wall of walls) + expect( + computeWallSlabSupport(wall, slabs, walls, undefined, undefined, 0, tracked).faceDatum, + ).toBeDefined() + expect(scans).toBe(after) +}) + +test('room floors cannot lift wall faces over a stair hole above their elected bases', () => { + const fixture = floorStepFixture() + const hole: [number, number][] = [ + [3, 1], + [5, 1], + [5, 3], + [3, 3], + ] + const slabs = fixture.slabs.map((slab) => ({ ...slab, elevation: 0.05, holes: [hole] })) + const nodes = { ...fixture.nodes, ...Object.fromEntries(slabs.map((slab) => [slab.id, slab])) } + const support = computeWallSlabSupport( + fixture.divider, + slabs, + fixture.walls, + undefined, + undefined, + 0, + nodes, + ) + for (const face of ['a', 'b'] as const) { + expect( + support.faceDatum[face].find((span) => span.start <= 0.5 && span.end > 0.5)?.elevation, + ).toBe(0) + expect(support.faceDatum[face][0]!.elevation).toBe(0.05) + } +}) + +test('facade slab edges remain explicit at equal elevations and on upper storeys', () => { + const { walls, zones, slabs } = floorStepFixture() + for (const elevation of [0.05, 3.05]) { + const equal = slabs.map((slab) => ({ + ...slab, + elevation, + thickness: 0.05, + plateRole: 'base' as const, + })) + const partition = computePlateSurfacePartition(equal[0]!, { walls, zones, slabs: equal })! + expect(classifyPlateSideAt(partition, [2, -0.1])).toBe('edge') + expect(classifyPlateSideAt(partition, [4.1, 2])).toBe('hidden') + expect( + partition.sides.some( + (side) => side.role === 'edge' && side.start[1] === -0.1 && side.end[1] === -0.1, + ), + ).toBe(true) + } +}) + +test('room and separator edits dirty wall bodies on their level', async () => { + const { initSpatialGridSync } = await import('../../hooks/spatial-grid/spatial-grid-sync') + const { spatialGridManager } = await import('../../hooks/spatial-grid/spatial-grid-manager') + const { default: useScene } = await import('../../store/use-scene') + const { walls, zones, boundary, nodes } = floorStepFixture(true) + const original = useScene.getState() + useScene.setState({ nodes, dirtyNodes: new Set() }) + const unsubscribe = initSpatialGridSync() + try { + const zone = zones[0]! + for (const patch of [ + { floor: { elevation: -0.8 } }, + { hasFloor: false as const }, + { polygon: zone.polygon.map(([x, y]) => [x + 0.01, y] as [number, number]) }, + { boundaryWallIds: walls.map((wall) => wall.id) }, + { boundarySeparatorIds: [boundary.id] }, + ]) { + useScene.setState({ dirtyNodes: new Set() }) + useScene.setState({ nodes: { ...nodes, [zone.id]: { ...zone, ...patch } } }) + for (const wall of walls) expect(useScene.getState().dirtyNodes.has(wall.id)).toBe(true) + } + useScene.setState({ dirtyNodes: new Set() }) + useScene.setState({ nodes: { ...nodes, [boundary.id]: { ...boundary, end: [4, 3] } } }) + for (const wall of walls) expect(useScene.getState().dirtyNodes.has(wall.id)).toBe(true) + const removed = { ...nodes } + delete removed[boundary.id] + useScene.setState({ dirtyNodes: new Set() }) + useScene.setState({ nodes: removed }) + for (const wall of walls) expect(useScene.getState().dirtyNodes.has(wall.id)).toBe(true) + } finally { + unsubscribe() + spatialGridManager.clear() + useScene.setState(original) + } +}) diff --git a/packages/core/src/systems/slab/platform-audit.test.ts b/packages/core/src/systems/slab/platform-audit.test.ts new file mode 100644 index 0000000000..b58b326b20 --- /dev/null +++ b/packages/core/src/systems/slab/platform-audit.test.ts @@ -0,0 +1,107 @@ +import { expect, test } from 'bun:test' +import { spatialGridManager } from '../../hooks/spatial-grid/spatial-grid-manager' +import { + initSpatialGridSync, + markTerrainSupportDependents, +} from '../../hooks/spatial-grid/spatial-grid-sync' +import { encodeTerrainField } from '../../lib/terrain-codec' +import { createTerrainField } from '../../lib/terrain-field' +import { levelBaseElevationAt, noteLevelBaseConsumer } from '../../lib/terrain-support' +import { nodeLevelFrame } from '../../procedural-items/query' +import { WallNode } from '../../schema' +import useLiveTerrain from '../../store/use-live-terrain' +import useScene from '../../store/use-scene' +import { raisedRoomFixture } from './__fixtures__/raised-room' +import { computeWallSlabSupport } from './slab-support' + +for (const elevation of [0.05, 0.6]) + test(`terrain dirties only platform plates and adjacent walls: floor=${elevation}`, () => { + const fixture = raisedRoomFixture() + const slabs = fixture.slabs.map((slab) => ({ ...slab, elevation })) + const remote = WallNode.parse({ + id: 'wall_remote', + parentId: fixture.level.id, + start: [20, 0], + end: [25, 0], + }) + const nodes = { + ...fixture.nodes, + [remote.id]: remote, + ...Object.fromEntries(slabs.map((slab) => [slab.id, slab])), + } + noteLevelBaseConsumer('slab') + const dirty = new Set() + markTerrainSupportDependents(nodes, (id) => dirty.add(id)) + expect([...dirty].sort()).toEqual( + elevation > 0.05 ? [...fixture.walls.map((wall) => wall.id), slabs[0]!.id].sort() : [], + ) + }) + +test('flush plate and face support stays cached and above a terrain depression', () => { + const fixture = raisedRoomFixture() + const slab = { ...fixture.slabs[0]!, elevation: 0.05 } + const field = createTerrainField({ origin: [-1, -1], cols: 12, rows: 8, spacing: 1 }) + field.heights.fill(-40) + const nodes = { + ...fixture.nodes, + [slab.id]: slab, + [fixture.site.id]: { ...fixture.site, terrain: encodeTerrainField(field) }, + } + const original = useScene.getState() + useScene.setState({ nodes, dirtyNodes: new Set() }) + spatialGridManager.clear() + const stop = initSpatialGridSync() + const wall = fixture.walls[0]! + const support = () => + spatialGridManager.getSlabSupportForWall( + fixture.level.id, + wall.start, + wall.end, + 0, + wall.thickness, + ) + try { + const before = support() + expect(before.faceDatum.a).toEqual([{ start: 0, end: 1, elevation: 0.05 }]) + expect(before.faceDatum.b).toEqual(before.faceDatum.a) + useScene.setState({ dirtyNodes: new Set() }) + // Change terrain away from this wall's election anchor. + const changed = { ...field, heights: field.heights.slice() } + changed.heights[30] = -50 + useLiveTerrain.getState().begin(fixture.site.id, changed) + expect(useScene.getState().dirtyNodes.size).toBe(0) + expect(support()).toBe(before) + } finally { + stop() + useLiveTerrain.getState().end(fixture.site.id) + spatialGridManager.clear() + useScene.setState(original) + } +}) + +test('sunken exterior faces use the ground profile on a sculpted site', () => { + const { nodes, slabs, walls } = raisedRoomFixture(false, true) + const sunken = slabs.map((slab) => ({ ...slab, elevation: -0.4 })) + const support = computeWallSlabSupport(walls[0]!, sunken, walls, undefined, undefined, 0, nodes) + expect(support.faceDatum.a).toEqual([{ start: 0, end: 1, elevation: -0.4 }]) + expect(support.faceDatum.b).toEqual([{ start: 0, end: 1, elevation: 0.12, endElevation: 0.28 }]) +}) + +test('procedural spatial queries use the supplied snapshot rather than a live terrain stroke', () => { + const fixture = raisedRoomFixture(false, true) + const wall = fixture.walls[0]! + const nodes = Object.fromEntries( + Object.entries(fixture.nodes).filter(([, node]) => node.type !== 'slab'), + ) + const before = nodeLevelFrame(wall.id, nodes) + const live = createTerrainField({ origin: [-1, -1], cols: 12, rows: 8, spacing: 1 }) + live.heights.fill(80) + try { + useLiveTerrain.getState().begin(fixture.site.id, live) + expect(levelBaseElevationAt(nodes, fixture.level.id, 0, 0)).toBe(0.8) + expect(nodeLevelFrame(wall.id, nodes)).toEqual(before) + expect(before.position[1]).toBeCloseTo(0.12) + } finally { + useLiveTerrain.getState().end(fixture.site.id) + } +}) diff --git a/packages/core/src/systems/slab/raised-room.test.ts b/packages/core/src/systems/slab/raised-room.test.ts new file mode 100644 index 0000000000..38186c087a --- /dev/null +++ b/packages/core/src/systems/slab/raised-room.test.ts @@ -0,0 +1,109 @@ +import { expect, test } from 'bun:test' +import { levelBaseElevationAt } from '../../lib/terrain-support-query' +import { getWallCurveFrameAt } from '../wall/wall-curve' +import { getWallFaceOffsets } from '../wall/wall-frame' +import { resolveWallTop } from '../wall/wall-top' +import { raisedRoomFixture } from './__fixtures__/raised-room' +import { computeWallSlabSupport } from './slab-support' + +test('raised room has a 0.6 inner face and a grounded outer face without changing hosted support', () => { + const { walls, slabs, nodes } = raisedRoomFixture() + for (const wall of walls) { + const support = computeWallSlabSupport(wall, slabs, walls, undefined, undefined, 0, nodes) + expect(support.faceDatum).toEqual({ + a: [{ start: 0, end: 1, elevation: 0.6 }], + b: [{ start: 0, end: 1, elevation: 0 }], + }) + expect(support.elevation).toBe(0.6) + expect(support.baseSegments).toEqual([{ start: 0, end: 1, elevation: 0.6 }]) + expect(resolveWallTop(wall, 3, support.elevation)).toBe(3) + expect(resolveWallTop({ ...wall, height: 2.5 }, 3, support.elevation)).toBe(3.1) + } +}) + +test('raised and ground rooms keep independent 0.6 and 0.05 shared-wall faces', () => { + const { divider, walls, slabs, nodes } = raisedRoomFixture(true) + const support = computeWallSlabSupport(divider, slabs, walls, undefined, undefined, 0, nodes) + expect(support.faceDatum).toEqual({ + a: [{ start: 0, end: 1, elevation: 0.6 }], + b: [{ start: 0, end: 1, elevation: 0.05 }], + }) +}) + +test('raised room exterior faces sample terrain independently of the room floor', () => { + const { walls, slabs, nodes, level } = raisedRoomFixture(false, true) + for (const wall of walls) { + const support = computeWallSlabSupport(wall, slabs, walls, undefined, undefined, 0, nodes) + for (const span of support.faceDatum.b) + for (const t of [span.start, span.end]) { + const frame = getWallCurveFrameAt(wall, t) + const offset = getWallFaceOffsets(wall).b + const ground = levelBaseElevationAt( + nodes, + level.id, + frame.point.x + offset * frame.normal.x, + frame.point.y + offset * frame.normal.y, + ) + expect( + t === span.start ? span.elevation : (span.endElevation ?? span.elevation), + ).toBeCloseTo(ground) + } + } +}) + +test('setZoneIntent raises the reconciled floor without moving wall tops or exterior support', async () => { + const { setZoneIntent } = await import('../../commands/structure/set-zone-intent') + const { applyToScratch, structureChangeBatch } = await import('../../commands/structure/shared') + const { reconcileSceneStructure } = await import('../../lib/structure-reconcile') + const { spatialGridManager } = await import('../../hooks/spatial-grid/spatial-grid-manager') + const { default: useScene } = await import('../../store/use-scene') + const fixture = raisedRoomFixture() + let sequence = 0 + const mintId = (kind: string) => `${kind}_platform_${sequence++}` + const nodes = Object.fromEntries( + Object.values(fixture.nodes).map((node) => [ + node.id, + node.type === 'slab' + ? { ...node, elevation: 0.05 } + : node.type === 'zone' + ? { ...node, floor: { elevation: 0.05 } } + : node, + ]), + ) + const before = reconcileSceneStructure({ nodes, mintId }).nodes + const zone = Object.values(before).find((node) => node.type === 'zone')! + const plan = setZoneIntent(before, { zoneId: zone.id, patch: { floor: { elevation: 0.6 } } }) + const edited = applyToScratch(before, structureChangeBatch(plan.changes)) + const after = reconcileSceneStructure({ nodes: edited, previousNodes: before, mintId }).nodes + const original = useScene.getState() + useScene.setState({ nodes: after }) + spatialGridManager.clear() + try { + for (const node of Object.values(after)) + spatialGridManager.handleNodeCreated(node, fixture.level.id) + const plate = Object.values(after).find( + (node) => node.type === 'slab' && node.plateRole === 'platform', + )! + expect(plate.type === 'slab' && plate.elevation).toBe(0.6) + expect(plate.type === 'slab' && plate.thickness).toBeCloseTo(0.55) + for (const wall of fixture.walls) { + expect(after[wall.id]).toEqual(before[wall.id]) + const support = spatialGridManager.getSlabSupportForWall( + fixture.level.id, + wall.start, + wall.end, + 0, + wall.thickness, + ) + expect(support.elevation).toBe(0.05) + expect(support.faceDatum.a).toEqual([{ start: 0, end: 1, elevation: 0.6 }]) + expect(support.faceDatum.b).toEqual([{ start: 0, end: 1, elevation: 0.05 }]) + expect(resolveWallTop(wall, 3, support.elevation)).toBe(3) + } + for (const node of Object.values(before)) + if (node.type === 'ceiling') expect(after[node.id]).toEqual(node) + } finally { + spatialGridManager.clear() + useScene.setState(original) + } +}) diff --git a/packages/core/src/systems/slab/slab-support.ts b/packages/core/src/systems/slab/slab-support.ts index 85e4a1c0b6..0e0c92601c 100644 --- a/packages/core/src/systems/slab/slab-support.ts +++ b/packages/core/src/systems/slab/slab-support.ts @@ -1,7 +1,16 @@ -import { getRenderableSlabPolygon } from '../../lib/slab-polygon' -import type { SlabNode, WallNode } from '../../schema' +import { floorConstructionLift, liftedManualSlab } from '../../lib/floor-construction-lift' +import { floorRoomFaces, roomPolygonKey } from '../../lib/floor-room-faces' +import { area, intersection, type MultiPolygon, union } from '../../lib/polygon-boolean' +import { + getRenderableSlabPolygon, + prepareSlabPolygonContext, + scopeSlabPolygonContext, +} from '../../lib/slab-polygon' +import { levelBaseElevationAt } from '../../lib/terrain-support-query' +import type { AnyNode, SeparatorNode, SlabNode, WallNode, ZoneNode } from '../../schema' import { getWallCurveFrameAt, isCurvedWall } from '../wall/wall-curve' import { DEFAULT_WALL_THICKNESS } from '../wall/wall-footprint' +import { getWallFaceOffsets, type WallJustification } from '../wall/wall-frame' import { MIN_WALL_HEIGHT } from '../wall/wall-top' export type SlabElevationClamp = { @@ -15,7 +24,7 @@ export type SlabElevationClamp = { * rises past `storeyHeight - MIN_WALL_HEIGHT` while electing as that * wall's base would squeeze the wall body below its minimum (and at the * plane, to nothing). Walls with explicit heights don't constrain — their - * top rides the elected base, not the plane. Negative proposals (the + * top is an explicit level-local height rather than the storey plane. Negative proposals (the * drag-through-zero path that commits the `recessed` intent) pass * through untouched: this is a purely numeric upper bound. * @@ -30,6 +39,7 @@ export function clampSlabElevationForWalls( levelWalls: WallNode[], levelSlabs: readonly SlabNode[], storeyHeight: number, + nodes?: Readonly>, ): SlabElevationClamp { const bound = storeyHeight - MIN_WALL_HEIGHT if (proposedElevation <= bound) return { elevation: proposedElevation, clamped: false } @@ -48,11 +58,20 @@ export function clampSlabElevationForWalls( end: wall.end, curveOffset: wall.curveOffset, thickness: wall.thickness, + justification: wall.justification, } // Cheap pre-filter: a wall that never reaches the slab's footprint // can't elect it, whatever the election says about sibling slabs. if (!wallOverlapsPolygon(wallLike, slab.polygon)) continue - const support = computeWallSlabSupport(wallLike, substituted, levelWalls) + const support = computeWallSlabSupport( + wallLike, + substituted, + levelWalls, + undefined, + undefined, + 0, + nodes, + ) if (Math.abs(support.elevation - proposedElevation) <= WALL_SLAB_ELEVATION_POOL_EPSILON) { return { elevation: bound, clamped: true } } @@ -72,10 +91,12 @@ export function getSlabElevationUpperBound( levelWalls: WallNode[], levelSlabs: readonly SlabNode[], storeyHeight: number, + nodes?: Readonly>, ): number { const probe = Math.max(storeyHeight, ...levelSlabs.map((candidate) => candidate.elevation ?? 0.05)) + 1 - return clampSlabElevationForWalls(probe, slab, levelWalls, levelSlabs, storeyHeight).clamped + return clampSlabElevationForWalls(probe, slab, levelWalls, levelSlabs, storeyHeight, nodes) + .clamped ? storeyHeight - MIN_WALL_HEIGHT : Number.POSITIVE_INFINITY } @@ -274,6 +295,8 @@ export type WallOverlapInput = { end: [number, number] curveOffset?: number thickness?: number + justification?: WallJustification + supportOffset?: number } // Minimum length of wall that must lie on/inside a slab polygon before the @@ -292,9 +315,13 @@ function wallTestPolylines( start: [number, number], end: [number, number], curveOffset: number, - halfThickness: number, + wall: WallOverlapInput, ): Array> { const wallLike = { start, end, curveOffset } + const { a, b } = getWallFaceOffsets({ + ...wall, + thickness: Math.max(wall.thickness ?? DEFAULT_WALL_THICKNESS, 0), + }) if (curveOffset !== 0 && isCurvedWall(wallLike)) { const count = 16 const center: Array<{ x: number; y: number }> = [] @@ -304,15 +331,15 @@ function wallTestPolylines( const frame = getWallCurveFrameAt(wallLike, i / count) center.push(frame.point) left.push({ - x: frame.point.x + frame.normal.x * halfThickness, - y: frame.point.y + frame.normal.y * halfThickness, + x: frame.point.x + frame.normal.x * a, + y: frame.point.y + frame.normal.y * a, }) right.push({ - x: frame.point.x - frame.normal.x * halfThickness, - y: frame.point.y - frame.normal.y * halfThickness, + x: frame.point.x - frame.normal.x * -b, + y: frame.point.y - frame.normal.y * -b, }) } - return halfThickness > 0 ? [center, left, right] : [center] + return a - b > 0 ? [center, left, right] : [center] } const center = [ @@ -322,9 +349,11 @@ function wallTestPolylines( const dx = end[0] - start[0] const dz = end[1] - start[1] const len = Math.hypot(dx, dz) - if (len < 1e-10 || halfThickness <= 0) return [center] - const nx = (-dz / len) * halfThickness - const nz = (dx / len) * halfThickness + if (len < 1e-10 || a - b <= 0) return [center] + const nx = (-dz / len) * a + const nz = (dx / len) * a + const rx = (-dz / len) * -b + const rz = (dx / len) * -b return [ center, [ @@ -332,8 +361,8 @@ function wallTestPolylines( { x: end[0] + nx, y: end[1] + nz }, ], [ - { x: start[0] - nx, y: start[1] - nz }, - { x: end[0] - nx, y: end[1] - nz }, + { x: start[0] - rx, y: start[1] - rz }, + { x: end[0] - rx, y: end[1] - rz }, ], ] } @@ -365,6 +394,7 @@ export function wallOverlapsPolygon( let polygon: Array<[number, number]> let curveOffset = 0 let thickness = DEFAULT_WALL_THICKNESS + let justification: WallJustification | undefined if (Array.isArray(startOrWall)) { start = startOrWall as [number, number] end = endOrPolygon as [number, number] @@ -374,9 +404,10 @@ export function wallOverlapsPolygon( end = startOrWall.end curveOffset = startOrWall.curveOffset ?? 0 thickness = startOrWall.thickness ?? DEFAULT_WALL_THICKNESS + justification = startOrWall.justification polygon = endOrPolygon as Array<[number, number]> } - return wallOverlapsSlabFootprint({ start, end, curveOffset, thickness }, polygon) + return wallOverlapsSlabFootprint({ start, end, curveOffset, thickness, justification }, polygon) } /** @@ -392,10 +423,9 @@ export function wallOverlapsSlabFootprint( polygon: Array<[number, number]>, holes?: ReadonlyArray>, ): boolean { - const { start, end, curveOffset = 0, thickness = DEFAULT_WALL_THICKNESS } = wallLike - const halfThickness = Math.max(thickness / 2, 0) + const { start, end, curveOffset = 0 } = wallLike - const polylines = wallTestPolylines(start, end, curveOffset, halfThickness) + const polylines = wallTestPolylines(start, end, curveOffset, wallLike) const centerLength = polylineLength(polylines[0]!) if (centerLength < 1e-9) return false @@ -448,6 +478,10 @@ const WALL_SLAB_ELEVATION_POOL_EPSILON = 1e-4 * than `WALL_SLAB_MIN_OVERLAP` of the wall is ignored entirely (point * contact, endpoint grazes). * + * Auto plates use their zones' reference footprints from `nodes` before this + * adoption step; their full stored wall coverage must not own both wall faces. + * Pass the scene snapshot when querying plates. + * * Same-elevation slabs pool their coverage. `elevation` is elected from * the wall's carrying profile: per arc segment, the highest support on * each face, then the min across supported faces — so a slab that only @@ -472,12 +506,17 @@ export type WallSlabSupport = { baseElevation: number /** Piecewise bottom elevation along the wall centerline, in normalized arc-length units. */ baseSegments: WallSlabSupportSegment[] + /** Room-facing bottoms; independent of the hosted-child support datum. */ + faceDatum: { a: WallSlabSupportSegment[]; b: WallSlabSupportSegment[] } + faceBottom: { a: WallSlabSupportSegment[]; b: WallSlabSupportSegment[] } } export type WallSlabSupportSegment = { start: number end: number elevation: number + /** Terrain runs interpolate linearly; omitted for flat room/support spans. */ + endElevation?: number } /** @@ -510,6 +549,10 @@ export type WallSlabSupportSegment = { * recessed slab up to `0` so a wall over a pool didn't sink — generalizes to * "never below the ground", which is the same rule with the ground no longer * assumed flat. + * + * `baseAt` optionally supplies the live level-base sampler for geometry face + * profiles. The spatial grid keeps it stable until its support inputs change; + * pure callers default to persisted terrain from `nodes`. */ // A rendered slab polygon depends only on the slab set and the level's walls, // never on the wall being tested — but a per-frame pass asks for support once @@ -519,27 +562,237 @@ export type WallSlabSupportSegment = { // live preview changes, so a hit means the inputs are the same objects. let polygonMemoSlabs: readonly SlabNode[] | null = null let polygonMemoWalls: readonly WallNode[] | null = null -let polygonMemo = new Map>() +let polygonMemoNodes: Readonly> | undefined +const polygonSets = new Map< + string, + { + polygons: Map + slabs: SlabNode[] + prepared: ReturnType + } +>() +let polygonMemo = new Map() +let supportSlabs: SlabNode[] = [] +let preparedPolygons: ReturnType function renderedSlabPolygon( slab: SlabNode, slabs: readonly SlabNode[], levelWalls: WallNode[], -): Array<[number, number]> { - if (polygonMemoSlabs !== slabs || polygonMemoWalls !== levelWalls) { + nodes?: Readonly>, +): MultiPolygon { + if (polygonMemoSlabs !== slabs || polygonMemoWalls !== levelWalls || polygonMemoNodes !== nodes) { polygonMemoSlabs = slabs polygonMemoWalls = levelWalls - polygonMemo = new Map() + polygonMemoNodes = nodes + const signature = JSON.stringify([ + slabs, + levelWalls.map((wall) => [ + wall.id, + wall.start, + wall.end, + wall.curveOffset, + wall.thickness, + wall.justification, + ]), + slabs.flatMap((slab) => + slab.boundary === 'auto' && !slab.plateRole + ? (slab.zoneIds ?? []).map((id) => { + const zone = nodes?.[id] + return zone?.type === 'zone' ? [id, zone.polygon, zone.holes] : id + }) + : [], + ), + ]) + const hit = polygonSets.get(signature) + if (hit) { + polygonMemo = hit.polygons + supportSlabs = hit.slabs + preparedPolygons = hit.prepared + } else { + polygonMemo = new Map() + supportSlabs = slabs.flatMap((source) => { + if ( + source.support === 'open' || + source.plateRole === 'platform' || + source.plateRole === 'sunken' + ) + return [] + if (source.plateRole === 'base') return [source] + const zones = + source.boundary === 'auto' + ? (source.zoneIds ?? []).flatMap((id) => { + const zone = nodes?.[id] + return zone?.type === 'zone' + ? [{ outer: zone.polygon, holes: zone.holes ?? [] }] + : [] + }) + : [] + if (!zones.length) return [source] + return intersection({ outer: source.polygon, holes: source.holes ?? [] }, union(zones)).map( + (part) => ({ + ...source, + boundary: undefined, + polygon: part.outer, + holes: part.holes, + }), + ) + }) + preparedPolygons = prepareSlabPolygonContext({ + walls: levelWalls, + siblingSlabs: supportSlabs, + }) + if (polygonSets.size >= 64) polygonSets.delete(polygonSets.keys().next().value!) + polygonSets.set(signature, { + polygons: polygonMemo, + slabs: supportSlabs, + prepared: preparedPolygons, + }) + } } const cached = polygonMemo.get(slab.id) if (cached) return cached + if (slab.plateRole === 'base') { + const polygon = [{ outer: slab.polygon, holes: slab.holes ?? [] }] + polygonMemo.set(slab.id, polygon) + return polygon + } + // Keep the pre-plate face/seam election. Full wall coverage belongs to rendering. + const polygons = supportSlabs + .filter((source) => source.id === slab.id) + .map((source) => ({ + outer: getRenderableSlabPolygon(source, scopeSlabPolygonContext(source, preparedPolygons)), + holes: source.holes ?? [], + })) + polygonMemo.set(slab.id, polygons) + return polygons +} - const polygon = getRenderableSlabPolygon(slab, { - walls: levelWalls, - siblingSlabs: slabs.filter((other) => other.id !== slab.id), - }) - polygonMemo.set(slab.id, polygon) - return polygon +function appendBaseSegment( + segments: WallSlabSupportSegment[], + start: number, + end: number, + elevation: number, +) { + const previous = segments.at(-1) + if ( + previous && + previous.endElevation === undefined && + Math.abs(previous.elevation - elevation) <= WALL_SLAB_ELEVATION_POOL_EPSILON + ) + previous.end = end + else segments.push({ start, end, elevation }) +} + +type RoomFaceBases = Record<'a' | 'b', Array> + +type SupportMemo = { + slabs: readonly SlabNode[] + nodes: Readonly> | undefined + results: Map + terrainResults?: { revision: object; results: Map } + baseAt?: (x: number, z: number) => number + roomBases?: Map +} +const supportMemo = new WeakMap() + +function roomFaceBases( + slabs: readonly SlabNode[], + walls: WallNode[], + nodes: Readonly> | undefined, + memo: SupportMemo, +) { + if (memo.roomBases) return memo.roomBases + const result = new Map() + memo.roomBases = result + if (!nodes || !walls.length) return result + const levels = new Set(walls.map((wall) => wall.parentId)) + const zones = Object.values(nodes).filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.spaceRole === 'room' && + node.floor?.support !== 'open' && + levels.has(node.parentId), + ) + if (!zones.length) return result + const separators = Object.values(nodes).filter( + (node): node is SeparatorNode => node.type === 'separator' && levels.has(node.parentId), + ) + const exactZones = new Map( + [...zones] + .sort((a, b) => b.id.localeCompare(a.id)) + .map((zone) => [roomPolygonKey(zone.polygon, zone.holes), zone]), + ) + const zoneBounds = new Map( + zones.map((zone) => [zone.id, polygonBounds([{ outer: zone.polygon, holes: [] }])]), + ) + for (const room of floorRoomFaces([...walls, ...separators])) { + const polygon = { outer: room.referencePolygon, holes: room.holes } + const bounds = polygonBounds([polygon]) + const zone = + exactZones.get(roomPolygonKey(room.referencePolygon, room.holes)) ?? + zones + .filter((zone) => { + const other = zoneBounds.get(zone.id)! + return ( + bounds.minX < other.maxX && + other.minX < bounds.maxX && + bounds.minZ < other.maxZ && + other.minZ < bounds.maxZ + ) + }) + .map((zone) => ({ + zone, + overlap: area(intersection(polygon, { outer: zone.polygon, holes: zone.holes ?? [] })), + })) + .filter(({ overlap }) => overlap > 1e-6) + .sort((a, b) => b.overlap - a.overlap || a.zone.id.localeCompare(b.zone.id))[0]?.zone + if (!zone) continue + const plate = + slabs.find( + (slab) => + slab.boundary === 'auto' && slab.plateRole !== 'base' && slab.zoneIds?.includes(zone.id), + ) ?? slabs.find((slab) => slab.plateRole === 'base' && slab.zoneIds?.includes(zone.id)) + const elevation = plate + ? plate.plateRole + ? (zone.floor?.elevation ?? plate.elevation) + : plate.elevation + : undefined + if (elevation === undefined || zone.hasFloor === false) continue + for (const span of room.spans) { + const wall = walls.find((wall) => wall.id === span.boundaryId) + if (!wall) continue + // Topology stations are chord parameters; support profiles use arc parameters. + const station = (t: number) => { + if (!isCurvedWall(wall) || t <= 0 || t >= 1) return t + const dx = wall.end[0] - wall.start[0], + dz = wall.end[1] - wall.start[1] + let low = 0, + high = 1 + for (let i = 0; i < 40; i++) { + const mid = (low + high) / 2, + point = getWallCurveFrameAt(wall, mid).point + if ( + ((point.x - wall.start[0]) * dx + (point.y - wall.start[1]) * dz) / + (dx * dx + dz * dz) < + t + ) + low = mid + else high = mid + } + return (low + high) / 2 + } + const bases = result.get(wall.id) ?? { a: [], b: [] } + bases[span.face].push({ + start: station(span.t0), + end: station(span.t1), + elevation, + thickness: plate?.thickness ?? 0.05, + }) + result.set(wall.id, bases) + } + } + return result } export function computeWallSlabSupport( @@ -549,10 +802,134 @@ export function computeWallSlabSupport( preferredSlabId?: string | null, maxElevation?: number | null, levelBase = 0, + nodes?: Readonly>, + baseAt?: (x: number, z: number) => number, + terrainRevision?: object, ): WallSlabSupport { - const { start, end, curveOffset = 0, thickness = DEFAULT_WALL_THICKNESS } = wallLike - const halfThickness = Math.max(thickness / 2, 0) - const polylines = wallTestPolylines(start, end, curveOffset, halfThickness) + let memo = supportMemo.get(levelWalls) + if (!memo || memo.slabs !== slabs || memo.nodes !== nodes || memo.baseAt !== baseAt) { + memo = { slabs, nodes, baseAt, results: new Map() } + supportMemo.set(levelWalls, memo) + } + const key = JSON.stringify([ + wallLike.start, + wallLike.end, + wallLike.curveOffset, + wallLike.thickness, + wallLike.justification, + wallLike.supportOffset, + preferredSlabId, + maxElevation, + levelBase, + ]) + if (terrainRevision && memo.terrainResults?.revision !== terrainRevision) + memo.terrainResults = { revision: terrainRevision, results: new Map() } + const results = terrainRevision ? memo.terrainResults!.results : memo.results + const cached = results.get(key) + if (cached) return cached + let support = computeWallSlabSupportUncached( + memo, + wallLike, + slabs, + levelWalls, + preferredSlabId, + maxElevation, + levelBase, + nodes, + ) + const groundWall = + preferredSlabId === 'ground' && nodes && slabs.some((slab) => slab.plateRole === 'base') + ? levelWalls.find( + (wall) => + wall.start[0] === wallLike.start[0] && + wall.start[1] === wallLike.start[1] && + wall.end[0] === wallLike.end[0] && + wall.end[1] === wallLike.end[1], + ) + : undefined + const offset = + (wallLike.supportOffset ?? 0) + (groundWall ? floorConstructionLift(nodes!, groundWall) : 0) + if (offset || preferredSlabId === 'ground') { + const raw = support + const ground = preferredSlabId === 'ground' + const elevation = (ground ? levelBase : raw.elevation) + offset + const shift = (segments: readonly WallSlabSupportSegment[]) => + segments.map((run) => ({ + ...run, + elevation: run.elevation + offset, + ...(run.endElevation === undefined ? {} : { endElevation: run.endElevation + offset }), + })) + const baseSegments = ground ? [{ start: 0, end: 1, elevation }] : shift(raw.baseSegments) + const wall = levelWalls.find( + (wall) => + wall.start[0] === wallLike.start[0] && + wall.start[1] === wallLike.start[1] && + wall.end[0] === wallLike.end[0] && + wall.end[1] === wallLike.end[1], + ) + const rooms = + wall && slabs.some((slab) => slab.plateRole === 'base') + ? roomFaceBases(slabs, levelWalls, nodes, memo).get(wall.id) + : undefined + const datum = (face: 'a' | 'b') => + raw.faceDatum[face].map((run) => { + const room = rooms?.[face].find( + (room) => + room.start <= (run.start + run.end) / 2 && room.end >= (run.start + run.end) / 2, + ) + return room + ? { ...run, elevation: room.elevation, endElevation: undefined } + : ground + ? { ...run, elevation, endElevation: undefined } + : shift([run])[0]! + }) + const faceDatum = { a: datum('a'), b: datum('b') } + support = { + elevation, + electedSlabId: ground ? null : raw.electedSlabId, + baseElevation: Math.min(...baseSegments.map((run) => run.elevation)), + baseSegments, + faceDatum, + faceBottom: { + a: resolveWallFaceBottom(faceDatum.a, baseSegments, elevation), + b: resolveWallFaceBottom(faceDatum.b, baseSegments, elevation), + }, + } + } + if (results.size >= 512) results.clear() + results.set(key, support) + return support +} + +type SupportBounds = { minX: number; minZ: number; maxX: number; maxZ: number } +const supportBounds = new WeakMap() +function polygonBounds(polygon: MultiPolygon): SupportBounds { + const cached = supportBounds.get(polygon) + if (cached) return cached + const bounds = { minX: Infinity, minZ: Infinity, maxX: -Infinity, maxZ: -Infinity } + for (const part of polygon) + for (const [x, z] of part.outer) { + bounds.minX = Math.min(bounds.minX, x) + bounds.maxX = Math.max(bounds.maxX, x) + bounds.minZ = Math.min(bounds.minZ, z) + bounds.maxZ = Math.max(bounds.maxZ, z) + } + supportBounds.set(polygon, bounds) + return bounds +} + +function computeWallSlabSupportUncached( + memo: SupportMemo, + wallLike: WallOverlapInput, + slabs: readonly SlabNode[], + levelWalls: WallNode[], + preferredSlabId?: string | null, + maxElevation?: number | null, + levelBase = 0, + nodes?: Readonly>, +): WallSlabSupport { + const { start, end, curveOffset = 0 } = wallLike + const polylines = wallTestPolylines(start, end, curveOffset, wallLike) const polylineLengths = polylines.map(polylineLength) const wallLength = polylineLengths[0]! if (wallLength < 1e-9) { @@ -561,9 +938,18 @@ export function computeWallSlabSupport( electedSlabId: null, baseElevation: levelBase, baseSegments: [], + faceDatum: { a: [], b: [] }, + faceBottom: { a: [], b: [] }, } } + const points = polylines.flat() + const band = { + minX: Math.min(...points.map((point) => point.x)) - ON_BOUNDARY_EPSILON, + maxX: Math.max(...points.map((point) => point.x)) + ON_BOUNDARY_EPSILON, + minZ: Math.min(...points.map((point) => point.y)) - ON_BOUNDARY_EPSILON, + maxZ: Math.max(...points.map((point) => point.y)) + ON_BOUNDARY_EPSILON, + } const minSupport = Math.max(1e-3, Math.min(WALL_SLAB_MIN_OVERLAP, wallLength * 0.5)) type ElevationGroup = { @@ -576,23 +962,44 @@ export function computeWallSlabSupport( let preferredElectedSlabId: string | null = null for (const slab of slabs) { - if (slab.polygon.length < 3) continue - const renderedPolygon = renderedSlabPolygon(slab, slabs, levelWalls) + if ( + slab.support === 'open' || + ((slab.plateRole === 'platform' || slab.plateRole === 'sunken') && + slab.id !== preferredSlabId) || + slab.polygon.length < 3 + ) + continue + const renderedPolygon = renderedSlabPolygon(slab, slabs, levelWalls, nodes) + const bounds = polygonBounds(renderedPolygon) + if ( + bounds.minX > band.maxX || + bounds.maxX < band.minX || + bounds.minZ > band.maxZ || + bounds.maxZ < band.minZ + ) + continue let supported = 0 const perPolyline = polylines.map((line) => { - let intervals = polylineInsideIntervals(line, renderedPolygon) - for (const hole of slab.holes || []) { - if (intervals.length === 0) break - if (hole.length < 3) continue - intervals = subtractIntervals(intervals, polylineInsideIntervals(line, hole, false)) - } + const intervals = mergeIntervals( + renderedPolygon.flatMap(({ outer, holes }) => { + let covered = polylineInsideIntervals(line, outer) + for (const hole of holes) { + if (hole.length >= 3) + covered = subtractIntervals(covered, polylineInsideIntervals(line, hole, false)) + } + return covered + }), + ) supported = Math.max(supported, intervalsLength(intervals)) return intervals }) if (supported < minSupport) continue - const elevation = slab.elevation ?? 0.05 + const elevation = + nodes && slabs.some((slab) => slab.plateRole === 'base') + ? liftedManualSlab(nodes, slab).elevation + : (slab.elevation ?? 0.05) if (preferredSlabId != null && slab.id === preferredSlabId) { preferredElevation = elevation preferredElectedSlabId = slab.id @@ -668,6 +1075,7 @@ export function computeWallSlabSupport( (group) => group.elevation <= maxElevation + SUPPORT_ELEVATION_EPSILON, ) + const faceDatum: WallSlabSupport['faceDatum'] = { a: [], b: [] } const baseSegments: WallSlabSupportSegment[] = [] type CarryCandidate = { elevation: number; length: number } const carryCandidates: CarryCandidate[] = [] @@ -695,6 +1103,18 @@ export function computeWallSlabSupport( const segmentElevation = faceElevations.length > 0 ? Math.min(...faceElevations) : Math.max(centerElevation, levelBase) + for (const [face, value] of [ + ['a', leftElevation], + ['b', rightElevation], + ] as const) { + appendBaseSegment( + faceDatum[face], + start, + end, + Number.isFinite(value) ? value : segmentElevation, + ) + } + if (electableNormalizedGroups === normalizedByGroup) { if (faceElevations.length > 0 || Number.isFinite(centerElevation)) { accumulateCarry(segmentElevation, end - start) @@ -746,13 +1166,13 @@ export function computeWallSlabSupport( } const elevation = - preferredElevation !== null - ? preferredElevation - : majorityElevation !== Number.NEGATIVE_INFINITY - ? majorityElevation - : bestElevation === Number.NEGATIVE_INFINITY + preferredElevation === null + ? majorityElevation === Number.NEGATIVE_INFINITY + ? bestElevation === Number.NEGATIVE_INFINITY ? levelBase : bestElevation + : majorityElevation + : preferredElevation const electedSlabId = preferredElectedSlabId ?? evaluatedGroups @@ -767,13 +1187,168 @@ export function computeWallSlabSupport( if (baseSegments.length === 0) baseSegments.push({ start: 0, end: 1, elevation }) const baseElevation = Math.min(...baseSegments.map((segment) => segment.elevation)) - return { elevation, electedSlabId, baseElevation, baseSegments } + let resolvedFaceDatum: WallSlabSupport['faceDatum'] | undefined + const resolveFaceDatum = () => { + const wall = levelWalls.find( + (candidate) => + candidate.start[0] === start[0] && + candidate.start[1] === start[1] && + candidate.end[0] === end[0] && + candidate.end[1] === end[1] && + (candidate.curveOffset ?? 0) === curveOffset && + candidate.justification === wallLike.justification, + ) + const roomBases = wall ? roomFaceBases(slabs, levelWalls, nodes, memo).get(wall.id) : undefined + if (roomBases) + for (const face of ['a', 'b'] as const) { + const spans = roomBases[face] + const cuts = [ + ...new Set([ + 0, + 1, + ...faceDatum[face].flatMap((segment) => [segment.start, segment.end]), + ...spans.flatMap((segment) => [segment.start, segment.end]), + ...roomBases[face === 'a' ? 'b' : 'a'].flatMap((segment) => [ + segment.start, + segment.end, + ]), + ]), + ].sort((a, b) => a - b) + const result: WallSlabSupportSegment[] = [] + for (let i = 1; i < cuts.length; i++) { + const start = cuts[i - 1]!, + end = cuts[i]!, + mid = (start + end) / 2 + const room = spans.find((span) => span.start <= mid && mid < span.end) + const elected = faceDatum[face].find((span) => span.start <= mid && mid < span.end) + if (!elected) continue + const opposite = roomBases[face === 'a' ? 'b' : 'a'].find( + (span) => span.start <= mid && mid < span.end, + ) + const groundAt = (t: number) => { + const frame = getWallCurveFrameAt(wall!, t) + const offset = getWallFaceOffsets(wall!)[face] + const x = frame.point.x + frame.normal.x * offset + const z = frame.point.y + frame.normal.y * offset + if (memo.baseAt) return memo.baseAt(x, z) + return nodes && wall!.parentId && nodes[wall!.parentId] + ? levelBaseElevationAt(nodes, wall!.parentId, x, z) + : levelBase + } + // Raised and sunken rooms never carry their exterior face with them. + // A flush floor follows depressed terrain only when explicitly opted in. + const count = Math.max(1, Math.ceil(((end - start) * wallLength) / 0.25)) + const ground = + !slabs.some((slab) => slab.plateRole === 'base') && + !room && + opposite && + (opposite.elevation - opposite.thickness > 1e-4 || opposite.elevation < -1e-4) + ? Array.from({ length: count + 1 }, (_, i) => + groundAt(start + ((end - start) * i) / count), + ) + : [] + if (ground.length) { + for (let j = 0; j < count; j++) { + const from = start + ((end - start) * j) / count + const to = start + ((end - start) * (j + 1)) / count + const elevation = ground[j]!, + endElevation = ground[j + 1]! + if (Math.abs(elevation - endElevation) < 1e-6) + appendBaseSegment(result, from, to, elevation) + else { + const previous = result.at(-1) + if ( + previous?.endElevation !== undefined && + Math.abs(previous.endElevation - elevation) < 1e-6 && + Math.abs( + (previous.endElevation - previous.elevation) / (previous.end - previous.start) - + (endElevation - elevation) / (to - from), + ) < 1e-6 + ) { + previous.end = to + previous.endElevation = endElevation + } else result.push({ start: from, end: to, elevation, endElevation }) + } + } + } else + appendBaseSegment( + result, + start, + end, + slabs.some((slab) => slab.plateRole === 'base') + ? (room?.elevation ?? elected.elevation) + : Math.min(room?.elevation ?? elected.elevation, elected.elevation), + ) + } + faceDatum[face] = result + } + return faceDatum + } + let faceBottom: WallSlabSupport['faceBottom'] | undefined + const datum = () => (resolvedFaceDatum ??= resolveFaceDatum()) + const bottom = (segments: WallSlabSupportSegment[]) => + resolveWallFaceBottom(segments, baseSegments, elevation) + return Object.defineProperties( + { elevation, electedSlabId, baseElevation, baseSegments }, + { + faceDatum: { get: datum }, + faceBottom: { get: () => (faceBottom ??= { a: bottom(datum().a), b: bottom(datum().b) }) }, + }, + ) as WallSlabSupport } export function computeWallSlabElevation( wallLike: WallOverlapInput, slabs: readonly SlabNode[], levelWalls: WallNode[], + nodes?: Readonly>, ): number { - return computeWallSlabSupport(wallLike, slabs, levelWalls).elevation + return computeWallSlabSupport(wallLike, slabs, levelWalls, undefined, undefined, 0, nodes) + .elevation +} + +export function resolveWallFaceBottom( + datums: readonly WallSlabSupportSegment[], + support: readonly WallSlabSupportSegment[], + fallback: number, +): WallSlabSupportSegment[] { + const at = (run: WallSlabSupportSegment, t: number) => + run.elevation + + ((t - run.start) / (run.end - run.start)) * + ((run.endElevation ?? run.elevation) - run.elevation) + const cuts = [...new Set([...datums, ...support].flatMap((run) => [run.start, run.end]))].sort( + (a, b) => a - b, + ) + const result: WallSlabSupportSegment[] = [] + for (let i = 1; i < cuts.length; i++) { + const start = cuts[i - 1]!, + end = cuts[i]!, + mid = (start + end) / 2 + const datum = datums.find((run) => run.start <= mid && run.end >= mid) + if (!datum) continue + const carrier = support.find((run) => run.start <= mid && run.end >= mid) + const d0 = at(datum, start), + d1 = at(datum, end), + w0 = carrier ? at(carrier, start) : fallback, + w1 = carrier ? at(carrier, end) : fallback + const crossing = + (d0 - w0) * (d1 - w1) < 0 + ? start + ((end - start) * (w0 - d0)) / (d1 - d0 - w1 + w0) + : undefined + const pieces = crossing === undefined ? [start, end] : [start, crossing, end] + for (let j = 1; j < pieces.length; j++) { + const from = pieces[j - 1]!, + to = pieces[j]! + const height = (t: number) => Math.min(at(datum, t), carrier ? at(carrier, t) : fallback) + const elevation = height(from), + endElevation = height(to) + result.push({ + start: from, + end: to, + elevation, + ...(Math.abs(elevation - endElevation) < 1e-9 ? {} : { endElevation }), + }) + } + } + return result } diff --git a/packages/core/src/systems/stair/stair-base-elevation.ts b/packages/core/src/systems/stair/stair-base-elevation.ts new file mode 100644 index 0000000000..50eeb12d16 --- /dev/null +++ b/packages/core/src/systems/stair/stair-base-elevation.ts @@ -0,0 +1,61 @@ +import { GROUND_SUPPORT_ID } from '../../hooks/spatial-grid/support-host-id' +import { itemOverlapsPolygon } from '../../lib/item-polygon-overlap' +import { resolveLevelId } from '../../lib/node-ancestry' +import { getRenderableSlabPolygon } from '../../lib/slab-polygon' +import { levelBaseElevationAt } from '../../lib/terrain-support-query' +import type { AnyNode, SlabNode, StairNode, WallNode } from '../../schema' +import { pointInPolygon } from '../slab/slab-support' +import { getStairFloorPlacedFootprints } from './stair-floor-footprints' + +export function stairBaseElevation( + stair: StairNode, + nodes: Record, + levelId: string | null, +) { + const parent = stair.parentId ? nodes[stair.parentId] : undefined + if ((stair.parentId && !parent) || (parent && parent.type !== 'level')) return stair.position[1] + const level = parent?.type === 'level' ? parent.id : levelId + if (!level) return stair.position[1] + const ground = levelBaseElevationAt(nodes, level, stair.position[0], stair.position[2]) + if (stair.supportSlabId === GROUND_SUPPORT_ID) return stair.position[1] + ground + const slabs: SlabNode[] = [] + const walls: WallNode[] = [] + for (const node of Object.values(nodes)) { + if ((node.type !== 'slab' && node.type !== 'wall') || resolveLevelId(node, nodes) !== level) + continue + if (node.type === 'slab') slabs.push(node) + else walls.push(node) + } + const polygons = new Map( + slabs.map((slab) => [ + slab.id, + getRenderableSlabPolygon(slab, { + walls, + siblingSlabs: slabs.filter((other) => other.id !== slab.id), + }), + ]), + ) + const footprints = getStairFloorPlacedFootprints(stair, nodes) + const supports = (slab: SlabNode, footprint: (typeof footprints)[number]) => { + const position = footprint.position ?? stair.position + return ( + itemOverlapsPolygon( + position, + footprint.dimensions, + footprint.rotation, + polygons.get(slab.id)!, + 0.01, + ) && !(slab.holes ?? []).some((hole) => pointInPolygon(position[0], position[2], hole)) + ) + } + const elevation = (slab: SlabNode) => + Number.isFinite(slab.elevation ?? 0.05) ? (slab.elevation ?? 0.05) : 0 + const host = slabs.find((slab) => slab.id === stair.supportSlabId) + if (host && footprints.some((footprint) => supports(host, footprint))) + return stair.position[1] + elevation(host) + const lifts = footprints.map((footprint) => { + const supported = slabs.filter((slab) => supports(slab, footprint)) + return supported.length ? Math.max(...supported.map(elevation)) : ground + }) + return stair.position[1] + (lifts.length ? Math.max(...lifts) : ground) +} diff --git a/packages/nodes/src/stair/floor-stack.ts b/packages/core/src/systems/stair/stair-floor-footprints.ts similarity index 93% rename from packages/nodes/src/stair/floor-stack.ts rename to packages/core/src/systems/stair/stair-floor-footprints.ts index 85c5a335f7..5a86ee72c7 100644 --- a/packages/nodes/src/stair/floor-stack.ts +++ b/packages/core/src/systems/stair/stair-floor-footprints.ts @@ -1,10 +1,5 @@ -import type { - AnyNode, - AnyNodeId, - FloorPlacedFootprint, - StairNode, - StairSegmentNode, -} from '@pascal-app/core' +import type { FloorPlacedFootprint } from '../../registry/types' +import type { AnyNode, AnyNodeId, StairNode, StairSegmentNode } from '../../schema' type SegmentTransform = { position: [number, number, number] @@ -49,13 +44,13 @@ function getArcStairFloorPlacedFootprints(stair: StairNode): FloorPlacedFootprin const [offsetX, offsetZ] = rotateXZ( Math.cos(midAngle) * centerRadius, Math.sin(midAngle) * centerRadius, - stair.rotation, + stair.rotation ?? 0, ) footprints.push({ position: [stair.position[0] + offsetX, stair.position[1], stair.position[2] + offsetZ], dimensions: [Math.max(radialSize, 0.01), 0.01, Math.max(tangentialSize, 0.01)], - rotation: [0, midAngle - stair.rotation, 0], + rotation: [0, midAngle - (stair.rotation ?? 0), 0], }) } @@ -85,7 +80,7 @@ export function getStairSegmentFloorPlacedFootprints( const [centerOffsetWorldX, centerOffsetWorldZ] = rotateXZ( centerInGroupX, centerInGroupZ, - stair.rotation, + stair.rotation ?? 0, ) return { @@ -99,7 +94,7 @@ export function getStairSegmentFloorPlacedFootprints( Math.max(segment.height, segment.thickness, 0.01), segment.length, ], - rotation: [0, stair.rotation + transform.rotation, 0], + rotation: [0, (stair.rotation ?? 0) + transform.rotation, 0], } }) } diff --git a/packages/core/src/systems/stair/stair-footprint.ts b/packages/core/src/systems/stair/stair-footprint.ts index cf41533dac..c8ecdbabe1 100644 --- a/packages/core/src/systems/stair/stair-footprint.ts +++ b/packages/core/src/systems/stair/stair-footprint.ts @@ -221,3 +221,59 @@ export function stairFootprintAABB( } return arcStairAABB(stair) } + +export function stairArrivalOpening( + stair: StairNode, + nodes: Readonly>, +): [number, number][] { + let start: [number, number] + let end: [number, number] + if (stair.stairType === 'straight') { + const segments = stair.children + .map((id) => nodes[id]) + .filter( + (node): node is StairSegmentNode => + node?.type === 'stair-segment' && node.visible !== false, + ) + const segment = segments.at(-1) + const transform = computeSegmentTransforms(segments).at(-1) + if (!segment || !transform) return [] + const point = (x: number): [number, number] => { + const [dx, dz] = rotateXZ(x, segment.length, transform.rotation) + return [transform.position[0] + dx, transform.position[2] + dz] + } + start = point(-segment.width / 2) + end = point(segment.width / 2) + } else { + const spiral = stair.stairType === 'spiral' + const inner = Math.max(spiral ? 0.05 : 0.2, stair.innerRadius ?? (spiral ? 0.2 : 0.9)) + const sweep = stair.sweepAngle ?? (spiral ? Math.PI * 2 : Math.PI / 2) + const angle = sweep / 2 + (spiral ? getSpiralLandingSweep(stair, sweep) : 0) + const outer = inner + Math.max(stair.width ?? 1, 0.4) + start = [Math.cos(angle) * inner, Math.sin(angle) * inner] + end = [Math.cos(angle) * outer, Math.sin(angle) * outer] + } + // Straddle the arrival line so wall-face clipping and edge tolerances do not close the gap. + const length = Math.hypot(end[0] - start[0], end[1] - start[1]) + const nx = (-(end[1] - start[1]) / length) * 0.15 + const nz = ((end[0] - start[0]) / length) * 0.15 + return [ + [start[0] + nx, start[1] + nz], + [end[0] + nx, end[1] + nz], + [end[0] - nx, end[1] - nz], + [start[0] - nx, start[1] - nz], + ].map(([x, z]) => { + const [dx, dz] = rotateXZ(x!, z!, stair.rotation) + return [stair.position[0] + dx, stair.position[2] + dz] + }) +} + +export function stairDeckLevelId( + nodes: Readonly>, + node?: AnyNode, +): string | undefined { + const stair = node?.type === 'stair-segment' ? nodes[node.parentId ?? ''] : node + if (stair?.type !== 'stair' || !stair.deckSlabId) return undefined + const deck = nodes[stair.deckSlabId] + return deck?.type === 'slab' && deck.support === 'open' ? (deck.parentId ?? undefined) : undefined +} diff --git a/packages/core/src/systems/stair/stair-opening-movement.test.ts b/packages/core/src/systems/stair/stair-opening-movement.test.ts new file mode 100644 index 0000000000..638fb0f868 --- /dev/null +++ b/packages/core/src/systems/stair/stair-opening-movement.test.ts @@ -0,0 +1,141 @@ +import { expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + CeilingNode, + FloorOpeningNode, + LevelNode, + SlabNode, + StairNode, + StairSegmentNode, +} from '../../schema' +import { syncAutoStairOpenings } from './stair-opening-sync' +import { resolveStairTotalRise } from './stair-rise-query' + +test('a stair leaves an authored opening and its own slab and ceiling cuts return', () => { + const building = BuildingNode.parse({ id: 'building_stair_move' }) + const ground = LevelNode.parse({ id: 'level_stair_move_0', parentId: building.id, level: 0 }) + const upper = LevelNode.parse({ id: 'level_stair_move_1', parentId: building.id, level: 1 }) + const opening = FloorOpeningNode.parse({ + id: 'floor-opening_stair_move', + parentId: upper.id, + polygon: [ + [1, 0], + [3, 0], + [3, 3], + [1, 3], + ], + }) + const footprint: [number, number][] = [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ] + const ceiling = CeilingNode.parse({ + id: 'ceiling_stair_move', + parentId: ground.id, + polygon: footprint, + holes: [opening.polygon], + holeMetadata: [{ source: 'floor-opening', openingId: opening.id }], + }) + const plate = SlabNode.parse({ + id: 'slab_stair_move', + parentId: upper.id, + polygon: footprint, + holes: [opening.polygon], + holeMetadata: [{ source: 'floor-opening', openingId: opening.id }], + }) + const segment = StairSegmentNode.parse({ + id: 'sseg_stair_move', + parentId: 'stair_stair_move', + width: 1, + length: 2.6, + height: 2.5, + stepCount: 12, + }) + const stair = StairNode.parse({ + id: 'stair_stair_move', + parentId: ground.id, + position: [2, 0, 0.2], + fromLevelId: ground.id, + toLevelId: upper.id, + slabOpeningMode: 'destination', + children: [segment.id], + }) + const nodes = Object.fromEntries( + [building, ground, upper, opening, ceiling, plate, segment, stair].map((node) => [ + node.id, + node, + ]), + ) as Record + expect(syncAutoStairOpenings(nodes)).toEqual([]) + const moved = syncAutoStairOpenings({ + ...nodes, + [stair.id]: { ...stair, position: [3.2, 0, 0.2] }, + }) + expect(moved.find((entry) => entry.id === plate.id)?.data.holeMetadata).toContainEqual({ + source: 'stair', + stairId: stair.id, + }) + expect(moved.find((entry) => entry.id === ceiling.id)?.data.holeMetadata).toContainEqual({ + source: 'stair', + stairId: stair.id, + }) +}) + +test('a spiral reaching a 4.5 m upper floor opens its plate and the ceiling below', () => { + const building = BuildingNode.parse({ id: 'building_spiral_reach' }) + const ground = LevelNode.parse({ + id: 'level_spiral_reach_0', + parentId: building.id, + level: 0, + height: 4.5, + }) + const upper = LevelNode.parse({ + id: 'level_spiral_reach_1', + parentId: building.id, + level: 1, + }) + building.children = [ground.id, upper.id] + const footprint: [number, number][] = [ + [0, 0], + [5, 0], + [5, 5], + [0, 5], + ] + const plate = SlabNode.parse({ + id: 'slab_spiral_reach', + parentId: upper.id, + polygon: footprint, + elevation: 0.05, + }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_spiral_reach', + parentId: ground.id, + polygon: footprint, + }) + const stair = StairNode.parse({ + id: 'stair_spiral_reach', + parentId: ground.id, + position: [2.5, 0, 2.5], + stairType: 'spiral', + stepCount: 24, + fromLevelId: ground.id, + toLevelId: upper.id, + slabOpeningMode: 'destination', + }) + const nodes = Object.fromEntries( + [building, ground, upper, plate, ceiling, stair].map((node) => [node.id, node]), + ) as Record + expect(resolveStairTotalRise(stair, nodes)).toBeCloseTo(4.5) + const updates = syncAutoStairOpenings(nodes) + expect(updates.find((update) => update.id === plate.id)?.data.holeMetadata).toContainEqual({ + source: 'stair', + stairId: stair.id, + }) + expect(updates.find((update) => update.id === ceiling.id)?.data.holeMetadata).toContainEqual({ + source: 'stair', + stairId: stair.id, + }) +}) diff --git a/packages/core/src/systems/stair/stair-opening-sync.test.ts b/packages/core/src/systems/stair/stair-opening-sync.test.ts index 9068c029fc..87cf724500 100644 --- a/packages/core/src/systems/stair/stair-opening-sync.test.ts +++ b/packages/core/src/systems/stair/stair-opening-sync.test.ts @@ -391,6 +391,14 @@ describe('syncAutoStairOpenings', () => { expect(updates.find((update) => update.id === landingSlab.id)).toBeUndefined() expect(updates.find((update) => update.id === sourceCeiling.id)).toBeUndefined() + const onlyFloorCovered = syncAutoStairOpenings({ + ...nodes, + [sourceCeiling.id]: { ...sourceCeiling, holes: [], holeMetadata: [] }, + }) + expect(onlyFloorCovered.find((update) => update.id === landingSlab.id)).toBeUndefined() + expect( + onlyFloorCovered.find((update) => update.id === sourceCeiling.id)?.data.holeMetadata, + ).toEqual([{ source: 'stair', stairId: stair.id }]) }) test('adds stair holes when an existing manual hole is too small', () => { diff --git a/packages/core/src/systems/stair/stair-opening-sync.ts b/packages/core/src/systems/stair/stair-opening-sync.ts index 0cd760cfb5..b80dda386d 100644 --- a/packages/core/src/systems/stair/stair-opening-sync.ts +++ b/packages/core/src/systems/stair/stair-opening-sync.ts @@ -1,4 +1,5 @@ -import { resolveBuildingForLevel, resolveLevelId } from '../../hooks/spatial-grid/spatial-grid-sync' +import { resolveBuildingForLevel, resolveLevelId } from '../../lib/node-ancestry' +import { area, difference, union } from '../../lib/polygon-boolean' import { type Point2D, polygonContainsPolygon, polygonsOverlap } from '../../lib/polygon-relations' import type { AnyNode, @@ -12,7 +13,7 @@ import type { import { resolveCeilingHeight } from '../../services/level-height' import { getLevelElevations } from '../../services/storey' import { computeSegmentTransforms, rotateXZ } from './stair-footprint' -import { resolveStairTotalRise } from './stair-rise' +import { resolveStairTotalRise } from './stair-rise-query' type SegmentTransform = { position: [number, number, number] @@ -32,6 +33,12 @@ type AxisAlignedRect = { maxZ: number } +const buildingLevelsMemo = new WeakMap[]>>() +const stairLevelsMemo = new WeakMap< + object, + WeakMap +>() + const CURVED_STAIR_SLAB_OPENING_RATIO = 0.8 const STRAIGHT_STAIR_TARGET_THRESHOLD_MIN = 0.35 const STAIR_SLAB_OPENING_TIGHTENING = 0 @@ -65,7 +72,8 @@ function metadataEqual(left: SurfaceHoleMetadata[], right: SurfaceHoleMetadata[] (entry, index) => entry.source === right[index]?.source && (entry.elevatorId ?? null) === (right[index]?.elevatorId ?? null) && - (entry.stairId ?? null) === (right[index]?.stairId ?? null), + (entry.stairId ?? null) === (right[index]?.stairId ?? null) && + (entry.openingId ?? null) === (right[index]?.openingId ?? null), ) } @@ -81,7 +89,7 @@ function normalizeExistingMetadata( // footprint via `./stair-footprint` so both derive the chain identically. function getLevelNumber(levelId: string | null, nodes: Record) { - if (!levelId) return undefined + if (!levelId) return const node = nodes[levelId as AnyNodeId] return node?.type === 'level' ? node.level : undefined } @@ -100,6 +108,14 @@ function getBuildingLevels(buildingId: string | null, nodes: Record>() for (const childId of building.children ?? []) { const child = nodes[childId as AnyNodeId] @@ -111,7 +127,9 @@ function getBuildingLevels(buildingId: string | null, nodes: Record left.level - right.level) + const sorted = Array.from(levels.values()).sort((left, right) => left.level - right.level) + cache.set(building.id, sorted) + return sorted } function inferSourceLevelForDestination( @@ -173,6 +191,13 @@ function isInStairBuildingScope( } function getResolvedStairLevelIds(stair: StairNode, nodes: Record) { + let cache = stairLevelsMemo.get(nodes) + if (!cache) { + cache = new WeakMap() + stairLevelsMemo.set(nodes, cache) + } + const cached = cache.get(stair) + if (cached) return cached const parentLevelId = normalizeLevelId(resolveLevelId(stair, nodes), nodes) const explicitToLevelId = normalizeLevelId(stair.toLevelId, nodes) const fromLevelId = @@ -186,7 +211,9 @@ function getResolvedStairLevelIds(stair: StairNode, nodes: Record) { @@ -290,7 +317,9 @@ function polygonArea(points: Point2D[]) { } function isCoveredByExistingHole(existingHoles: Point2D[][], autoHole: Point2D[]) { - return existingHoles.some((existingHole) => polygonContainsPolygon(existingHole, autoHole)) + if (existingHoles.some((existingHole) => polygonContainsPolygon(existingHole, autoHole))) + return true + return area(difference(autoHole, union(existingHoles))) <= 1e-6 } function getAxisAlignedRectFromPolygon(polygon: Point2D[]): AxisAlignedRect | null { @@ -403,7 +432,7 @@ function buildUnionPolygonsFromRects(rects: AxisAlignedRect[]): Point2D[][] { return polygons } -function getCurvedOpeningPolygon(stair: StairNode, offset: number = 0): Point2D[] { +function getCurvedOpeningPolygon(stair: StairNode, offset = 0): Point2D[] { const width = Math.max(stair.width ?? 1, 0.4) const innerRadius = Math.max(0.01, (stair.innerRadius ?? 0.9) - offset) const outerRadius = (stair.innerRadius ?? 0.9) + width + offset @@ -446,7 +475,7 @@ function getCurvedOpeningPolygon(stair: StairNode, offset: number = 0): Point2D[ return [...outerPoints, ...innerPoints] } -function getSpiralOpeningPolygon(stair: StairNode, offset: number = 0): Point2D[] { +function getSpiralOpeningPolygon(stair: StairNode, offset = 0): Point2D[] { const radius = Math.max(0.05, stair.innerRadius ?? 0.9) + Math.max(stair.width ?? 1, 0.4) + offset const segmentCount = 48 @@ -611,7 +640,7 @@ function getTargetSlabElevationForStair( const fromElevation = fromLevelId ? elevations.get(fromLevelId) : undefined const slabElevation = elevations.get(slabLevelId) - if (!fromElevation || !slabElevation || fromElevation.buildingId !== slabElevation.buildingId) { + if (!(fromElevation && slabElevation) || fromElevation.buildingId !== slabElevation.buildingId) { return slab.elevation ?? 0.05 } @@ -634,8 +663,7 @@ function getTargetCeilingElevationForStair( const ceilingHeight = resolveCeilingHeight(ceiling, nodes as Record) if ( - !fromElevation || - !ceilingElevation || + !(fromElevation && ceilingElevation) || fromElevation.buildingId !== ceilingElevation.buildingId ) { return ceilingHeight @@ -703,6 +731,21 @@ export function syncAutoStairOpenings(nodes: Record) { (node): node is CeilingNode => node.type === 'ceiling', ) const updates: Array<{ id: AnyNodeId; data: Partial }> = [] + const slabStairsByLevel = new Map() + const ceilingStairsByLevel = new Map() + const stairsFor = (levelId: string, ceiling: boolean) => { + const cache = ceiling ? ceilingStairsByLevel : slabStairsByLevel + let selected = cache.get(levelId) + if (!selected) { + selected = stairs.filter((stair) => + ceiling + ? shouldApplyStairToCeiling(stair, levelId, nodes) + : shouldApplyStairToSlab(stair, levelId, nodes), + ) + cache.set(levelId, selected) + } + return selected + } for (const slab of slabs) { const slabLevelId = resolveLevelId(slab, nodes) @@ -713,8 +756,7 @@ export function syncAutoStairOpenings(nodes: Record) { .filter((entry) => entry.metadata.source !== 'stair') const preservedHolePolygons = preservedHoles.map((entry) => entry.polygon) - const stairHoles = stairs - .filter((stair) => shouldApplyStairToSlab(stair, slabLevelId, nodes)) + const stairHoles = stairsFor(slabLevelId, false) .flatMap((stair) => getApplicableStairOpeningPolygons( stair, @@ -762,8 +804,7 @@ export function syncAutoStairOpenings(nodes: Record) { .filter((entry) => entry.metadata.source !== 'stair') const preservedHolePolygons = preservedHoles.map((entry) => entry.polygon) - const stairHoles = stairs - .filter((stair) => shouldApplyStairToCeiling(stair, ceilingLevelId, nodes)) + const stairHoles = stairsFor(ceilingLevelId, true) .flatMap((stair) => getApplicableStairOpeningPolygons( stair, diff --git a/packages/core/src/systems/stair/stair-opening-system.tsx b/packages/core/src/systems/stair/stair-opening-system.tsx index e61aa98a3d..f019ac9571 100644 --- a/packages/core/src/systems/stair/stair-opening-system.tsx +++ b/packages/core/src/systems/stair/stair-opening-system.tsx @@ -1,12 +1,16 @@ 'use client' import { useEffect } from 'react' +import { structureChangeBatch } from '../../commands/structure/shared' import type { AnyNode, AnyNodeId } from '../../schema' import { pauseSceneHistory, resumeSceneHistory } from '../../store/history-control' -import { queueSceneNormalization } from '../../store/scene-hydration' +import { isHydrationNormalization, queueSceneNormalization } from '../../store/scene-hydration' import useLiveNodeOverrides from '../../store/use-live-node-overrides' import useLiveTransforms from '../../store/use-live-transforms' import useScene from '../../store/use-scene' +import { ensureSceneOpenings } from '../../utils/ensure-scene-openings' +import { planOwnedFloorOpenings } from '../owned-floor-openings' +import { reconcileOwnedFloorOpeningChanges } from '../reconcile-owned-floor-openings' import { createSurfaceOpeningPreviewController, getNodesWithLiveStairOpeningInputs, @@ -67,6 +71,21 @@ export function initializeStairOpeningSync() { }) } + const applyOpeningChanges = (skipExistingSurfaces = false) => { + const changes = planOwnedFloorOpenings(useScene.getState().nodes, { skipExistingSurfaces }) + if (!changes.length) return + syncingAutoOpenings = true + pauseSceneHistory(useScene) + try { + const before = useScene.getState().nodes + useScene.getState().applyNodeChanges(structureChangeBatch(changes)) + reconcileOwnedFloorOpeningChanges(before, changes) + } finally { + resumeSceneHistory(useScene) + syncingAutoOpenings = false + } + } + const clearPreviewUpdates = () => { if (previewController.previewSurfaceIds.size === 0) return syncingPreviewOpenings = true @@ -96,18 +115,23 @@ export function initializeStairOpeningSync() { ) } - const runAutoSync = () => { + const runAutoSync = (preserveSlabs: boolean) => { + if (preserveSlabs) { + applyUpdates(ensureSceneOpenings(useScene.getState().nodes).updates) + applyOpeningChanges(true) + return + } // Rise first: straight stairs converge their flight heights to the // resolved rise (level height or deck elevation), and the opening pass // reads those segment heights — so it must run against the post-rise // nodes. applyUpdates(syncStairRises(useScene.getState().nodes)) - applyUpdates(syncAutoStairOpenings(useScene.getState().nodes)) + applyOpeningChanges() } let disposed = false let syncGeneration = 0 - const scheduleAutoSync = () => { + const scheduleAutoSync = (preserveSlabs = false) => { const generation = ++syncGeneration // One microtask later so every other scene-store listener for the // triggering transition (and, at mount, the editor's spatial-grid @@ -117,17 +141,17 @@ export function initializeStairOpeningSync() { // rescale flights against the pre-transition slab state. queueSceneNormalization(() => { if (disposed || generation !== syncGeneration) return - runAutoSync() + runAutoSync(preserveSlabs) refreshLivePreview() }) } - scheduleAutoSync() + scheduleAutoSync(true) const unsubscribeScene = useScene.subscribe((state, prevState) => { if (syncingAutoOpenings) return if (!hasOpeningRelevantNodeChange(state.nodes, prevState.nodes)) return - scheduleAutoSync() + scheduleAutoSync(isHydrationNormalization() || state.hydrationId !== prevState.hydrationId) }) const unsubscribeLiveTransforms = useLiveTransforms.subscribe(() => { diff --git a/packages/core/src/systems/stair/stair-rise-query.test.ts b/packages/core/src/systems/stair/stair-rise-query.test.ts new file mode 100644 index 0000000000..eb31c6365f --- /dev/null +++ b/packages/core/src/systems/stair/stair-rise-query.test.ts @@ -0,0 +1,27 @@ +import { expect, test } from 'bun:test' +import { type AnyNode, LevelNode, StairNode, StairSegmentNode } from '../../schema' +import { syncStairRises } from './stair-rise-query' + +test('a single flight restores the exact target rise after floor-normalized height and repeated level writes', () => { + const level = LevelNode.parse({ height: 2.5 }) + const stair = StairNode.parse({ parentId: level.id }) + const segment = StairSegmentNode.parse({ parentId: stair.id, height: 2.45 }) + level.children = [stair.id] + stair.children = [segment.id] + let nodes: Record = Object.fromEntries( + [level, stair, segment].map((node) => [node.id, node]), + ) + for (const height of [2.5, 4, 2.5, 4, 2.5]) { + nodes = { ...nodes, [level.id]: { ...level, height } } + const updates = syncStairRises(nodes) + expect(updates).toEqual([{ id: segment.id, data: { height } }]) + nodes = { + ...nodes, + [segment.id]: { + ...segment, + ...(updates[0]!.data as Partial), + } as StairSegmentNode, + } + expect(syncStairRises(nodes)).toEqual([]) + } +}) diff --git a/packages/core/src/systems/stair/stair-rise-query.ts b/packages/core/src/systems/stair/stair-rise-query.ts new file mode 100644 index 0000000000..a336bfb881 --- /dev/null +++ b/packages/core/src/systems/stair/stair-rise-query.ts @@ -0,0 +1,152 @@ +import { containsPoint } from '../../lib/polygon-boolean' +import type { AnyNode, AnyNodeId, StairNode, StairSegmentNode } from '../../schema' +import { DEFAULT_LEVEL_HEIGHT } from '../../services/level-height' +import { + findLevelAboveId, + getLevelElevations, + getLevelFloorToFloorHeight, +} from '../../services/storey' +import { stairBaseElevation } from './stair-base-elevation' +import { stairArrivalOpening } from './stair-footprint' + +export function resolveStairTotalRise( + stair: StairNode, + nodes: Record, + baseElevationFor = stairBaseElevation, + legacyArrival = false, +): number { + if (stair.totalRise !== undefined) return stair.totalRise + + const parentLevel = Object.values(nodes).find( + (node) => node.type === 'level' && (node.children ?? []).includes(stair.id), + ) + const requestedSource = stair.fromLevelId ? nodes[stair.fromLevelId] : undefined + const level = requestedSource?.type === 'level' ? requestedSource : parentLevel + + // Both destinations are absolute level-local heights, while the stair's own + // base may be lifted onto a floor slab by the floor-stack + // (`FloorElevationSystem` / `syncStairGroupElevation` put the group at + // `position[1] + elected slab elevation`). The rise is measured from that + // base, so subtract it — electing the base exactly the way the visual + // systems do (persisted `supportSlabId` honored, uncapped election + // otherwise) keeps base + rise landing precisely on the destination surface. + const baseElevation = baseElevationFor(stair, nodes, level?.id ?? null) + + if (stair.deckSlabId) { + // The deck's `elevation` IS its walking surface (level-local). A stale + // reference (deck gone) falls through to the level-derived rise. + const deck = nodes[stair.deckSlabId] + if (deck?.type === 'slab') return (deck.elevation ?? 0.05) - baseElevation + } + + if (level?.type !== 'level') return DEFAULT_LEVEL_HEIGHT + if (legacyArrival) + return getLevelFloorToFloorHeight(level.id, nodes as Record) - baseElevation + const elevations = getLevelElevations(nodes as Record) + const requestedDestination = stair.toLevelId ? elevations.get(stair.toLevelId) : undefined + const sourceElevation = elevations.get(level.id) + const destinationId = + requestedDestination && + sourceElevation && + requestedDestination.buildingId === sourceElevation.buildingId && + requestedDestination.ordinal > sourceElevation.ordinal + ? stair.toLevelId! + : findLevelAboveId(level.id, elevations) + if (!destinationId) + return getLevelFloorToFloorHeight(level.id, nodes as Record) - baseElevation + const opening = stairArrivalOpening(stair, nodes) + const point: [number, number] = opening.length + ? [ + opening.reduce((sum, vertex) => sum + vertex[0], 0) / opening.length, + opening.reduce((sum, vertex) => sum + vertex[1], 0) / opening.length, + ] + : [stair.position[0], stair.position[2]] + const covers = (polygon: [number, number][], holes: [number, number][][]) => + containsPoint([{ outer: polygon, holes }], point) + const room = Object.values(nodes).find( + (node) => + node.type === 'zone' && + node.parentId === destinationId && + node.spaceRole === 'room' && + node.enclosureStatus !== 'open' && + node.hasFloor !== false && + node.floor?.support !== 'open' && + node.floor?.elevation !== undefined && + covers(node.polygon, node.holes ?? []), + ) + const plate = Object.values(nodes).find( + (node) => + node.type === 'slab' && + node.parentId === destinationId && + node.plateRole === 'base' && + covers(node.polygon, []), + ) + const top = + room?.type === 'zone' ? room.floor!.elevation! : plate?.type === 'slab' ? plate.elevation : 0 + return ( + elevations.get(destinationId)!.baseY - elevations.get(level.id)!.baseY + top - baseElevation + ) +} + +const RISE_SYNC_EPSILON = 1e-4 + +/** + * Keeps straight stairs' flight segments in step with the resolved rise. + * Straight-stair geometry derives from per-segment heights (not from + * `resolveStairTotalRise`), so level-height and deck-elevation changes must + * write through to the flight segments — curved/spiral stairs read the + * resolved rise directly and need no sync. + * + * Scope: stairs whose total the system owns — follows-mode stairs (absent + * `totalRise`, tracking their level or their deck) and deck-attached stairs + * (an explicit rise converges to the typed value). A detached stair with an + * explicit `totalRise` is the one place hand-edited segment chains are + * legitimate, so it is never touched. Flight heights scale proportionally + * (landings keep theirs); returns `updateNodes` patches, empty when every + * stair is already in step. + */ +export function syncStairRises( + nodes: Record, + baseElevationFor = stairBaseElevation, + legacyArrival = false, +): Array<{ id: AnyNodeId; data: Partial }> { + const updates: Array<{ id: AnyNodeId; data: Partial }> = [] + + for (const node of Object.values(nodes)) { + if (node.type !== 'stair' || (node.stairType ?? 'straight') !== 'straight') continue + const deck = node.deckSlabId ? nodes[node.deckSlabId] : undefined + if (node.totalRise !== undefined && deck?.type !== 'slab') continue + + const segments = (node.children ?? []) + .map((childId) => nodes[childId]) + .filter((child): child is StairSegmentNode => child?.type === 'stair-segment') + const flights = segments.filter((segment) => segment.segmentType === 'stair') + if (flights.length === 0) continue + + const landingRise = segments + .filter((segment) => segment.segmentType !== 'stair') + .reduce((sum, segment) => sum + segment.height, 0) + const flightRise = flights.reduce((sum, segment) => sum + segment.height, 0) + const targetFlightRise = + resolveStairTotalRise(node, nodes, baseElevationFor, legacyArrival) - landingRise + if (!Number.isFinite(targetFlightRise) || targetFlightRise <= 0) continue + if (Math.abs(flightRise - targetFlightRise) <= RISE_SYNC_EPSILON) continue + + for (const flight of flights) { + // A sole flight owns the exact target; proportional scaling adds undo/redo rounding drift. + const height = + flights.length === 1 + ? targetFlightRise + : flightRise > RISE_SYNC_EPSILON + ? flight.height * (targetFlightRise / flightRise) + : targetFlightRise / flights.length + updates.push({ id: flight.id as AnyNodeId, data: { height } }) + } + } + + return updates +} + +export function stairHasNoRise(stair: StairNode, nodes: Record): boolean { + return resolveStairTotalRise(stair, nodes) <= 0 +} diff --git a/packages/core/src/systems/stair/stair-rise.ts b/packages/core/src/systems/stair/stair-rise.ts index 3e62daf6bc..ffc810f1c3 100644 --- a/packages/core/src/systems/stair/stair-rise.ts +++ b/packages/core/src/systems/stair/stair-rise.ts @@ -1,90 +1,28 @@ import { getFloorStackedPosition } from '../../hooks/spatial-grid/floor-placed-elevation' -import type { AnyNode, AnyNodeId, StairNode, StairSegmentNode } from '../../schema' -import { DEFAULT_LEVEL_HEIGHT } from '../../services/level-height' -import { getLevelFloorToFloorHeight } from '../../services/storey' - -export function resolveStairTotalRise(stair: StairNode, nodes: Record): number { - if (stair.totalRise !== undefined) return stair.totalRise - - const level = Object.values(nodes).find( - (node) => node.type === 'level' && node.children.includes(stair.id), - ) - - // Both destinations are absolute level-local heights, while the stair's own - // base may be lifted onto a floor slab by the floor-stack - // (`FloorElevationSystem` / `syncStairGroupElevation` put the group at - // `position[1] + elected slab elevation`). The rise is measured from that - // base, so subtract it — electing the base exactly the way the visual - // systems do (persisted `supportSlabId` honored, uncapped election - // otherwise) keeps base + rise landing precisely on the destination surface. - const baseElevation = getFloorStackedPosition({ +import type { AnyNode, StairNode } from '../../schema' +import { + resolveStairTotalRise as resolveRise, + syncStairRises as syncRises, +} from './stair-rise-query' + +function liveBaseElevation( + stair: StairNode, + nodes: Record, + levelId: string | null, +) { + return getFloorStackedPosition({ node: stair, nodes, position: stair.position, rotation: stair.rotation, - levelId: level?.id ?? null, + levelId, })[1] - - if (stair.deckSlabId) { - // The deck's `elevation` IS its walking surface (level-local). A stale - // reference (deck gone) falls through to the level-derived rise. - const deck = nodes[stair.deckSlabId] - if (deck?.type === 'slab') return (deck.elevation ?? 0.05) - baseElevation - } - - if (level?.type !== 'level') return DEFAULT_LEVEL_HEIGHT - return getLevelFloorToFloorHeight(level.id, nodes as Record) - baseElevation } -const RISE_SYNC_EPSILON = 1e-4 - -/** - * Keeps straight stairs' flight segments in step with the resolved rise. - * Straight-stair geometry derives from per-segment heights (not from - * `resolveStairTotalRise`), so level-height and deck-elevation changes must - * write through to the flight segments — curved/spiral stairs read the - * resolved rise directly and need no sync. - * - * Scope: stairs whose total the system owns — follows-mode stairs (absent - * `totalRise`, tracking their level or their deck) and deck-attached stairs - * (an explicit rise converges to the typed value). A detached stair with an - * explicit `totalRise` is the one place hand-edited segment chains are - * legitimate, so it is never touched. Flight heights scale proportionally - * (landings keep theirs); returns `updateNodes` patches, empty when every - * stair is already in step. - */ -export function syncStairRises( - nodes: Record, -): Array<{ id: AnyNodeId; data: Partial }> { - const updates: Array<{ id: AnyNodeId; data: Partial }> = [] - - for (const node of Object.values(nodes)) { - if (node.type !== 'stair' || node.stairType !== 'straight') continue - const deck = node.deckSlabId ? nodes[node.deckSlabId] : undefined - if (node.totalRise !== undefined && deck?.type !== 'slab') continue - - const segments = (node.children ?? []) - .map((childId) => nodes[childId]) - .filter((child): child is StairSegmentNode => child?.type === 'stair-segment') - const flights = segments.filter((segment) => segment.segmentType === 'stair') - if (flights.length === 0) continue - - const landingRise = segments - .filter((segment) => segment.segmentType !== 'stair') - .reduce((sum, segment) => sum + segment.height, 0) - const flightRise = flights.reduce((sum, segment) => sum + segment.height, 0) - const targetFlightRise = resolveStairTotalRise(node, nodes) - landingRise - if (targetFlightRise <= 0) continue - if (Math.abs(flightRise - targetFlightRise) <= RISE_SYNC_EPSILON) continue - - for (const flight of flights) { - const height = - flightRise > RISE_SYNC_EPSILON - ? flight.height * (targetFlightRise / flightRise) - : targetFlightRise / flights.length - updates.push({ id: flight.id as AnyNodeId, data: { height } }) - } - } +export function resolveStairTotalRise(stair: StairNode, nodes: Record) { + return resolveRise(stair, nodes, liveBaseElevation) +} - return updates +export function syncStairRises(nodes: Record) { + return syncRises(nodes, liveBaseElevation) } diff --git a/packages/core/src/systems/wall/__fixtures__/wall-frame-golden.json b/packages/core/src/systems/wall/__fixtures__/wall-frame-golden.json new file mode 100644 index 0000000000..ab97230757 --- /dev/null +++ b/packages/core/src/systems/wall/__fixtures__/wall-frame-golden.json @@ -0,0 +1,2402 @@ +[ + { + "walls": [ + { + "object": "node", + "id": "wall_v6wfghqmnpwksoqr", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 0], + "end": [4, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_10usrztobrbkfqj8", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [8, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_itzhe3m4h9er75yb", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 0], + "end": [8, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_05jeqzxhxtvqw2q7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 3], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_4tujenozv0ovwh6e", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 3], + "end": [0, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_uk11r2ommw87mlt7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 3], + "end": [0, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_hyhbb4wtsu9si4lv", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + } + ], + "slabs": [ + { + "object": "node", + "id": "slab_8iidf8weskkvq5z4", + "type": "slab", + "parentId": null, + "visible": true, + "metadata": {}, + "polygon": [[0, 0], [4, 0], [4, 3], [0, 3]], + "holes": [], + "holeMetadata": [], + "elevation": 0.05, + "thickness": 0.05, + "recessed": false, + "autoFromWalls": true + }, + { + "object": "node", + "id": "slab_ldunjvnzb98jq1r5", + "type": "slab", + "parentId": null, + "visible": true, + "metadata": {}, + "polygon": [[4, 0], [8, 0], [8, 3], [4, 3]], + "holes": [], + "holeMetadata": [], + "elevation": 0.05, + "thickness": 0.05, + "recessed": false, + "autoFromWalls": true + } + ], + "output": { + "miters": { + "junctionData": [ + [ + "0,0", + [ + [ + "wall_v6wfghqmnpwksoqr", + { + "left": { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + "right": { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + } + } + ], + [ + "wall_uk11r2ommw87mlt7", + { + "right": { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + "left": { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + } + } + ] + ] + ], + [ + "4000,0", + [ + [ + "wall_10usrztobrbkfqj8", + { + "left": { + "x": 4.05, + "y": 0.05000000000000001 + } + } + ], + [ + "wall_hyhbb4wtsu9si4lv", + { + "right": { + "x": 4.05, + "y": 0.05000000000000001 + }, + "left": { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + } + } + ], + [ + "wall_v6wfghqmnpwksoqr", + { + "right": { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + } + } + ] + ] + ], + [ + "8000,0", + [ + [ + "wall_itzhe3m4h9er75yb", + { + "left": { + "x": 7.95, + "y": 0.05000000000000001 + }, + "right": { + "x": 8.05, + "y": -0.05000000000000001 + } + } + ], + [ + "wall_10usrztobrbkfqj8", + { + "right": { + "x": 7.95, + "y": 0.05000000000000001 + }, + "left": { + "x": 8.05, + "y": -0.05000000000000001 + } + } + ] + ] + ], + [ + "8000,3000", + [ + [ + "wall_itzhe3m4h9er75yb", + { + "left": { + "x": 8.05, + "y": 3.0499999999999994 + }, + "right": { + "x": 7.95, + "y": 2.9500000000000006 + } + } + ], + [ + "wall_05jeqzxhxtvqw2q7", + { + "right": { + "x": 8.05, + "y": 3.0499999999999994 + }, + "left": { + "x": 7.95, + "y": 2.9500000000000006 + } + } + ] + ] + ], + [ + "4000,3000", + [ + [ + "wall_hyhbb4wtsu9si4lv", + { + "left": { + "x": 4.05, + "y": 2.9500000000000006 + }, + "right": { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + } + } + ], + [ + "wall_05jeqzxhxtvqw2q7", + { + "right": { + "x": 4.05, + "y": 2.9500000000000006 + } + } + ], + [ + "wall_4tujenozv0ovwh6e", + { + "left": { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + } + } + ] + ] + ], + [ + "0,3000", + [ + [ + "wall_uk11r2ommw87mlt7", + { + "left": { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + "right": { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + } + } + ], + [ + "wall_4tujenozv0ovwh6e", + { + "right": { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + "left": { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + } + } + ] + ] + ] + ], + "junctions": [ + [ + "0,0", + { + "meetingPoint": { + "x": 0, + "y": 0 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_v6wfghqmnpwksoqr", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 0], + "end": [4, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + }, + { + "wall": { + "object": "node", + "id": "wall_uk11r2ommw87mlt7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 3], + "end": [0, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + } + ] + } + ], + [ + "4000,0", + { + "meetingPoint": { + "x": 4, + "y": 0 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_v6wfghqmnpwksoqr", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 0], + "end": [4, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_10usrztobrbkfqj8", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [8, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + }, + { + "wall": { + "object": "node", + "id": "wall_hyhbb4wtsu9si4lv", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ], + [ + "8000,0", + { + "meetingPoint": { + "x": 8, + "y": 0 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_10usrztobrbkfqj8", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [8, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_itzhe3m4h9er75yb", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 0], + "end": [8, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ], + [ + "8000,3000", + { + "meetingPoint": { + "x": 8, + "y": 3 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_itzhe3m4h9er75yb", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 0], + "end": [8, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_05jeqzxhxtvqw2q7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 3], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ], + [ + "4000,3000", + { + "meetingPoint": { + "x": 4, + "y": 3 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_05jeqzxhxtvqw2q7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 3], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_4tujenozv0ovwh6e", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 3], + "end": [0, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + }, + { + "wall": { + "object": "node", + "id": "wall_hyhbb4wtsu9si4lv", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + } + ] + } + ], + [ + "0,3000", + { + "meetingPoint": { + "x": 0, + "y": 3 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_4tujenozv0ovwh6e", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 3], + "end": [0, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_uk11r2ommw87mlt7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 3], + "end": [0, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ] + ] + }, + "footprints": [ + [ + { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + }, + { + "x": 4, + "y": -0.05 + }, + { + "x": 4, + "y": 0 + }, + { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + }, + { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + { + "x": 0, + "y": 0 + } + ], + [ + { + "x": 4, + "y": -0.05 + }, + { + "x": 8.05, + "y": -0.05000000000000001 + }, + { + "x": 8, + "y": 0 + }, + { + "x": 7.95, + "y": 0.05000000000000001 + }, + { + "x": 4.05, + "y": 0.05000000000000001 + }, + { + "x": 4, + "y": 0 + } + ], + [ + { + "x": 8.05, + "y": -0.05000000000000001 + }, + { + "x": 8.05, + "y": 3.0499999999999994 + }, + { + "x": 8, + "y": 3 + }, + { + "x": 7.95, + "y": 2.9500000000000006 + }, + { + "x": 7.95, + "y": 0.05000000000000001 + }, + { + "x": 8, + "y": 0 + } + ], + [ + { + "x": 8.05, + "y": 3.0499999999999994 + }, + { + "x": 4, + "y": 3.05 + }, + { + "x": 4, + "y": 3 + }, + { + "x": 4.05, + "y": 2.9500000000000006 + }, + { + "x": 7.95, + "y": 2.9500000000000006 + }, + { + "x": 8, + "y": 3 + } + ], + [ + { + "x": 4, + "y": 3.05 + }, + { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + }, + { + "x": 0, + "y": 3 + }, + { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + }, + { + "x": 4, + "y": 3 + } + ], + [ + { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + }, + { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + }, + { + "x": 0, + "y": 0 + }, + { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + { + "x": 0, + "y": 3 + } + ], + [ + { + "x": 4.05, + "y": 0.05000000000000001 + }, + { + "x": 4.05, + "y": 2.9500000000000006 + }, + { + "x": 4, + "y": 3 + }, + { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + }, + { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + }, + { + "x": 4, + "y": 0 + } + ] + ], + "polygons": [ + [ + [4, -0.05], + [4, 3.05], + [-0.04999999999999982, 3.05], + [-0.05, -0.04999999999999982] + ], + [[8.05, -0.05], [8.05, 3.05], [4, 3.05], [4, -0.04999999999999982]] + ], + "support": [ + { + "elevation": 0.05, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_ldunjvnzb98jq1r5", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_ldunjvnzb98jq1r5", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_ldunjvnzb98jq1r5", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + } + ] + } + }, + { + "walls": [ + { + "object": "node", + "id": "wall_v6wfghqmnpwksoqr", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 0], + "end": [4, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_10usrztobrbkfqj8", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [8, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_itzhe3m4h9er75yb", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 0], + "end": [8, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_05jeqzxhxtvqw2q7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 3], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_4tujenozv0ovwh6e", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 3], + "end": [0, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_uk11r2ommw87mlt7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 3], + "end": [0, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_hyhbb4wtsu9si4lv", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + } + ], + "slabs": [ + { + "object": "node", + "id": "slab_8iidf8weskkvq5z4", + "type": "slab", + "parentId": null, + "visible": true, + "metadata": {}, + "polygon": [[0, 0], [4, 0], [4, 3], [0, 3]], + "holes": [], + "holeMetadata": [], + "elevation": 0.4, + "thickness": 0.4, + "recessed": false, + "autoFromWalls": true + }, + { + "object": "node", + "id": "slab_ldunjvnzb98jq1r5", + "type": "slab", + "parentId": null, + "visible": true, + "metadata": {}, + "polygon": [[4, 0], [8, 0], [8, 3], [4, 3]], + "holes": [], + "holeMetadata": [], + "elevation": 0.05, + "thickness": 0.05, + "recessed": false, + "autoFromWalls": true + } + ], + "output": { + "miters": { + "junctionData": [ + [ + "0,0", + [ + [ + "wall_v6wfghqmnpwksoqr", + { + "left": { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + "right": { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + } + } + ], + [ + "wall_uk11r2ommw87mlt7", + { + "right": { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + "left": { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + } + } + ] + ] + ], + [ + "4000,0", + [ + [ + "wall_10usrztobrbkfqj8", + { + "left": { + "x": 4.05, + "y": 0.05000000000000001 + } + } + ], + [ + "wall_hyhbb4wtsu9si4lv", + { + "right": { + "x": 4.05, + "y": 0.05000000000000001 + }, + "left": { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + } + } + ], + [ + "wall_v6wfghqmnpwksoqr", + { + "right": { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + } + } + ] + ] + ], + [ + "8000,0", + [ + [ + "wall_itzhe3m4h9er75yb", + { + "left": { + "x": 7.95, + "y": 0.05000000000000001 + }, + "right": { + "x": 8.05, + "y": -0.05000000000000001 + } + } + ], + [ + "wall_10usrztobrbkfqj8", + { + "right": { + "x": 7.95, + "y": 0.05000000000000001 + }, + "left": { + "x": 8.05, + "y": -0.05000000000000001 + } + } + ] + ] + ], + [ + "8000,3000", + [ + [ + "wall_itzhe3m4h9er75yb", + { + "left": { + "x": 8.05, + "y": 3.0499999999999994 + }, + "right": { + "x": 7.95, + "y": 2.9500000000000006 + } + } + ], + [ + "wall_05jeqzxhxtvqw2q7", + { + "right": { + "x": 8.05, + "y": 3.0499999999999994 + }, + "left": { + "x": 7.95, + "y": 2.9500000000000006 + } + } + ] + ] + ], + [ + "4000,3000", + [ + [ + "wall_hyhbb4wtsu9si4lv", + { + "left": { + "x": 4.05, + "y": 2.9500000000000006 + }, + "right": { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + } + } + ], + [ + "wall_05jeqzxhxtvqw2q7", + { + "right": { + "x": 4.05, + "y": 2.9500000000000006 + } + } + ], + [ + "wall_4tujenozv0ovwh6e", + { + "left": { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + } + } + ] + ] + ], + [ + "0,3000", + [ + [ + "wall_uk11r2ommw87mlt7", + { + "left": { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + "right": { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + } + } + ], + [ + "wall_4tujenozv0ovwh6e", + { + "right": { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + "left": { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + } + } + ] + ] + ] + ], + "junctions": [ + [ + "0,0", + { + "meetingPoint": { + "x": 0, + "y": 0 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_v6wfghqmnpwksoqr", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 0], + "end": [4, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + }, + { + "wall": { + "object": "node", + "id": "wall_uk11r2ommw87mlt7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 3], + "end": [0, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + } + ] + } + ], + [ + "4000,0", + { + "meetingPoint": { + "x": 4, + "y": 0 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_v6wfghqmnpwksoqr", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 0], + "end": [4, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_10usrztobrbkfqj8", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [8, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + }, + { + "wall": { + "object": "node", + "id": "wall_hyhbb4wtsu9si4lv", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ], + [ + "8000,0", + { + "meetingPoint": { + "x": 8, + "y": 0 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_10usrztobrbkfqj8", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [8, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_itzhe3m4h9er75yb", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 0], + "end": [8, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ], + [ + "8000,3000", + { + "meetingPoint": { + "x": 8, + "y": 3 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_itzhe3m4h9er75yb", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 0], + "end": [8, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_05jeqzxhxtvqw2q7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 3], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ], + [ + "4000,3000", + { + "meetingPoint": { + "x": 4, + "y": 3 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_05jeqzxhxtvqw2q7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [8, 3], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_4tujenozv0ovwh6e", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 3], + "end": [0, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + }, + { + "wall": { + "object": "node", + "id": "wall_hyhbb4wtsu9si4lv", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 0], + "end": [4, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + } + ] + } + ], + [ + "0,3000", + { + "meetingPoint": { + "x": 0, + "y": 3 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_4tujenozv0ovwh6e", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [4, 3], + "end": [0, 3], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_uk11r2ommw87mlt7", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [0, 3], + "end": [0, 0], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ] + ] + }, + "footprints": [ + [ + { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + }, + { + "x": 4, + "y": -0.05 + }, + { + "x": 4, + "y": 0 + }, + { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + }, + { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + { + "x": 0, + "y": 0 + } + ], + [ + { + "x": 4, + "y": -0.05 + }, + { + "x": 8.05, + "y": -0.05000000000000001 + }, + { + "x": 8, + "y": 0 + }, + { + "x": 7.95, + "y": 0.05000000000000001 + }, + { + "x": 4.05, + "y": 0.05000000000000001 + }, + { + "x": 4, + "y": 0 + } + ], + [ + { + "x": 8.05, + "y": -0.05000000000000001 + }, + { + "x": 8.05, + "y": 3.0499999999999994 + }, + { + "x": 8, + "y": 3 + }, + { + "x": 7.95, + "y": 2.9500000000000006 + }, + { + "x": 7.95, + "y": 0.05000000000000001 + }, + { + "x": 8, + "y": 0 + } + ], + [ + { + "x": 8.05, + "y": 3.0499999999999994 + }, + { + "x": 4, + "y": 3.05 + }, + { + "x": 4, + "y": 3 + }, + { + "x": 4.05, + "y": 2.9500000000000006 + }, + { + "x": 7.95, + "y": 2.9500000000000006 + }, + { + "x": 8, + "y": 3 + } + ], + [ + { + "x": 4, + "y": 3.05 + }, + { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + }, + { + "x": 0, + "y": 3 + }, + { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + }, + { + "x": 4, + "y": 3 + } + ], + [ + { + "x": -0.05000000000000001, + "y": 3.0499999999999994 + }, + { + "x": -0.05000000000000001, + "y": -0.05000000000000001 + }, + { + "x": 0, + "y": 0 + }, + { + "x": 0.05000000000000001, + "y": 0.05000000000000001 + }, + { + "x": 0.05000000000000001, + "y": 2.9500000000000006 + }, + { + "x": 0, + "y": 3 + } + ], + [ + { + "x": 4.05, + "y": 0.05000000000000001 + }, + { + "x": 4.05, + "y": 2.9500000000000006 + }, + { + "x": 4, + "y": 3 + }, + { + "x": 3.9500000000000006, + "y": 2.9500000000000006 + }, + { + "x": 3.9500000000000006, + "y": 0.05000000000000001 + }, + { + "x": 4, + "y": 0 + } + ] + ], + "polygons": [ + [ + [4.05, -0.05], + [4.05, 3.05], + [-0.04999999999999982, 3.05], + [-0.05, -0.04999999999999982] + ], + [ + [8.05, -0.05], + [8.05, 3.05], + [4.049999999999999, 3.05], + [4.05, -0.04999999999999982] + ] + ], + "support": [ + { + "elevation": 0.4, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.4, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.4 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_ldunjvnzb98jq1r5", + "baseElevation": 0, + "baseSegments": [ + { + "start": 0, + "end": 0.012499999999999947, + "elevation": 0 + }, + { + "start": 0.012499999999999947, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_ldunjvnzb98jq1r5", + "baseElevation": 0.05, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.05 + } + ] + }, + { + "elevation": 0.05, + "electedSlabId": "slab_ldunjvnzb98jq1r5", + "baseElevation": 0, + "baseSegments": [ + { + "start": 0, + "end": 0.9875000000000004, + "elevation": 0.05 + }, + { + "start": 0.9875000000000004, + "end": 1, + "elevation": 0 + } + ] + }, + { + "elevation": 0.4, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.4, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.4 + } + ] + }, + { + "elevation": 0.4, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.4, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.4 + } + ] + }, + { + "elevation": 0.4, + "electedSlabId": "slab_8iidf8weskkvq5z4", + "baseElevation": 0.4, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0.4 + } + ] + } + ] + } + }, + { + "walls": [ + { + "object": "node", + "id": "wall_avig3bvkfsy5nam1", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.3, + "curveOffset": 0.4, + "start": [10, 10], + "end": [14, 12], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_v5697vc9uc6v70jj", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.2, + "start": [14, 12], + "end": [16, 9], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_gadr3d6ptj839lwa", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [16, 9], + "end": [20, 9], + "frontSide": "unknown", + "backSide": "unknown" + }, + { + "object": "node", + "id": "wall_se8453eb6nymm4dl", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "start": [22, 0], + "end": [23, 2], + "frontSide": "unknown", + "backSide": "unknown" + } + ], + "slabs": [], + "output": { + "miters": { + "junctionData": [ + [ + "14000,12000", + [ + [ + "wall_avig3bvkfsy5nam1", + { + "left": { + "x": 14.015212481907616, + "y": 11.796903713365376 + }, + "right": { + "x": 13.984787518092386, + "y": 12.203096286634624 + } + } + ], + [ + "wall_v5697vc9uc6v70jj", + { + "right": { + "x": 14.015212481907616, + "y": 11.796903713365376 + }, + "left": { + "x": 13.984787518092386, + "y": 12.203096286634624 + } + } + ] + ] + ], + [ + "16000,9000", + [ + [ + "wall_gadr3d6ptj839lwa", + { + "left": { + "x": 16.086851709182135, + "y": 9.05 + }, + "right": { + "x": 15.913148290817865, + "y": 8.95 + } + } + ], + [ + "wall_v5697vc9uc6v70jj", + { + "right": { + "x": 16.086851709182135, + "y": 9.05 + }, + "left": { + "x": 15.913148290817865, + "y": 8.95 + } + } + ] + ] + ] + ], + "junctions": [ + [ + "14000,12000", + { + "meetingPoint": { + "x": 14, + "y": 12 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_avig3bvkfsy5nam1", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.3, + "curveOffset": 0.4, + "start": [10, 10], + "end": [14, 12], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_v5697vc9uc6v70jj", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.2, + "start": [14, 12], + "end": [16, 9], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ], + [ + "16000,9000", + { + "meetingPoint": { + "x": 16, + "y": 9 + }, + "connectedWalls": [ + { + "wall": { + "object": "node", + "id": "wall_v5697vc9uc6v70jj", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.2, + "start": [14, 12], + "end": [16, 9], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "end" + }, + { + "wall": { + "object": "node", + "id": "wall_gadr3d6ptj839lwa", + "type": "wall", + "parentId": null, + "visible": true, + "metadata": {}, + "children": [], + "thickness": 0.1, + "start": [16, 9], + "end": [20, 9], + "frontSide": "unknown", + "backSide": "unknown" + }, + "endType": "start" + } + ] + } + ] + ] + }, + "footprints": [ + [ + { + "x": 10.01641028494825, + "y": 9.850900360336059 + }, + { + "x": 10.209613708378917, + "y": 9.875054206242964 + }, + { + "x": 10.402020569773539, + "y": 9.90489663887997 + }, + { + "x": 10.59346341433503, + "y": 9.940401685896267 + }, + { + "x": 10.783775626265705, + "y": 9.981538446676355 + }, + { + "x": 10.97279157377571, + "y": 10.028271119233338 + }, + { + "x": 11.160346753235045, + "y": 10.08055903136799 + }, + { + "x": 11.346277932343716, + "y": 10.138356676066403 + }, + { + "x": 11.530423292195447, + "y": 10.201613751105489 + }, + { + "x": 11.71262256811129, + "y": 10.270275202831813 + }, + { + "x": 11.892717189120553, + "y": 10.344281274075689 + }, + { + "x": 12.070550415967686, + "y": 10.423567556158783 + }, + { + "x": 12.245967477524978, + "y": 10.508065044950046 + }, + { + "x": 12.418815705492364, + "y": 10.597700200921121 + }, + { + "x": 12.588944667267118, + "y": 10.692395013148973 + }, + { + "x": 12.756206296867777, + "y": 10.79206706721006 + }, + { + "x": 12.920455023798343, + "y": 10.896629616906935 + }, + { + "x": 13.081547899740649, + "y": 11.005991659764868 + }, + { + "x": 13.239344722964582, + "y": 11.120058016232758 + }, + { + "x": 13.393708160347902, + "y": 11.238729412519435 + }, + { + "x": 13.544503866899495, + "y": 11.361902566993248 + }, + { + "x": 13.69160060268197, + "y": 11.489470280069737 + }, + { + "x": 13.834870347031899, + "y": 11.621321527509151 + }, + { + "x": 13.974188409978279, + "y": 11.757341557042645 + }, + { + "x": 14.015212481907616, + "y": 11.796903713365376 + }, + { + "x": 13.984787518092386, + "y": 12.203096286634624 + }, + { + "x": 13.761468834398595, + "y": 11.96888441833841 + }, + { + "x": 13.628483410677052, + "y": 11.839047117420074 + }, + { + "x": 13.491725927433937, + "y": 11.713189108500634 + }, + { + "x": 13.351315406914301, + "y": 11.591419927836714 + }, + { + "x": 13.207374050660508, + "y": 11.47384555311171 + }, + { + "x": 13.060027133158247, + "y": 11.3605683112017 + }, + { + "x": 12.909402892808131, + "y": 11.251686789118716 + }, + { + "x": 12.755632420317749, + "y": 11.147295748208869 + }, + { + "x": 12.598849544611298, + "y": 11.047486041680035 + }, + { + "x": 12.439190716356123, + "y": 10.952344535530814 + }, + { + "x": 12.276794889207494, + "y": 10.861954032949683 + }, + { + "x": 12.11180339887499, + "y": 10.776393202250022 + }, + { + "x": 11.944359840115757, + "y": 10.695736508403815 + }, + { + "x": 11.774609941761675, + "y": 10.62005414823359 + }, + { + "x": 11.602701439889195, + "y": 10.549411989318981 + }, + { + "x": 11.428783949242256, + "y": 10.483871512671124 + }, + { + "x": 11.253008833020148, + "y": 10.423489759224724 + }, + { + "x": 11.07552907114369, + "y": 10.36831928019442 + }, + { + "x": 10.896499127114327, + "y": 10.318408091338618 + }, + { + "x": 10.716074813582047, + "y": 10.273799631170588 + }, + { + "x": 10.53441315673913, + "y": 10.234532723153231 + }, + { + "x": 10.35167225965771, + "y": 10.200641541910402 + }, + { + "x": 10.168011164690114, + "y": 10.17215558348417 + }, + { + "x": 9.98358971505175, + "y": 10.149099639663941 + } + ], + [ + { + "x": 14.015212481907616, + "y": 11.796903713365376 + }, + { + "x": 15.913148290817865, + "y": 8.95 + }, + { + "x": 16, + "y": 9 + }, + { + "x": 16.086851709182135, + "y": 9.05 + }, + { + "x": 13.984787518092386, + "y": 12.203096286634624 + }, + { + "x": 14, + "y": 12 + } + ], + [ + { + "x": 15.913148290817865, + "y": 8.95 + }, + { + "x": 20, + "y": 8.95 + }, + { + "x": 20, + "y": 9.05 + }, + { + "x": 16.086851709182135, + "y": 9.05 + }, + { + "x": 16, + "y": 9 + } + ], + [ + { + "x": 22.044721359549996, + "y": -0.022360679774997897 + }, + { + "x": 23.044721359549996, + "y": 1.977639320225002 + }, + { + "x": 22.955278640450004, + "y": 2.022360679774998 + }, + { + "x": 21.955278640450004, + "y": 0.022360679774997897 + } + ] + ], + "polygons": [], + "support": [ + { + "elevation": 0, + "electedSlabId": null, + "baseElevation": 0, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0 + } + ] + }, + { + "elevation": 0, + "electedSlabId": null, + "baseElevation": 0, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0 + } + ] + }, + { + "elevation": 0, + "electedSlabId": null, + "baseElevation": 0, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0 + } + ] + }, + { + "elevation": 0, + "electedSlabId": null, + "baseElevation": 0, + "baseSegments": [ + { + "start": 0, + "end": 1, + "elevation": 0 + } + ] + } + ] + } + } +] diff --git a/packages/core/src/systems/wall/wall-assembly.test.ts b/packages/core/src/systems/wall/wall-assembly.test.ts index bfb2e140ac..2e537b2093 100644 --- a/packages/core/src/systems/wall/wall-assembly.test.ts +++ b/packages/core/src/systems/wall/wall-assembly.test.ts @@ -168,7 +168,7 @@ describe('resolveWallAssembly', () => { 'interior-finish', ]) expect(resolved.exteriorSide).toBeNull() - expect(resolved.exteriorSideResolved).toBe(1) + expect(resolved.exteriorSideResolved).toBe(-1) }) test('a wall with no assembly resolves to one framing layer of its thickness', () => { @@ -186,6 +186,21 @@ describe('resolveWallAssembly', () => { expect(resolveWallExteriorSide({ frontSide: 'unknown', backSide: 'unknown' })).toBeNull() }) + test('an undetermined outside draws the exterior layers on side B, like the 3D cladding', () => { + const unknown = wall('w', [0, 0], [4, 0], { + assembly: EXT_2X6, + frontSide: 'unknown', + backSide: 'unknown', + }) + const back = wall('w', [0, 0], [4, 0], { + assembly: EXT_2X6, + frontSide: 'interior', + backSide: 'exterior', + }) + expect(resolveWallAssembly(unknown).exteriorSideResolved).toBe(-1) + expect(wallLayerBoundaryOffsets(unknown)).toEqual(wallLayerBoundaryOffsets(back)) + }) + test('flipping the exterior side mirrors the boundary offsets', () => { const front = wallLayerBoundaryOffsets( wall('w', [0, 0], [4, 0], { assembly: EXT_2X6, frontSide: 'exterior', backSide: 'interior' }), diff --git a/packages/core/src/systems/wall/wall-assembly.ts b/packages/core/src/systems/wall/wall-assembly.ts index f83af03c49..f6c748d288 100644 --- a/packages/core/src/systems/wall/wall-assembly.ts +++ b/packages/core/src/systems/wall/wall-assembly.ts @@ -36,8 +36,9 @@ * * Fallback when it is `null`: the stack is still drawn at its true total * thickness (thickness must never change because a room was not detected), the - * exterior face is pinned to the +normal side, and `exteriorSideResolved` - * reports the fallback so callers can say so. A wall with both sides interior + * exterior face is pinned to the -normal side (face b, the legacy exterior + * slot the 3D materials already use), and `exteriorSideResolved` reports the + * fallback so callers can say so. A wall with both sides interior * is a PARTITION and should carry a partition assembly — one with neither * `exterior` nor `sheathing`, whose interior finish is then applied to BOTH * faces and no cladding or sheathing is drawn (see `resolveWallAssembly`). @@ -130,7 +131,7 @@ export type ResolvedWallAssembly = { kind: 'envelope' | 'partition' | 'unspecified' /** +1 = exterior on the +normal (front) side, -1 = -normal (back), null = undetermined. */ exteriorSide: 1 | -1 | null - /** `exteriorSide` with the +normal fallback applied. Always a usable sign. */ + /** `exteriorSide` with the -normal (face b) fallback applied. Always a usable sign. */ exteriorSideResolved: 1 | -1 } @@ -391,7 +392,7 @@ function drawnLayer(layer: AssemblyLayer): { role: WallAssemblyLayerRole; materi /** The wall's F2 layers ordered from the exterior face, with the side that faces out. */ function layersOutsideIn(wall: Pick) { const exteriorSide = resolveWallExteriorSide(wall) - const exteriorSideResolved: 1 | -1 = exteriorSide ?? 1 + const exteriorSideResolved: 1 | -1 = exteriorSide ?? -1 const listed = wall.assembly?.layers ?? [] // A front-listed stack reads outside-in when the exterior is the front face. const layers = diff --git a/packages/core/src/systems/wall/wall-curve.ts b/packages/core/src/systems/wall/wall-curve.ts index 8f3e8a739c..f1a646ce3a 100644 --- a/packages/core/src/systems/wall/wall-curve.ts +++ b/packages/core/src/systems/wall/wall-curve.ts @@ -1,4 +1,5 @@ import type { FenceNode, WallNode } from '../../schema' +import { getWallFaceOffsets } from './wall-frame' import type { Point2D } from './wall-mitering' const CURVE_EPSILON = 1e-6 @@ -290,11 +291,12 @@ export function getWallCurveLength(wall: WallCurveLike, segments = DEFAULT_SAMPL } export function getWallSurfacePolygon( - wall: Pick, + wall: Pick & + Pick, segments = DEFAULT_SAMPLE_SEGMENTS, miterOverrides?: WallSurfaceMiterOverrides, ) { - const halfThickness = (wall.thickness ?? 0.1) / 2 + const { a, b } = getWallFaceOffsets(wall) const count = Math.max(1, segments) const left: Point2D[] = [] const right: Point2D[] = [] @@ -302,12 +304,12 @@ export function getWallSurfacePolygon( for (let index = 0; index <= count; index += 1) { const frame = getWallCurveFrameAt(wall, index / count) left.push({ - x: frame.point.x + frame.normal.x * halfThickness, - y: frame.point.y + frame.normal.y * halfThickness, + x: frame.point.x + frame.normal.x * a, + y: frame.point.y + frame.normal.y * a, }) right.push({ - x: frame.point.x - frame.normal.x * halfThickness, - y: frame.point.y - frame.normal.y * halfThickness, + x: frame.point.x - frame.normal.x * -b, + y: frame.point.y - frame.normal.y * -b, }) } @@ -320,3 +322,22 @@ export function getWallSurfacePolygon( return [...right, ...left.reverse()] } + +export function getWallCurveStationAtPoint( + wall: WallCurveLike, + point: readonly [number, number], +): number { + const arc = getWallArcData(wall) + if (!arc) { + const chord = getWallChordFrame(wall) + return clamp01( + ((point[0] - chord.start.x) * chord.tangent.x + + (point[1] - chord.start.y) * chord.tangent.y) / + chord.length, + ) + } + let angle = Math.atan2(point[1] - arc.center.y, point[0] - arc.center.x) - arc.startAngle + if (arc.delta > 0 && angle < 0) angle += Math.PI * 2 + if (arc.delta < 0 && angle > 0) angle -= Math.PI * 2 + return clamp01(angle / arc.delta) +} diff --git a/packages/core/src/systems/wall/wall-finish.test.ts b/packages/core/src/systems/wall/wall-finish.test.ts new file mode 100644 index 0000000000..cbd0b051a1 --- /dev/null +++ b/packages/core/src/systems/wall/wall-finish.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, test } from 'bun:test' +import { extractRooms } from '../../lib/room-graph' +import { WallNode } from '../../schema/nodes/wall' +import { ZoneNode } from '../../schema/nodes/zone' +import { + buildWallFinishLayout, + getWallZoneSpans, + resolveWallFaceChain, + resolveWallFinish, + type WallFinishHit, + wallFinishMaterialIndex, +} from './wall-finish' + +// Two rooms side by side on the a side (+z) of one long wall; the partition +// meets the long wall mid-span (a T-junction at x = 4). Side b faces outside. +// +// z=4 +-------+-------+ +// | A | B | +// z=0 +=======+=======+ ← host wall 0 → 8 (face a up, face b down) +function tJunction(host: Partial = {}) { + const wall = (id: string, start: [number, number], end: [number, number], extra = {}) => + WallNode.parse({ id, parentId: 'level_t', start, end, ...extra }) + const walls = [ + wall('wall_host', [0, 0], [8, 0], host), + wall('wall_east', [8, 0], [8, 4]), + wall('wall_north', [8, 4], [0, 4]), + wall('wall_west', [0, 4], [0, 0]), + wall('wall_partition', [4, 0], [4, 4]), + ] + const rooms = extractRooms(walls) + expect(rooms).toHaveLength(2) + const zone = (name: 'A' | 'B', extra: Partial = {}) => { + const room = rooms.find((candidate) => + candidate.referencePolygon.every(([x]) => (name === 'A' ? x <= 4 : x >= 4)), + )! + return ZoneNode.parse({ + id: `zone_${name}`, + parentId: 'level_t', + name, + spaceRole: 'room', + autoFromWalls: true, + polygon: room.referencePolygon, + holes: room.holes, + boundaryWallIds: [...new Set(room.spans.map((span) => span.boundaryId))], + ...extra, + }) + } + return { host: walls[0]!, zone } +} + +const describeHit = (hit: WallFinishHit) => + hit.source === 'slot' ? 'slot' : `${hit.source}:${hit.ref}` + +describe('wall face spans from zones', () => { + test('a long wall bordering two rooms on one face splits at the T-junction', () => { + const { host, zone } = tJunction() + expect(getWallZoneSpans(host, [zone('A'), zone('B')])).toEqual([ + { zoneId: 'zone_A', face: 'a', t0: 0, t1: 0.5 }, + { zoneId: 'zone_B', face: 'a', t0: 0.5, t1: 1 }, + ]) + }) + + test('the face follows the wall direction, not the room', () => { + const { host, zone } = tJunction() + const reversed = { ...host, start: host.end, end: host.start } + expect(getWallZoneSpans(reversed, [zone('A'), zone('B')])).toEqual([ + { zoneId: 'zone_B', face: 'b', t0: 0, t1: 0.5 }, + { zoneId: 'zone_A', face: 'b', t0: 0.5, t1: 1 }, + ]) + }) + + test('a zone that does not list the wall contributes nothing', () => { + const { host, zone } = tJunction() + expect(getWallZoneSpans(host, [zone('A', { boundaryWallIds: [] })])).toEqual([]) + }) +}) + +describe('wall finish resolution order', () => { + // region > zone override for this face > zone wallMaterial > wall face slot > kind default + test('each level wins over the ones below it, per span of the T-junction', () => { + const { host, zone } = tJunction({ + slots: { a: 'library:slot-a' }, + faceRegions: [{ id: 'wainscot', face: 'a', u0: 1, u1: 5, v1: 0.9, finish: 'library:wood' }], + }) + const zones = [ + zone('A', { wallMaterial: 'library:room-a' }), + zone('B', { + wallMaterial: 'library:room-b', + wallOverrides: [{ wallId: 'wall_host', face: 'a', finish: 'library:override-b' }], + }), + ] + const layout = buildWallFinishLayout(host, zones) + const at = (face: 'a' | 'b', u: number, v: number) => + describeHit(resolveWallFinish(layout, face, u, v)) + + const table: Array<[string, ReturnType, string]> = [ + ['region over room A', at('a', 2, 0.5), 'region:library:wood'], + ['region over room B override', at('a', 4.5, 0.5), 'region:library:wood'], + ['room A above the region', at('a', 2, 1.5), 'zone:library:room-a'], + ['room A beside the region', at('a', 0.5, 0.5), 'zone:library:room-a'], + ['room B override beats its room finish', at('a', 6, 0.5), 'override:library:override-b'], + ['room B override above the region', at('a', 4.5, 1.5), 'override:library:override-b'], + ['outside face falls back to the face slot', at('b', 2, 0.5), 'slot'], + [ + 'mitred corner past the end stays in room B', + at('a', 8.05, 1), + 'override:library:override-b', + ], + ] + for (const [label, actual, expected] of table) + expect([label, actual]).toEqual([label, expected]) + + expect(resolveWallFaceChain(host, 'a')).toEqual({ kind: 'ref', ref: 'library:slot-a' }) + expect(resolveWallFaceChain(host, 'b')).toEqual({ + kind: 'default', + ref: 'library:concrete-drywall', + }) + }) + + test('removing each level exposes the next one', () => { + const { host, zone } = tJunction() + const at = (wall: WallNode, zones: ZoneNode[]) => + describeHit(resolveWallFinish(buildWallFinishLayout(wall, zones), 'a', 6, 0.5)) + const region = { id: 'r', face: 'a' as const, finish: 'library:region' } + const override = [{ wallId: 'wall_host', face: 'a' as const, finish: 'library:override' }] + const withSlot = { ...host, slots: { a: 'library:slot' } } + + expect( + at({ ...withSlot, faceRegions: [region] }, [ + zone('B', { wallMaterial: 'library:zone', wallOverrides: override }), + ]), + ).toBe('region:library:region') + expect( + at(withSlot, [zone('B', { wallMaterial: 'library:zone', wallOverrides: override })]), + ).toBe('override:library:override') + expect(at(withSlot, [zone('B', { wallMaterial: 'library:zone' })])).toBe('zone:library:zone') + expect(at(withSlot, [zone('B')])).toBe('slot') + expect(resolveWallFaceChain(withSlot, 'a')).toEqual({ kind: 'ref', ref: 'library:slot' }) + expect(resolveWallFaceChain(host, 'a')).toEqual({ + kind: 'default', + ref: 'library:concrete-drywall', + }) + }) + + test('later regions win and legacy inline finishes sit between slot and default', () => { + const wall = WallNode.parse({ + start: [0, 0], + end: [4, 0], + faceRegions: [ + { id: 'low', face: 'b', v1: 1, finish: 'library:first' }, + { id: 'strip', face: 'b', v0: 0.5, v1: 0.7, finish: 'library:second' }, + ], + legacyFaceMaterials: { b: { materialPreset: 'library:legacy-b' } }, + materialPreset: 'library:legacy-wall', + }) + const layout = buildWallFinishLayout(wall, []) + expect(describeHit(resolveWallFinish(layout, 'b', 1, 0.6))).toBe('region:library:second') + expect(describeHit(resolveWallFinish(layout, 'b', 1, 0.2))).toBe('region:library:first') + expect(resolveWallFaceChain(wall, 'b')).toEqual({ + kind: 'legacy', + spec: { material: undefined, materialPreset: 'library:legacy-b' }, + }) + expect(resolveWallFaceChain(wall, 'a')).toEqual({ + kind: 'legacy', + spec: { material: undefined, materialPreset: 'library:legacy-wall' }, + }) + }) +}) + +describe('wall finish layout', () => { + test('plain walls need no splits and draw faces with indices 1 and 2', () => { + const { host, zone } = tJunction() + const layout = buildWallFinishLayout(host, [zone('A'), zone('B')]) + expect(layout).toMatchObject({ plain: true, uSplits: [], vSplits: [], refs: [] }) + expect(wallFinishMaterialIndex(layout, 'a', { source: 'slot' })).toBe(1) + expect(wallFinishMaterialIndex(layout, 'b', { source: 'slot' })).toBe(2) + }) + + test('splits only at bounds that exist and indexes extra finishes canonically', () => { + const { host, zone } = tJunction({ + slots: { b: 'library:shared' }, + faceRegions: [{ id: 'r', face: 'b', u0: 2, v0: 0.3, v1: 0.9, finish: 'library:z-last' }], + }) + const layout = buildWallFinishLayout(host, [ + zone('A', { wallMaterial: 'library:shared' }), + zone('B', { wallMaterial: 'library:a-first' }), + ]) + expect(layout.plain).toBe(false) + expect(layout.uSplits).toEqual([2, 4]) + expect(layout.vSplits).toEqual([0.3, 0.9]) + // A finish equal to a face slot still gets its own entry: indices 1 / 2 are + // the face chains alone, so previewing a face slot never repaints a room span. + expect(layout.refs).toEqual(['library:a-first', 'library:shared', 'library:z-last']) + const index = (face: 'a' | 'b', u: number, v: number) => + wallFinishMaterialIndex(layout, face, resolveWallFinish(layout, face, u, v)) + expect(index('a', 1, 1)).toBe(4) + expect(index('a', 6, 1)).toBe(3) + expect(index('b', 3, 0.5)).toBe(5) + expect(index('b', 3, 1.5)).toBe(2) + }) +}) diff --git a/packages/core/src/systems/wall/wall-finish.ts b/packages/core/src/systems/wall/wall-finish.ts new file mode 100644 index 0000000000..544f731fde --- /dev/null +++ b/packages/core/src/systems/wall/wall-finish.ts @@ -0,0 +1,387 @@ +import { containsPoint } from '../../lib/polygon-boolean' +import { sampleWallPointsForRoomDetection, WALL_JUNCTION_TOLERANCE } from '../../lib/room-graph' +import type { AnyNode, AnyNodeId } from '../../schema' +import { + getEffectiveWallFaceMaterial, + WALL_FACE_REGION_LIMIT, + WALL_SLOT_DEFAULT, + type WallFace, + type WallFaceRegion, + type WallNode, + type WallSurfaceMaterialSpec, +} from '../../schema/nodes/wall' +import type { ZoneNode } from '../../schema/nodes/zone' +import { isCurvedWall } from './wall-curve' + +// Which finish shows at a point of a wall face. Resolution order, highest first: +// face paint region → zone `wallOverrides` for this wall face → `wallMaterial` +// of the zone that span faces → the wall's own face chain (slot → legacy → default). +// Spans come from the zones' stored reference polygons, so a long wall bordering +// two rooms on one face splits at the T-junction (span t0..t1). + +/** A stretch of one wall face bordering one zone, in reference-line parameter space. */ +export type WallZoneSpan = { zoneId: string; face: WallFace; t0: number; t1: number } + +export type WallFinishSpan = { + zoneId: string + u0: number + u1: number + ref: string + source: 'override' | 'zone' +} + +export type WallFinishHit = + | { source: 'region'; ref: string; regionId: string } + | { source: 'override' | 'zone'; ref: string; zoneId: string } + | { source: 'slot' } + +export type WallFinishLayout = { + /** Reference chord length (m); `u` runs 0..length. */ + length: number + /** True when no region or room finish touches the wall: no splits, two face groups. */ + plain: boolean + regions: Record + spans: Record + /** Stations (m from start) where triangles must split: region and span bounds. */ + uSplits: number[] + /** Heights (m above the face base) where triangles must split: region bounds. */ + vSplits: number[] + /** + * Finish refs beyond the two face slots, sorted — material indices 3.. of the + * wall's palette (0 = caps, 1 = face a chain, 2 = face b chain). + */ + refs: string[] +} + +const FACE_PROBE = 0.01 +const SPLIT_EPSILON = 1e-6 + +function chord(wall: Pick) { + // Unhealed saves can carry non-tuple endpoints; they have no faces to finish. + if (!(Array.isArray(wall.start) && Array.isArray(wall.end))) return { dx: 0, dz: 0, length: 0 } + const dx = wall.end[0] - wall.start[0] + const dz = wall.end[1] - wall.start[1] + const length = Math.hypot(dx, dz) + return { dx, dz, length: Number.isFinite(length) ? length : 0 } +} + +function distanceToPolyline(point: [number, number], polyline: { x: number; y: number }[]) { + let best = Number.POSITIVE_INFINITY + for (let index = 0; index < polyline.length - 1; index += 1) { + const a = polyline[index]! + const b = polyline[index + 1]! + const dx = b.x - a.x + const dy = b.y - a.y + const lengthSquared = dx * dx + dy * dy + const t = + lengthSquared < 1e-12 + ? 0 + : Math.max(0, Math.min(1, ((point[0] - a.x) * dx + (point[1] - a.y) * dy) / lengthSquared)) + best = Math.min(best, Math.hypot(point[0] - (a.x + dx * t), point[1] - (a.y + dy * t))) + } + return best +} + +/** + * Stretches of each wall face bordering a zone that lists the wall among its + * boundary walls. Derived from the zone's stored reference polygon (outer ring + * and holes): an edge lying on the wall's reference line borders that wall, and + * the side the zone interior lies on names the face (a = left of start → end). + */ +export function getWallZoneSpans( + wall: Pick, + zones: readonly Pick[], +): WallZoneSpan[] { + const { dx, dz, length } = chord(wall) + if (length < 1e-9) return [] + const curved = isCurvedWall(wall) + const polyline = sampleWallPointsForRoomDetection(wall) + const tolerance = WALL_JUNCTION_TOLERANCE + 1e-6 + const rawStation = (point: readonly [number, number]) => + ((point[0] - wall.start[0]) * dx + (point[1] - wall.start[1]) * dz) / (length * length) + const lineDistance = (point: readonly [number, number]) => + Math.abs((point[0] - wall.start[0]) * dz - (point[1] - wall.start[1]) * dx) / length + const spans: WallZoneSpan[] = [] + for (const zone of [...zones].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) { + if (!zone.boundaryWallIds?.includes(wall.id as never)) continue + const shape = [{ outer: zone.polygon, holes: zone.holes ?? [] }] + for (const ring of [zone.polygon, ...(zone.holes ?? [])]) { + if (ring.length < 3) continue + for (let index = 0; index < ring.length; index += 1) { + const p = ring[index]! + const q = ring[(index + 1) % ring.length]! + const ex = q[0] - p[0] + const ez = q[1] - p[1] + const edgeLength = Math.hypot(ex, ez) + if (edgeLength < 1e-9) continue + let t0: number + let t1: number + if (curved) { + // An arc's sampled facets are room edges one to one. + const mid: [number, number] = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2] + if ( + distanceToPolyline(p, polyline) > tolerance || + distanceToPolyline(q, polyline) > tolerance || + distanceToPolyline(mid, polyline) > tolerance + ) + continue + t0 = Math.max(0, Math.min(rawStation(p), rawStation(q), 1)) + t1 = Math.min(1, Math.max(rawStation(p), rawStation(q), 0)) + } else { + // A straight edge on the wall's line borders it where the two overlap, + // even when the edge also runs along a collinear neighbour. + if (lineDistance(p) > tolerance || lineDistance(q) > tolerance) continue + t0 = Math.max(0, Math.min(rawStation(p), rawStation(q))) + t1 = Math.min(1, Math.max(rawStation(p), rawStation(q))) + } + if ((t1 - t0) * length < 1e-6) continue + // Probe across the edge at the middle of the shared stretch. + const tm = (t0 + t1) / 2 + const edgeT = Math.max( + 0, + Math.min( + 1, + ((wall.start[0] + dx * tm - p[0]) * ex + (wall.start[1] + dz * tm - p[1]) * ez) / + (edgeLength * edgeLength), + ), + ) + const mid: [number, number] = [p[0] + ex * edgeT, p[1] + ez * edgeT] + const along = ex * dx + ez * dz >= 0 ? 1 : -1 + const nx = (-ez / edgeLength) * along + const nz = (ex / edgeLength) * along + const left = containsPoint(shape, [mid[0] + nx * FACE_PROBE, mid[1] + nz * FACE_PROBE]) + const right = containsPoint(shape, [mid[0] - nx * FACE_PROBE, mid[1] - nz * FACE_PROBE]) + if (left === right) continue + spans.push({ zoneId: zone.id, face: left ? 'a' : 'b', t0, t1 }) + } + } + } + spans.sort( + (a, b) => a.face.localeCompare(b.face) || a.t0 - b.t0 || (a.zoneId < b.zoneId ? -1 : 1), + ) + const merged: WallZoneSpan[] = [] + for (const span of spans) { + const last = merged.at(-1) + if ( + last && + last.face === span.face && + last.zoneId === span.zoneId && + span.t0 <= last.t1 + SPLIT_EPSILON + ) { + last.t1 = Math.max(last.t1, span.t1) + continue + } + merged.push({ ...span }) + } + return merged +} + +/** Zones on the wall's level, the only ones that can border it. */ +export function getWallLevelZones( + wall: Pick, + nodes: Readonly>, +): ZoneNode[] { + const level = wall.parentId ? nodes[wall.parentId as AnyNodeId] : undefined + const childIds = (level as { children?: readonly string[] } | undefined)?.children + if (!Array.isArray(childIds)) return [] + const zones: ZoneNode[] = [] + for (const id of childIds) { + const child = nodes[id] + if (child?.type === 'zone') zones.push(child) + } + return zones +} + +/** Whether a zone carries any finish its boundary walls render. */ +export function zoneHasWallFinish(zone: Pick): boolean { + return zone.wallMaterial !== undefined || (zone.wallOverrides?.length ?? 0) > 0 +} + +function regionIsEmpty(region: WallFaceRegion): boolean { + return ( + (region.u0 !== undefined && + region.u1 !== undefined && + region.u1 - region.u0 <= SPLIT_EPSILON) || + (region.v0 !== undefined && region.v1 !== undefined && region.v1 - region.v0 <= SPLIT_EPSILON) + ) +} + +function uniqueSorted(values: number[]): number[] { + const out: number[] = [] + for (const value of [...values].sort((a, b) => a - b)) { + if (out.length === 0 || value - out.at(-1)! > SPLIT_EPSILON) out.push(value) + } + return out +} + +export function buildWallFinishLayout( + wall: Pick, + zones: readonly ZoneNode[], +): WallFinishLayout { + const { length } = chord(wall) + const regions: Record = { a: [], b: [] } + for (const face of ['a', 'b'] as const) { + regions[face] = (wall.faceRegions ?? []) + .filter((region) => region.face === face && !regionIsEmpty(region)) + .slice(-WALL_FACE_REGION_LIMIT) + } + + const spans: Record = { a: [], b: [] } + const finishZones = zones.filter( + (zone) => + zone.wallMaterial !== undefined || + zone.wallOverrides?.some((entry) => entry.wallId === wall.id), + ) + if (finishZones.length > 0) { + const byId = new Map(finishZones.map((zone) => [zone.id, zone])) + for (const span of getWallZoneSpans(wall, finishZones)) { + const zone = byId.get(span.zoneId)! + const override = zone.wallOverrides?.find( + (entry) => entry.wallId === wall.id && entry.face === span.face, + ) + const ref = override?.finish ?? zone.wallMaterial + if (ref === undefined) continue + // A span reaching a wall end runs past it, over the mitred corner of the face. + spans[span.face].push({ + zoneId: zone.id, + u0: span.t0 <= SPLIT_EPSILON ? Number.NEGATIVE_INFINITY : span.t0 * length, + u1: span.t1 >= 1 - SPLIT_EPSILON ? Number.POSITIVE_INFINITY : span.t1 * length, + ref, + source: override ? 'override' : 'zone', + }) + } + } + + const all = [...regions.a, ...regions.b] + const allSpans = [...spans.a, ...spans.b] + const inside = (value: number | undefined): value is number => + value !== undefined && value > SPLIT_EPSILON && value < length - SPLIT_EPSILON + const uSplits = uniqueSorted([ + ...all.flatMap((region) => [region.u0, region.u1].filter(inside)), + ...allSpans.flatMap((span) => [span.u0, span.u1].filter(inside)), + ]) + const vSplits = uniqueSorted( + all.flatMap((region) => + [region.v0, region.v1].filter((value): value is number => value !== undefined), + ), + ) + // Always their own entries, even when a ref equals a face slot: index 1 / 2 + // must stay the face chains alone, so a face-slot preview never repaints a + // region. Equal materials still share a batch run (canonical batch key). + const refs = [ + ...new Set([...all.map((region) => region.finish), ...allSpans.map((span) => span.ref)]), + ].sort() + + return { + length, + plain: all.length === 0 && allSpans.length === 0, + regions, + spans, + uSplits, + vSplits, + refs, + } +} + +function within(value: number, low: number | undefined, high: number | undefined) { + return (low === undefined || value >= low) && (high === undefined || value < high) +} + +/** + * The finish at station `u` (m from the wall start) and height `v` (m above the + * face's own base) of one face. `{ source: 'slot' }` means the wall's own face + * chain: `slots[face]` → legacy inline finish → the kind default. + */ +export function resolveWallFinish( + layout: WallFinishLayout, + face: WallFace, + u: number, + v: number, +): WallFinishHit { + const regions = layout.regions[face] + for (let index = regions.length - 1; index >= 0; index -= 1) { + const region = regions[index]! + if (within(u, region.u0, region.u1) && within(v, region.v0, region.v1)) + return { source: 'region', ref: region.finish, regionId: region.id } + } + for (const span of layout.spans[face]) { + if (u >= span.u0 && u < span.u1) + return { source: span.source, ref: span.ref, zoneId: span.zoneId } + } + return { source: 'slot' } +} + +/** Palette index for a resolved finish: 1 / 2 for a face chain, 3.. for `layout.refs`. */ +export function wallFinishMaterialIndex( + layout: WallFinishLayout, + face: WallFace, + hit: WallFinishHit, +): number { + if (hit.source === 'slot') return face === 'a' ? 1 : 2 + const index = layout.refs.indexOf(hit.ref) + return index < 0 ? (face === 'a' ? 1 : 2) : 3 + index +} + +/** + * The wall's own chain for one face, in the order the renderer walks it: + * `slots[face]` ref → legacy inline finish (per-face, then wall-wide) → the + * declared default. A dangling ref renders the declared default. + */ +export type WallFaceChainFinish = + | { kind: 'ref'; ref: string } + | { kind: 'legacy'; spec: WallSurfaceMaterialSpec } + | { kind: 'default'; ref: string } + +export function resolveWallFaceChain( + wall: Pick, + face: WallFace, +): WallFaceChainFinish { + const ref = wall.slots?.[face] + if (ref) return { kind: 'ref', ref } + const spec = getEffectiveWallFaceMaterial(wall, face) + if (spec.materialPreset || spec.material) return { kind: 'legacy', spec } + return { kind: 'default', ref: WALL_SLOT_DEFAULT[face] } +} + +// Paint roles a wall resolves to (the paint tool offers `room:`): +// `a` / `b` / `aSkirting` … a wall slot +// `region:` one paint region on the wall +// `room:/` this wall face inside that room (zone `wallOverrides`) +// `room:` every wall of that room (zone `wallMaterial`) +export type WallPaintRole = + | { kind: 'slot'; slotId: string } + | { kind: 'region'; regionId: string } + | { kind: 'room'; zoneId: string } + | { kind: 'room-face'; zoneId: string; face: WallFace } + +export function wallRegionRole(regionId: string): string { + return `region:${regionId}` +} + +/** "This room's walls": paints the zone's `wallMaterial`. */ +export function wallRoomFinishRole(zoneId: string): string { + return `room:${zoneId}` +} + +/** "This wall face" inside a room: paints a zone `wallOverrides` entry. */ +export function wallRoomFaceRole(zoneId: string, face: WallFace): string { + return `room:${zoneId}/${face}` +} + +export function parseWallPaintRole( + role: string, + isSlot: (slotId: string) => boolean, +): WallPaintRole | null { + if (isSlot(role)) return { kind: 'slot', slotId: role } + if (role.startsWith('region:')) { + const regionId = role.slice('region:'.length) + return regionId ? { kind: 'region', regionId } : null + } + if (!role.startsWith('room:')) return null + const rest = role.slice('room:'.length) + const slash = rest.indexOf('/') + if (slash < 0) return rest ? { kind: 'room', zoneId: rest } : null + const zoneId = rest.slice(0, slash) + const face = rest.slice(slash + 1) + return zoneId && (face === 'a' || face === 'b') ? { kind: 'room-face', zoneId, face } : null +} diff --git a/packages/core/src/systems/wall/wall-footprint.ts b/packages/core/src/systems/wall/wall-footprint.ts index 63cb1da19e..4a363ca878 100644 --- a/packages/core/src/systems/wall/wall-footprint.ts +++ b/packages/core/src/systems/wall/wall-footprint.ts @@ -1,5 +1,6 @@ import type { WallNode } from '../../schema' import { getWallSurfacePolygon, isCurvedWall } from './wall-curve' +import { getWallFaceOffsets } from './wall-frame' import { getWallMiterBoundaryPoints, type Point2D, @@ -7,7 +8,9 @@ import { type WallMiterData, } from './wall-mitering' +export { faceOnLine, justificationForFaceOnLine } from './wall-frame' export { calculateLevelMiters, type Point2D, type WallMiterData } from './wall-mitering' +export { roomSideFaces } from './wall-room-sides' export const DEFAULT_WALL_THICKNESS = 0.1 export const DEFAULT_WALL_HEIGHT = 2.5 @@ -21,8 +24,7 @@ export function getWallPlanFootprint(wallNode: WallNode, miterData: WallMiterDat const { junctionData } = miterData const wallStart: Point2D = { x: wallNode.start[0], y: wallNode.start[1] } const wallEnd: Point2D = { x: wallNode.end[0], y: wallNode.end[1] } - const thickness = getWallThickness(wallNode) - const halfT = thickness / 2 + const { a, b } = getWallFaceOffsets(wallNode) const v = { x: wallEnd.x - wallStart.x, y: wallEnd.y - wallStart.y } const L = Math.sqrt(v.x * v.x + v.y * v.y) @@ -52,29 +54,29 @@ export function getWallPlanFootprint(wallNode: WallNode, miterData: WallMiterDat } const pStartLeft: Point2D = startJunction?.left || { - x: wallStart.x + nUnit.x * halfT, - y: wallStart.y + nUnit.y * halfT, + x: wallStart.x + nUnit.x * a, + y: wallStart.y + nUnit.y * a, } const pStartRight: Point2D = startJunction?.right || { - x: wallStart.x - nUnit.x * halfT, - y: wallStart.y - nUnit.y * halfT, + x: wallStart.x - nUnit.x * -b, + y: wallStart.y - nUnit.y * -b, } const pEndLeft: Point2D = endJunction?.right || { - x: wallEnd.x + nUnit.x * halfT, - y: wallEnd.y + nUnit.y * halfT, + x: wallEnd.x + nUnit.x * a, + y: wallEnd.y + nUnit.y * a, } const pEndRight: Point2D = endJunction?.left || { - x: wallEnd.x - nUnit.x * halfT, - y: wallEnd.y - nUnit.y * halfT, + x: wallEnd.x - nUnit.x * -b, + y: wallEnd.y - nUnit.y * -b, } const polygon: Point2D[] = [pStartRight, pEndRight] if (endJunction) { - polygon.push(wallEnd) + polygon.push(endJunction.closing ?? wallEnd) } polygon.push(pEndLeft, pStartLeft) if (startJunction) { - polygon.push(wallStart) + polygon.push(startJunction.closing ?? wallStart) } return polygon diff --git a/packages/core/src/systems/wall/wall-frame.test.ts b/packages/core/src/systems/wall/wall-frame.test.ts new file mode 100644 index 0000000000..e42b977340 --- /dev/null +++ b/packages/core/src/systems/wall/wall-frame.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, test } from 'bun:test' +import { getRenderableSlabPolygon } from '../../lib/slab-polygon' +import { SlabNode, WallNode } from '../../schema' +import { computeWallSlabSupport } from '../slab/slab-support' +import golden from './__fixtures__/wall-frame-golden.json' +import { getWallCurveFrameAt } from './wall-curve' +import { getWallPlanFootprint } from './wall-footprint' +import { + getWallBodyCenterOffset, + getWallBodyLine, + getWallFaceLine, + getWallFaceOffsets, + getWallLocalFaceZ, + reverseWallDirection, +} from './wall-frame' +import { calculateLevelMiters } from './wall-mitering' + +describe('wall reference frame', () => { + for (const justification of [undefined, 'a', 'b'] as const) { + test(`offsets, face lines and body line: ${justification ?? 'center'}`, () => { + const wall = WallNode.parse({ start: [0, 0], end: [4, 0], thickness: 0.2, justification }) + const a = justification === 'a' ? 0.2 : justification === 'b' ? 0 : 0.1 + const b = justification === 'a' ? 0 : justification === 'b' ? -0.2 : -0.1 + expect(getWallFaceOffsets(wall)).toEqual({ a, b }) + expect(a - b).toBe(wall.thickness!) + expect(getWallBodyCenterOffset(wall)).toBe((a + b) / 2) + expect(getWallBodyLine(wall)).toEqual({ + start: { x: 0, y: (a + b) / 2 }, + end: { x: 4, y: (a + b) / 2 }, + }) + for (const face of ['a', 'b'] as const) { + const offset = face === 'a' ? a : b + expect(getWallFaceLine(wall, face)).toEqual({ + start: { x: 0, y: offset }, + end: { x: 4, y: offset }, + }) + expect(getWallLocalFaceZ(wall, face)).toBe(offset) + } + }) + + test(`reversal preserves the body and round-trips sparse data: ${justification ?? 'center'}`, () => { + const wall = WallNode.parse({ + start: [1, 2], + end: [5, 4], + thickness: 0.2, + ...(justification ? { justification } : {}), + frontSide: 'interior', + backSide: 'exterior', + slots: { a: 'library:left', b: 'library:right', aSkirting: 'library:trim' }, + legacyFaceMaterials: { a: { materialPreset: 'library:legacy-left' } }, + faceRegions: [{ id: 'r', face: 'a', u0: 1, v1: 0.9, finish: 'library:wainscot' }], + skirting: { enabled: true, sides: 'a' }, + }) + for (const original of [wall, { ...wall, curveOffset: 0.4 }]) { + const reversed = { ...original, ...reverseWallDirection(original) } + expect({ ...reversed, ...reverseWallDirection(reversed) }).toEqual(original) + // Face-keyed data follows the faces; stations are re-measured from the new start. + expect(reversed.slots).toEqual({ + b: 'library:left', + a: 'library:right', + bSkirting: 'library:trim', + }) + expect(reversed.legacyFaceMaterials).toEqual({ + b: { materialPreset: 'library:legacy-left' }, + }) + const length = Math.hypot(4, 2) + expect(reversed.faceRegions).toEqual([ + { id: 'r', face: 'b', u1: length - 1, v1: 0.9, finish: 'library:wainscot' }, + ]) + expect(reversed.skirting?.sides).toBe('b') + expect(reversed.frontSide).toBe(original.backSide) + expect(reversed.backSide).toBe(original.frontSide) + expect('justification' in reversed).toBe('justification' in original) + expect('curveOffset' in reversed).toBe('curveOffset' in original) + for (const t of [0, 0.25, 0.5, 1]) { + const before = getWallCurveFrameAt(original, t) + const after = getWallCurveFrameAt(reversed, 1 - t) + expect(after.point.x).toBeCloseTo(before.point.x, 12) + expect(after.point.y).toBeCloseTo(before.point.y, 12) + } + const before = getWallFaceOffsets(original) + const after = getWallFaceOffsets(reversed) + expect(after.a).toBeCloseTo(-before.b, 12) + expect(after.b).toBeCloseTo(-before.a, 12) + } + }) + } + + test('local face z matches the viewer world-to-local rotation', () => { + for (const end of [ + [4, 0], + [0, 4], + [3, -4], + [-3, -4], + ] as [number, number][]) { + for (const justification of [undefined, 'a', 'b'] as const) { + const wall = WallNode.parse({ start: [0, 0], end, thickness: 0.2, justification }) + const angle = Math.atan2(end[1], end[0]) + for (const face of ['a', 'b'] as const) { + const point = getWallFaceLine(wall, face).start + expect(point.x * Math.sin(-angle) + point.y * Math.cos(-angle)).toBeCloseTo( + getWallLocalFaceZ(wall, face), + 14, + ) + } + } + } + }) + + test('absence remains absent and degenerate lines stay finite', () => { + const wall = WallNode.parse({ start: [0, 0], end: [0, 0] }) + expect('justification' in wall).toBe(false) + expect(getWallFaceOffsets(wall)).toEqual({ a: 0.05, b: -0.05 }) + expect(getWallBodyLine({ ...wall, justification: 'a' })).toEqual({ + start: { x: 0, y: 0 }, + end: { x: 0, y: 0 }, + }) + }) +}) + +test('centered walls match the pre-kernel golden byte for byte', () => { + const serialize = (value: unknown) => + JSON.stringify(value, (_, entry) => (entry instanceof Map ? [...entry.entries()] : entry)) + for (const fixture of golden) { + const walls = fixture.walls.map((wall) => WallNode.parse(wall)) + const slabs = fixture.slabs.map((slab) => SlabNode.parse(slab)) + const miters = calculateLevelMiters(walls) + expect( + serialize({ + miters, + footprints: walls.map((wall) => getWallPlanFootprint(wall, miters)), + polygons: slabs.map((slab) => + getRenderableSlabPolygon(slab, { + walls, + siblingSlabs: slabs.filter((other) => other.id !== slab.id), + }), + ), + support: walls.map((wall) => { + const { + faceDatum, + faceBottom: _bottom, + ...legacy + } = computeWallSlabSupport(wall, slabs, walls) + expect(faceDatum.a).toEqual(legacy.baseSegments) + expect(faceDatum.b).toEqual(legacy.baseSegments) + return legacy + }), + }), + ).toBe(serialize(fixture.output)) + } +}) diff --git a/packages/core/src/systems/wall/wall-frame.ts b/packages/core/src/systems/wall/wall-frame.ts new file mode 100644 index 0000000000..be9fce693c --- /dev/null +++ b/packages/core/src/systems/wall/wall-frame.ts @@ -0,0 +1,196 @@ +import type { SceneNodes } from '../../lib/structure-kernel' +import type { WallNode } from '../../schema/nodes/wall' +import { getWallArcData } from './wall-curve' +import type { Point2D } from './wall-mitering' + +// Stored endpoints define the reference line: a is left, b is right. +// Endpoint snapping and room topology use that line; faces, hosted objects +// and body handles use its offsets. Justification moves the body, never the line. +export type WallJustification = 'a' | 'b' +export type WallFaceOffsets = { a: number; b: number } + +type WallFrame = Pick +type WallLine = WallFrame & Pick + +export function getWallFaceOffsets(wall: WallFrame): WallFaceOffsets { + const thickness = wall.thickness ?? 0.1 + if (wall.justification === 'a') return { a: thickness, b: 0 } + if (wall.justification === 'b') return { a: 0, b: -thickness } + return { a: thickness / 2, b: -thickness / 2 } +} + +export function getWallBodyCenterOffset(wall: WallFrame): number { + const { a, b } = getWallFaceOffsets(wall) + return (a + b) / 2 +} + +function offsetLine(wall: WallLine, offset: number): { start: Point2D; end: Point2D } { + const start = { x: wall.start[0], y: wall.start[1] } + const end = { x: wall.end[0], y: wall.end[1] } + const dx = end.x - start.x + const dy = end.y - start.y + const length = Math.hypot(dx, dy) + if (offset === 0 || length < 1e-9) return { start, end } + const nx = (-dy / length) * offset + const ny = (dx / length) * offset + return { + start: { x: start.x + nx, y: start.y + ny }, + end: { x: end.x + nx, y: end.y + ny }, + } +} + +export function getWallBodyLine(wall: WallLine): { start: Point2D; end: Point2D } { + return offsetLine(wall, getWallBodyCenterOffset(wall)) +} + +export function getWallFaceLine( + wall: WallLine, + face: WallJustification, +): { start: Point2D; end: Point2D } { + return offsetLine(wall, getWallFaceOffsets(wall)[face]) +} + +export function getWallLocalFaceZ(wall: WallFrame, face: WallJustification): number { + // The viewer rotates XZ by -atan2(dy, dx), mapping the left normal to +z. + return getWallFaceOffsets(wall)[face] +} + +/** + * Which physical face a point on the wall mesh lies on, from wall-local + * coordinates (x along the chord, z toward its left) — never from the material + * a face happens to draw with. Curved walls use the arc's own frame, so a point + * near an arc end is judged against the curve, not the chord. Returns null for + * caps and tops (the surface normal is not across the wall) and for points too + * close to the body centre to call. + */ +export function getWallFaceAtLocalPoint( + wall: WallLine & Pick, + localPosition: readonly [number, number, number], + localNormal?: readonly [number, number, number], +): WallJustification | null { + const dx = wall.end[0] - wall.start[0] + const dz = wall.end[1] - wall.start[1] + const length = Math.hypot(dx, dz) + if (length < 1e-9) return null + const tangent = { x: dx / length, y: dz / length } + const left = { x: -tangent.y, y: tangent.x } + const toWorld = (x: number, z: number) => ({ + x: tangent.x * x + left.x * z, + y: tangent.y * x + left.y * z, + }) + const [localX, , localZ] = localPosition + let across = localZ + let faceNormal = left + const arc = getWallArcData(wall) + if (arc) { + const offset = toWorld(localX, localZ) + const px = wall.start[0] + offset.x - arc.center.x + const py = wall.start[1] + offset.y - arc.center.y + const radius = Math.hypot(px, py) + if (radius < 1e-9) return null + // Left of a counter-clockwise arc points at its centre. + const inward = arc.direction > 0 + across = inward ? arc.radius - radius : radius - arc.radius + faceNormal = inward ? { x: -px / radius, y: -py / radius } : { x: px / radius, y: py / radius } + } + if (localNormal) { + const normal = toWorld(localNormal[0], localNormal[2]) + if (Math.abs(normal.x * faceNormal.x + normal.y * faceNormal.y) < 0.65) return null + } + const fromCentre = across - getWallBodyCenterOffset(wall) + const thickness = wall.thickness ?? 0.1 + if (Math.abs(fromCentre) < Math.max(thickness * 0.2, 0.01)) return null + return fromCentre >= 0 ? 'a' : 'b' +} + +export function faceOnLine(wall: Pick): 'a' | 'b' | 'center' { + return wall.justification === 'a' ? 'b' : wall.justification === 'b' ? 'a' : 'center' +} + +export function justificationForFaceOnLine( + face: 'a' | 'b' | 'center', +): WallJustification | undefined { + return face === 'a' ? 'b' : face === 'b' ? 'a' : undefined +} + +export function buildWallJustificationPatch( + justification: WallJustification | undefined, +): Pick { + return { justification } +} + +const swapFace = (face: 'a' | 'b'): 'a' | 'b' => (face === 'a' ? 'b' : 'a') + +function swapFaceSlotKey(key: string): string { + if (key === 'a' || key === 'b') return swapFace(key) + const match = /^([ab])([A-Z].*)$/.exec(key) + return match ? `${swapFace(match[1] as 'a' | 'b')}${match[2]}` : key +} + +// Legacy semantic sides draw on their canonical face (interior → a), so they turn too. +const TRIM_FACE: Record = { a: 'a', interior: 'a', b: 'b', exterior: 'b' } + +function reverseTrim(trim: T): T { + const face = trim?.sides ? TRIM_FACE[trim.sides] : undefined + if (!(trim && face)) return trim + return { ...trim, sides: swapFace(face) } +} + +/** + * Turns a wall around. Face `a` becomes `b`, so everything keyed by face swaps + * with it, and region stations are re-measured from the new start. Zone + * `wallOverrides` live on zones; callers reversing a wall swap those too. + */ +export function reverseWallDirection(wall: WallNode): Partial { + const length = Math.hypot(wall.end[0] - wall.start[0], wall.end[1] - wall.start[1]) + const legacy = wall.legacyFaceMaterials + return { + start: wall.end, + end: wall.start, + frontSide: wall.backSide, + backSide: wall.frontSide, + ...(wall.justification === undefined + ? {} + : { justification: wall.justification === 'a' ? 'b' : 'a' }), + ...(wall.curveOffset === undefined ? {} : { curveOffset: -wall.curveOffset }), + ...(wall.slots === undefined + ? {} + : { + slots: Object.fromEntries( + Object.entries(wall.slots).map(([key, value]) => [swapFaceSlotKey(key), value]), + ), + }), + ...(legacy === undefined + ? {} + : { + legacyFaceMaterials: { + ...(legacy.b === undefined ? {} : { a: legacy.b }), + ...(legacy.a === undefined ? {} : { b: legacy.a }), + }, + }), + ...(wall.faceRegions === undefined + ? {} + : { + faceRegions: wall.faceRegions.map(({ u0, u1, ...region }) => ({ + ...region, + face: swapFace(region.face), + ...(u1 === undefined ? {} : { u0: length - u1 }), + ...(u0 === undefined ? {} : { u1: length - u0 }), + })), + }), + ...(wall.skirting === undefined ? {} : { skirting: reverseTrim(wall.skirting) }), + ...(wall.crown === undefined ? {} : { crown: reverseTrim(wall.crown) }), + ...(wall.chairRail === undefined ? {} : { chairRail: reverseTrim(wall.chairRail) }), + } +} + +export function planWallJustification( + nodes: SceneNodes, + wallId: string, + justification: WallJustification | undefined, +): Array<{ id: WallNode['id']; data: Pick }> { + const wall = nodes[wallId] + if (wall?.type !== 'wall') throw Error('Select a wall.') + if (wall.justification === justification) return [] + return [{ id: wall.id, data: buildWallJustificationPatch(justification) }] +} diff --git a/packages/core/src/systems/wall/wall-justification.test.ts b/packages/core/src/systems/wall/wall-justification.test.ts new file mode 100644 index 0000000000..89c34db5be --- /dev/null +++ b/packages/core/src/systems/wall/wall-justification.test.ts @@ -0,0 +1,397 @@ +import { describe, expect, test } from 'bun:test' +import { extractRooms } from '../../lib/room-graph' +import { getRenderableSlabPolygon } from '../../lib/slab-polygon' +import { detectSpacesForLevel, initSpaceDetectionSync } from '../../lib/space-detection' +import { reconcileSceneStructure } from '../../lib/structure-reconcile' +import { + BuildingNode, + generateId, + LevelNode, + SeparatorNode, + SlabNode, + WallNode, +} from '../../schema' +import { wallSegmentAnchors } from '../../services/alignment-anchors' +import useScene, { clearSceneHistory } from '../../store/use-scene' +import { computeWallSlabSupport } from '../slab/slab-support' +import { getWallCurveFrameAt, getWallSurfacePolygon } from './wall-curve' +import { getWallPlanFootprint } from './wall-footprint' +import { + buildWallJustificationPatch, + getWallBodyLine, + planWallJustification, + reverseWallDirection, +} from './wall-frame' +import { planWallMerge } from './wall-merge' +import { calculateLevelMiters } from './wall-mitering' +import { planWallDivision, planWallDivisions, planWallRectangle } from './wall-operations' + +const wall = (start: [number, number], end: [number, number], justification?: 'a' | 'b') => + WallNode.parse({ start, end, thickness: 0.2, justification }) + +function expectSimple(points: { x: number; y: number }[]) { + const cross = (a: (typeof points)[number], b: typeof a, c: typeof a) => + (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) + for (let i = 0; i < points.length; i++) + for (let j = i + 2; j < points.length; j++) { + if (i === 0 && j === points.length - 1) continue + const a = points[i]!, + b = points[(i + 1) % points.length]! + const c = points[j]!, + d = points[(j + 1) % points.length]! + expect( + cross(a, b, c) * cross(a, b, d) < -1e-12 && cross(c, d, a) * cross(c, d, b) < -1e-12, + ).toBe(false) + } +} + +describe('justified junction footprints', () => { + for (const first of [undefined, 'a'] as const) + test(`corner ${first ?? 'center'} / a closes on intersecting body lines`, () => { + const walls = [wall([0, 0], [4, 0], first), wall([4, 0], [4, 3], 'a')] + const miters = calculateLevelMiters(walls) + const closing = { x: 3.9, y: first ? 0.1 : 0 } + for (const w of walls) { + const footprint = getWallPlanFootprint(w, miters) + expect(footprint.some((p) => Math.hypot(p.x - closing.x, p.y - closing.y) < 1e-10)).toBe( + true, + ) + expectSimple(footprint) + for (const point of footprint) { + expect(point.x).toBeGreaterThanOrEqual(-0.2) + expect(point.x).toBeLessThanOrEqual(4.2) + expect(point.y).toBeGreaterThanOrEqual(-0.2) + expect(point.y).toBeLessThanOrEqual(3.2) + } + } + }) + + test('near-parallel justified corners never exceed the miter limit', () => { + const walls = [wall([0, 0], [4, 0], 'a'), wall([0, 0], [4, 0.000_01], 'a')] + for (const w of walls) + for (const p of getWallPlanFootprint(w, calculateLevelMiters(walls))) { + expect(Math.min(Math.hypot(p.x, p.y), Math.hypot(p.x - 4, p.y))).toBeLessThanOrEqual(2) + } + }) + + for (const hostJustification of [undefined, 'a', 'b'] as const) { + for (const side of [-1, 1]) + for (const slant of [0, 0.8]) + test(`T stem meets near face: host ${hostJustification ?? 'center'}, side ${side}, slant ${slant}`, () => { + const host = wall([0, 0], [6, 0], hostJustification) + const stem = wall([3 + slant, side * 3], [3, 0], 'a') + const miters = calculateLevelMiters([host, stem]) + const footprint = getWallPlanFootprint(stem, miters) + const face = + side > 0 + ? hostJustification === 'a' + ? 0.2 + : hostJustification === 'b' + ? 0 + : 0.1 + : hostJustification === 'b' + ? -0.2 + : hostJustification === 'a' + ? 0 + : -0.1 + for (const p of footprint.slice(1, 4)) expect(p.y).toBeCloseTo(face, 10) + expectSimple(footprint) + expect(getWallPlanFootprint(host, miters)).toHaveLength(4) + }) + } + + test('curved a body lies entirely to the left of the reference arc', () => { + const w = { ...wall([0, 0], [4, 0], 'a'), curveOffset: 0.7 } + const points = getWallSurfacePolygon(w, 12) + for (let i = 0; i <= 12; i++) { + const frame = getWallCurveFrameAt(w, i / 12) + expect(points[i]!.x).toBeCloseTo(frame.point.x, 12) + expect(points[i]!.y).toBeCloseTo(frame.point.y, 12) + const left = points[25 - i]! + expect( + (left.x - frame.point.x) * frame.normal.x + (left.y - frame.point.y) * frame.normal.y, + ).toBeCloseTo(0.2, 12) + } + }) +}) + +test('outside justified room retains reference topology, adopts outer slab faces and has 100% support', () => { + const points: [number, number][] = [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ] + const walls = points.map((p, i) => wall(p, points[(i + 1) % 4]!, 'b')) + const detected = detectSpacesForLevel('level_test', walls) + expect(detected.spaces).toHaveLength(1) + expect( + new Set( + detected.spaces[0]!.polygon.map((p) => p.map((value) => Number(value.toFixed(6))).join(',')), + ), + ).toEqual(new Set(['-0.1,-0.1', '4.1,-0.1', '4.1,3.1', '-0.1,3.1'])) + const slab = SlabNode.parse({ + polygon: detected.spaces[0]!.polygon, + elevation: 0.3, + thickness: 0.3, + }) + const rendered = getRenderableSlabPolygon(slab, { walls, siblingSlabs: [] }) + expect(Math.min(...rendered.map((p) => p[0]))).toBeCloseTo(-0.2) + expect(Math.max(...rendered.map((p) => p[0]))).toBeCloseTo(4.2) + expect(Math.min(...rendered.map((p) => p[1]))).toBeCloseTo(-0.2) + expect(Math.max(...rendered.map((p) => p[1]))).toBeCloseTo(3.2) + for (const w of walls) { + expect(detected.wallUpdates.find((update) => update.wallId === w.id)).toMatchObject({ + frontSide: 'interior', + backSide: 'exterior', + }) + const support = computeWallSlabSupport(w, [slab], walls) + expect(support.electedSlabId).toBe(slab.id) + expect(support.baseSegments).toHaveLength(1) + expect(support.baseSegments[0]!.start).toBeCloseTo(0, 12) + expect(support.baseSegments[0]!.end).toBeCloseTo(1, 12) + expect(support.baseSegments[0]!.elevation).toBe(0.3) + } +}) + +for (const curveOffset of [0, 0.7, -0.7]) + test(`switching justification moves the body but keeps reference endpoints and arc: curve ${curveOffset}`, () => { + const original = { ...wall([1, 2], [5, 4]), curveOffset } + const originalPolygon = getWallSurfacePolygon(original) + let current = original + for (const justification of ['a', undefined, 'b', undefined] as const) { + const patch = buildWallJustificationPatch(justification) + expect(Object.keys(patch)).toEqual(['justification']) + current = { ...current, ...patch } + expect(current.start).toBe(original.start) + expect(current.end).toBe(original.end) + expect(current.curveOffset).toBe(original.curveOffset) + const nextPolygon = getWallSurfacePolygon(current) + if (justification) expect(nextPolygon).not.toEqual(originalPolygon) + else expect(nextPolygon).toEqual(originalPolygon) + } + }) + +for (const multiple of [false, true]) + test(`${multiple ? 'multiple' : 'single'} split preserves justified orientation`, () => { + const level = LevelNode.parse({}) + const w = { ...wall([0, 0], [6, 0], 'a'), parentId: level.id } + const nodes = { [level.id]: level, [w.id]: w } + const plan = multiple + ? planWallDivisions(nodes, w.id, [2, 4]) + : planWallDivision(nodes, w.id, 3) + const pieces = [ + ...plan.changes.create.map((op) => op.node), + ...plan.changes.update.map((op) => ({ ...nodes[op.id], ...op.data })), + ] + for (const piece of pieces) + if (piece.type === 'wall') { + expect(piece.justification).toBe('a') + expect(getWallBodyLine(piece as WallNode).start.y).toBeCloseTo(0.1) + } + }) + +test('backwards merge preserves the same world body side', () => { + const first = wall([0, 0], [2, 0], 'a') + const second = wall([4, 0], [2, 0], 'b') + const plan = planWallMerge({ [first.id]: first, [second.id]: second }, [first.id, second.id]) + const merged = plan.changes.update.find((op) => op.id === plan.wallId)!.data as WallNode + expect(getWallBodyLine(merged).start.y).toBeCloseTo(0.1) + expect(getWallBodyLine(merged).end.y).toBeCloseTo(0.1) +}) + +for (const end of [ + [4, 3], + [-4, -3], +] as [number, number][]) + test(`rectangle keeps counterclockwise reference orientation: ${end}`, () => { + const level = LevelNode.parse({}) + const plan = planWallRectangle( + { [level.id]: level }, + { levelId: level.id, start: [0, 0], end, wallDefaults: { justification: 'b' } }, + ) + expect(plan.walls).toHaveLength(4) + for (const w of plan.walls) { + expect(w.justification).toBe('b') + const reversed = { ...w, ...reverseWallDirection(w) } + expect(getWallBodyLine(reversed).start).toEqual(getWallBodyLine(w).end) + } + }) + +test('alignment retains reference endpoints and adds actual face anchors', () => { + const anchors = wallSegmentAnchors('wall_test', [0, 0], [4, 0], 0.2, 'a') + expect(anchors.slice(0, 3).map((p) => [p.x, p.z])).toEqual([ + [0, 0], + [4, 0], + [2, 0], + ]) + expect(anchors.slice(3).map((p) => p.z)).toEqual([0.2, 0, 0.2, 0]) +}) + +for (const stemTop of [undefined, 1.5, 3]) + test(`reference switch preserves topology and all endpoints, T-stem ${stemTop ?? 'none'}`, () => { + const walls = [ + wall([0, 0], [4, 0]), + wall([4, 0], [4, 3]), + wall([4, 3], [0, 3]), + wall([0, 3], [0, 0]), + ] + if (stemTop) walls.push(wall([2, stemTop], [2, 0])) + const before = extractRooms(walls) + .map(({ polygon: _polygon, ...reference }) => reference) + .sort((a, b) => a.id.localeCompare(b.id)) + expect(before).toHaveLength(stemTop === 3 ? 2 : 1) + let nodes = Object.fromEntries(walls.map((wall) => [wall.id, wall])) + for (const next of ['a', undefined, 'b'] as const) { + const updates = planWallJustification(nodes, walls[0]!.id, next) + expect(updates).toEqual([{ id: walls[0]!.id, data: { justification: next } }]) + nodes = { ...nodes, [walls[0]!.id]: { ...nodes[walls[0]!.id]!, ...updates[0]!.data } } + expect(Object.values(nodes).map(({ start, end }) => ({ start, end }))).toEqual( + walls.map(({ start, end }) => ({ start, end })), + ) + expect( + extractRooms(Object.values(nodes)) + .map(({ polygon: _polygon, ...reference }) => reference) + .sort((a, b) => a.id.localeCompare(b.id)), + ).toEqual(before) + expect(planWallJustification(nodes, walls[0]!.id, next)).toEqual([]) + } + }) + +test('mixed junction changes its centred member; unrelated all-centred junction remains legacy', () => { + const walls = [wall([0, 0], [4, 0]), wall([4, 0], [4, 3]), wall([4, 3], [0, 3])] + const before = calculateLevelMiters(walls) + const mixed = [{ ...walls[0]!, justification: 'a' as const }, ...walls.slice(1)] + const after = calculateLevelMiters(mixed) + expect(getWallPlanFootprint(walls[1]!, after)).not.toEqual( + getWallPlanFootprint(walls[1]!, before), + ) + expect(after.junctionData.get('4000,3000')).toEqual(before.junctionData.get('4000,3000')) +}) + +test('reference switch leaves oblique neighbours and T-stems byte-identical', () => { + const walls = [ + wall([0, 0], [4, 0]), + wall([4, 0], [5, 3]), + wall([5, 3], [1, 3]), + wall([1, 3], [0, 0]), + wall([2, 0], [3.5, 3]), + ] + const nodes = Object.fromEntries(walls.map((wall) => [wall.id, wall])) + const serialized = JSON.stringify(nodes) + const updates = planWallJustification(nodes, walls[0]!.id, 'a') + expect(updates).toEqual([{ id: walls[0]!.id, data: { justification: 'a' } }]) + const next = walls.map((wall) => ({ + ...wall, + ...updates.find((patch) => patch.id === wall.id)?.data, + })) + expect(next.slice(1)).toEqual(walls.slice(1)) + expect( + extractRooms(next) + .map(({ polygon: _polygon, ...reference }) => reference) + .sort((a, b) => a.id.localeCompare(b.id)), + ).toEqual( + extractRooms(walls) + .map(({ polygon: _polygon, ...reference }) => reference) + .sort((a, b) => a.id.localeCompare(b.id)), + ) + expect(JSON.stringify(nodes)).toBe(serialized) +}) + +for (const division of ['rectangle', 'separator', 'T-stem'] as const) + test(`a/center/b keeps reference endpoints and room IDs with undo: ${division}`, () => { + const raf = Object.getOwnPropertyDescriptor(globalThis, 'requestAnimationFrame') + const cancel = Object.getOwnPropertyDescriptor(globalThis, 'cancelAnimationFrame') + Object.defineProperty(globalThis, 'requestAnimationFrame', { + configurable: true, + writable: true, + value: () => 0, + }) + Object.defineProperty(globalThis, 'cancelAnimationFrame', { + configurable: true, + writable: true, + value: () => {}, + }) + const previous = useScene.getState() + const building = BuildingNode.parse({}) + const level = LevelNode.parse({ parentId: building.id }) + const walls = [ + wall([0, 0], [4, 0]), + wall([4, 0], [4, 3]), + wall([4, 3], [0, 3]), + wall([0, 3], [0, 0]), + ].map((w, i) => ({ + ...w, + parentId: level.id, + frontSide: 'interior' as const, + backSide: i === 4 ? ('interior' as const) : ('exterior' as const), + })) + const divider = + division === 'rectangle' + ? [] + : [ + division === 'separator' + ? SeparatorNode.parse({ parentId: level.id, start: [2, 3], end: [2, 0] }) + : { ...wall([2, 3], [2, 0]), parentId: level.id }, + ] + level.children = [...walls, ...divider].map((w) => w.id) + building.children = [level.id] + const initial = Object.fromEntries( + [building, level, ...walls, ...divider].map((n) => [n.id, n]), + ) + const nodes = reconcileSceneStructure({ nodes: initial, mintId: generateId }).nodes + useScene.setState({ nodes, rootNodeIds: [building.id], dirtyNodes: new Set(), readOnly: false }) + clearSceneHistory() + const editor = { + spaces: {} as Record, + setSpaces(next: typeof editor.spaces) { + editor.spaces = next + }, + } + const strategies: string[] = [] + const stop = initSpaceDetectionSync( + useScene, + { getState: () => editor }, + { onTopologyReconcile: (event) => strategies.push(event.strategy) }, + ) + try { + const roomIds = () => + Object.values(useScene.getState().nodes) + .filter((node) => node.type === 'zone') + .map((zone) => zone.id) + .sort() + const beforeIds = roomIds() + expect(beforeIds).toHaveLength(division === 'rectangle' ? 1 : 2) + const references = (graph: typeof nodes) => + JSON.stringify( + Object.values(graph) + .filter((node) => node.type === 'wall' || node.type === 'separator') + .map(({ id, start, end }) => ({ id, start, end })), + ) + for (const next of ['a', undefined, 'b'] as const) { + const before = useScene.getState().nodes + clearSceneHistory() + strategies.length = 0 + useScene.getState().updateNodes(planWallJustification(before, walls[0]!.id, next)) + expect(strategies).toEqual(['indexed']) + expect(roomIds()).toEqual(beforeIds) + expect(references(useScene.getState().nodes)).toBe(references(nodes)) + if (next === undefined) + expect(useScene.getState().nodes[walls[0]!.id]).not.toHaveProperty('justification') + expect(useScene.temporal.getState().pastStates).toHaveLength(1) + const after = useScene.getState().nodes + useScene.temporal.getState().undo() + expect(useScene.getState().nodes).toEqual(before) + useScene.temporal.getState().redo() + expect(useScene.getState().nodes).toEqual(after) + } + } finally { + stop() + useScene.setState(previous, true) + clearSceneHistory() + if (raf) Object.defineProperty(globalThis, 'requestAnimationFrame', raf) + else Reflect.deleteProperty(globalThis, 'requestAnimationFrame') + if (cancel) Object.defineProperty(globalThis, 'cancelAnimationFrame', cancel) + else Reflect.deleteProperty(globalThis, 'cancelAnimationFrame') + } + }) diff --git a/packages/core/src/systems/wall/wall-layer-bands.ts b/packages/core/src/systems/wall/wall-layer-bands.ts index 358518e845..78495fefea 100644 --- a/packages/core/src/systems/wall/wall-layer-bands.ts +++ b/packages/core/src/systems/wall/wall-layer-bands.ts @@ -37,7 +37,7 @@ export type WallLayerBands = ResolvedAssembly & { bands: WallLayerBand[] } * wall whose stored thickness disagrees gets the `assembly.thickness-mismatch` * diagnostic and no bands: it keeps its plain body until a writer re-derives * the thickness. Layers stack from the front face (+n), or from the exterior - * face with `face: 'exterior'` (`resolveWallExteriorSide`, front as fallback). + * face with `face: 'exterior'` (`resolveWallExteriorSide`, back as fallback). * * Straight walls intersect the footprint with half-plane strips through the * core polygon booleans, which handles the junction vertex a mitred end cap @@ -58,7 +58,7 @@ export function getWallLayerBands( } const half = thickness / 2 // +1 when the first listed layer is on the front face, −1 when it is on the back. - const sign = assembly.face === 'exterior' ? (resolveWallExteriorSide(wall) ?? 1) : 1 + const sign = assembly.face === 'exterior' ? (resolveWallExteriorSide(wall) ?? -1) : 1 const footprint = getWallPlanFootprint(wall, miterData) const curved = isCurvedWall(wall) diff --git a/packages/core/src/systems/wall/wall-merge-finish.test.ts b/packages/core/src/systems/wall/wall-merge-finish.test.ts new file mode 100644 index 0000000000..9a464bbc5b --- /dev/null +++ b/packages/core/src/systems/wall/wall-merge-finish.test.ts @@ -0,0 +1,196 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test' +import { type AnyNode, type AnyNodeId, LevelNode, WallNode, ZoneNode } from '../../schema' +import useScene from '../../store/use-scene' +import { mergeWallFaceRegions, planWallMerge, wallStyleMismatch } from './wall-merge' +import type { WallTopologyChanges } from './wall-topology' + +const level = LevelNode.parse({ id: 'level_mf', children: [] }) +const map = (nodes: AnyNode[]) => + Object.fromEntries([level, ...nodes].map((n) => [n.id, n])) as Record +const apply = (nodes: Record, changes: WallTopologyChanges) => { + const next = { ...nodes } + for (const { id, data } of changes.update) next[id] = { ...next[id]!, ...data } as AnyNode + for (const id of changes.delete) delete next[id] + return next +} +const wall = (start: [number, number], end: [number, number], extra: Partial = {}) => + WallNode.parse({ parentId: level.id, start, end, ...extra }) +const room = (walls: WallNode[], extra: Partial = {}) => + ZoneNode.parse({ + name: 'Room', + parentId: level.id, + polygon: [ + [0, 0], + [4, 0], + [4, 3], + [0, 3], + ], + boundaryWallIds: walls.map((w) => w.id), + ...extra, + }) + +describe('merge compares what each face shows, in the merged direction', () => { + test('face slots are compared after reading the other wall backwards', () => { + const a = wall([0, 0], [2, 0], { slots: { a: 'library:red' } }) + // Drawn the other way: its face b is a's face a. + const sameLook = wall([4, 0], [2, 0], { slots: { b: 'library:red' } }) + const otherLook = wall([4, 0], [2, 0], { slots: { a: 'library:red' } }) + expect(wallStyleMismatch(a, sameLook, { sides: false })).toBeNull() + expect(wallStyleMismatch(a, otherLook, { sides: false })).toBe('side A finish') + expect(() => planWallMerge(map([a, otherLook]), [a.id, otherLook.id])).toThrow( + 'These walls have a different side A finish.', + ) + }) + + test('trims must draw the same on the same faces', () => { + const a = wall([0, 0], [2, 0], { skirting: { enabled: true, sides: 'a' } as never }) + const mirrored = wall([4, 0], [2, 0], { skirting: { enabled: true, sides: 'b' } as never }) + const opposite = wall([4, 0], [2, 0], { skirting: { enabled: true, sides: 'a' } as never }) + const recoloured = wall([2, 0], [4, 0], { + skirting: { enabled: true, sides: 'a' } as never, + slots: { aSkirting: 'library:oak' }, + }) + expect(wallStyleMismatch(a, mirrored, { sides: false })).toBeNull() + expect(wallStyleMismatch(a, opposite, { sides: false })).toBe('trim') + expect(wallStyleMismatch(a, recoloured, { sides: false })).toBe('trim') + }) +}) + +describe('merge carries room overrides onto the kept wall', () => { + test('an absorbed wall read backwards hands its override over on the swapped face', () => { + const a = wall([0, 0], [2, 0]) + const b = wall([4, 0], [2, 0]) + const zone = room([a, b], { + wallOverrides: [ + { wallId: a.id, face: 'a', finish: 'library:accent' }, + { wallId: b.id, face: 'b', finish: 'library:accent' }, + ], + }) + const plan = planWallMerge(map([a, b, zone]), [a.id, b.id]) + const merged = apply(map([a, b, zone]), plan.changes) + // The kept wall keeps its own direction; the room sits on its a side if it is `a`. + const face = plan.wallId === a.id ? 'a' : 'b' + expect((merged[zone.id] as ZoneNode).wallOverrides).toEqual([ + { wallId: plan.wallId, face, finish: 'library:accent' }, + ]) + expect((merged[zone.id] as ZoneNode).boundaryWallIds).toEqual([plan.wallId]) + }) + + test('refuses when the walls disagree on a room face they both border', () => { + const a = wall([0, 0], [2, 0]) + const b = wall([2, 0], [4, 0]) + const differing = room([a, b], { + wallOverrides: [ + { wallId: a.id, face: 'a', finish: 'library:one' }, + { wallId: b.id, face: 'a', finish: 'library:two' }, + ], + }) + expect(() => planWallMerge(map([a, b, differing]), [a.id, b.id])).toThrow('room finish') + const halfPainted = room([a, b], { + wallOverrides: [{ wallId: a.id, face: 'a', finish: 'library:one' }], + }) + expect(() => planWallMerge(map([a, b, halfPainted]), [a.id, b.id])).toThrow('room finish') + }) +}) + +describe('merge rebases paint regions', () => { + test('stations move to the merged start, faces follow the direction, open ends stay open', () => { + const a = wall([0, 0], [2, 0], { + faceRegions: [{ id: 'dado', face: 'a', u0: 0.5, v1: 0.9, finish: 'library:wood' }], + }) + const b = wall([4, 0], [2, 0], { + faceRegions: [{ id: 'dado', face: 'b', u1: 1, v1: 0.9, finish: 'library:wood' }], + }) + expect(mergeWallFaceRegions([a, b], [0, 0], [4, 0])).toEqual([ + { id: 'dado', face: 'a', u0: 0.5, u1: 2, v1: 0.9, finish: 'library:wood' }, + { id: `dado-${b.id}`, face: 'a', u0: 3, v1: 0.9, finish: 'library:wood' }, + ]) + }) + + test('a region continuing across the joint coalesces into one', () => { + const a = wall([0, 0], [2, 0], { + faceRegions: [{ id: 'band-a-lower', face: 'a', v1: 0.9, finish: 'library:wood' }], + }) + const b = wall([2, 0], [4, 0], { + faceRegions: [{ id: 'band-a-lower', face: 'a', v1: 0.9, finish: 'library:wood' }], + }) + const plan = planWallMerge(map([a, b]), [a.id, b.id]) + const kept = apply(map([a, b]), plan.changes)[plan.wallId] as WallNode + expect(kept.faceRegions).toEqual([ + { id: 'band-a-lower', face: 'a', v1: 0.9, finish: 'library:wood' }, + ]) + }) + + test('refuses a merge that would leave more than eight regions on a face', () => { + const regions = (count: number, offset: number) => + Array.from({ length: count }, (_, i) => ({ + id: `r${offset + i}`, + face: 'a' as const, + u0: 0.1 + i * 0.3, + u1: 0.2 + i * 0.3, + finish: `library:c${offset + i}`, + })) + const a = wall([0, 0], [2, 0], { faceRegions: regions(5, 0) }) + const b = wall([2, 0], [4, 0], { faceRegions: regions(5, 5) }) + expect(mergeWallFaceRegions([a, b], [0, 0], [4, 0])).toBeNull() + expect(() => planWallMerge(map([a, b]), [a.id, b.id])).toThrow('paint regions') + }) +}) + +describe('delete heal', () => { + let saved: ReturnType + const raf = globalThis.requestAnimationFrame + const cancel = globalThis.cancelAnimationFrame + beforeEach(() => { + saved = useScene.getState() + globalThis.requestAnimationFrame = () => 0 + globalThis.cancelAnimationFrame = () => {} + }) + afterEach(() => { + useScene.setState(saved) + globalThis.requestAnimationFrame = raf + globalThis.cancelAnimationFrame = cancel + }) + + test('rejoins painted walls with rebased regions and remapped overrides', () => { + const a = wall([0, 0], [2, 0], { + faceRegions: [{ id: 'dado', face: 'a', u0: 1, v1: 0.9, finish: 'library:wood' }], + }) + const b = wall([4, 0], [2, 0]) + const stub = wall([2, 0], [2, -1]) + const zone = room([a, b], { + wallOverrides: [ + { wallId: a.id, face: 'a', finish: 'library:accent' }, + { wallId: b.id, face: 'b', finish: 'library:accent' }, + ], + }) + const nodes = map([a, b, stub, zone]) + ;(nodes[level.id] as LevelNode).children = [a.id, b.id, stub.id, zone.id] as never + useScene.setState({ nodes, rootNodeIds: [level.id], dirtyNodes: new Set() } as never) + useScene.getState().deleteNode(stub.id as AnyNodeId) + const state = useScene.getState().nodes + const survivors = Object.values(state).filter((n): n is WallNode => n.type === 'wall') + expect(survivors).toHaveLength(1) + const kept = survivors[0]! + expect([kept.start, kept.end]).toEqual( + kept.id === a.id + ? [ + [0, 0], + [4, 0], + ] + : [ + [4, 0], + [0, 0], + ], + ) + const keptFace = kept.id === a.id ? 'a' : 'b' + expect(kept.faceRegions).toEqual([ + kept.id === a.id + ? { id: 'dado', face: 'a', u0: 1, u1: 2, v1: 0.9, finish: 'library:wood' } + : { id: 'dado', face: 'b', u0: 2, u1: 3, v1: 0.9, finish: 'library:wood' }, + ]) + expect((state[zone.id as AnyNodeId] as ZoneNode).wallOverrides).toEqual([ + { wallId: kept.id, face: keptFace, finish: 'library:accent' }, + ]) + }) +}) diff --git a/packages/core/src/systems/wall/wall-merge.ts b/packages/core/src/systems/wall/wall-merge.ts index f6f85d0e9b..f1bfc9991b 100644 --- a/packages/core/src/systems/wall/wall-merge.ts +++ b/packages/core/src/systems/wall/wall-merge.ts @@ -2,10 +2,17 @@ import { getWallEffectiveHeightForNodes } from '../../hooks/spatial-grid/spatial import { type AnyNode, type AnyNodeId, - getEffectiveWallSurfaceMaterial, - getWallSurfaceMaterialSignature, + getWallTrimFaces, + getWallTrimSlotId, + WALL_FACE_REGION_LIMIT, + WALL_TRIM_DEFAULTS, + type WallFace, + type WallFaceRegion, type WallNode, + type ZoneNode, } from '../../schema' +import { getWallZoneSpans, resolveWallFaceChain } from './wall-finish' +import { reverseWallDirection } from './wall-frame' import type { WallTopologyChanges } from './wall-topology' // Joining two walls that continue each other at a shared end: the delete heal @@ -51,6 +58,12 @@ export function wallStyleMismatch( if ((a.parentId ?? null) !== (b.parentId ?? null)) return 'floor' if (Math.abs((a.curveOffset ?? 0) - (b.curveOffset ?? 0)) > 1e-6) return 'curve' if (Math.abs((a.thickness ?? 0.2) - (b.thickness ?? 0.2)) > 1e-6) return 'thickness' + const opposite = + (a.end[0] - a.start[0]) * (b.end[0] - b.start[0]) + + (a.end[1] - a.start[1]) * (b.end[1] - b.start[1]) < + 0 + const alignedB = opposite ? { ...b, ...reverseWallDirection(b) } : b + if (a.justification !== alignedB.justification) return 'justification' const { heightOf } = options if ( heightOf @@ -59,19 +72,207 @@ export function wallStyleMismatch( Math.abs((a.height ?? 0) - (b.height ?? 0)) > 1e-6 ) return 'height' - for (const side of ['interior', 'exterior'] as const) { + // Faces are compared as the merged wall will carry them: b read in a's direction. + for (const face of ['a', 'b'] as const) { if ( - getWallSurfaceMaterialSignature(getEffectiveWallSurfaceMaterial(a, side)) !== - getWallSurfaceMaterialSignature(getEffectiveWallSurfaceMaterial(b, side)) + JSON.stringify(resolveWallFaceChain(a, face)) !== + JSON.stringify(resolveWallFaceChain(alignedB, face)) ) - return `${side} finish` + return `side ${face.toUpperCase()} finish` } + if (wallTrimSignature(a) !== wallTrimSignature(alignedB)) return 'trim' if (options.sides && (a.frontSide !== b.frontSide || a.backSide !== b.backSide)) return 'room sides' if (a.visible !== b.visible) return 'visibility' return null } +/** Every trim as it draws: which faces, which profile and size, which finish per face. */ +function wallTrimSignature(wall: WallNode): string { + return JSON.stringify( + (['skirting', 'crown', 'chairRail'] as const).map((kind) => { + const trim = { ...WALL_TRIM_DEFAULTS[kind], ...(wall[kind] ?? {}) } + if (!trim.enabled) return null + const faces = getWallTrimFaces(trim.sides) + return { + faces, + profile: trim.profile, + height: trim.height, + proud: trim.proud, + offsetY: trim.offsetY ?? null, + finishes: faces.map((face) => wall.slots?.[getWallTrimSlotId(face, kind)] ?? null), + } + }), + ) +} + +function readsBackwards( + wall: Pick, + start: [number, number], + end: [number, number], +) { + return ( + (wall.end[0] - wall.start[0]) * (end[0] - start[0]) + + (wall.end[1] - wall.start[1]) * (end[1] - start[1]) < + 0 + ) +} + +const REGION_EPSILON = 1e-6 + +function sameRegionBody(left: WallFaceRegion, right: WallFaceRegion) { + return ( + left.face === right.face && + left.finish === right.finish && + left.v0 === right.v0 && + left.v1 === right.v1 + ) +} + +/** + * Both walls' paint regions in the merged wall's coordinates: faces read in its + * direction, stations measured from its start, each region clipped to the stretch + * its own wall covered (an open bound stays open only at a merged-wall end), and + * matching regions that meet at the joint joined into one. Null when a face would + * exceed the region limit. + */ +export function mergeWallFaceRegions( + walls: readonly WallNode[], + mergedStart: [number, number], + mergedEnd: [number, number], +): WallFaceRegion[] | null { + const mergedLength = Math.hypot(mergedEnd[0] - mergedStart[0], mergedEnd[1] - mergedStart[1]) + if (mergedLength < 1e-9) return [] + const tx = (mergedEnd[0] - mergedStart[0]) / mergedLength + const tz = (mergedEnd[1] - mergedStart[1]) / mergedLength + const station = (point: [number, number]) => + (point[0] - mergedStart[0]) * tx + (point[1] - mergedStart[1]) * tz + const seenIds = new Set() + const out: WallFaceRegion[] = [] + for (const wall of walls) { + const regions = wall.faceRegions ?? [] + if (regions.length === 0) continue + const length = wallLength(wall) + const backwards = readsBackwards(wall, mergedStart, mergedEnd) + const from = Math.min(station(wall.start), station(wall.end)) + const to = Math.max(station(wall.start), station(wall.end)) + const toMerged = (u: number) => (backwards ? to - u : from + u) + for (const region of regions) { + const low = backwards ? region.u1 : region.u0 + const high = backwards ? region.u0 : region.u1 + const u0 = Math.max(from, low === undefined ? from : toMerged(low)) + const u1 = Math.min(to, high === undefined ? to : toMerged(high)) + if (u1 - u0 <= REGION_EPSILON && length > REGION_EPSILON) continue + let id = region.id + if (seenIds.has(id)) id = `${region.id}-${wall.id}` + seenIds.add(id) + const { u0: _u0, u1: _u1, ...body } = region + out.push({ + ...body, + id, + face: backwards ? (region.face === 'a' ? 'b' : 'a') : region.face, + ...(u0 <= REGION_EPSILON ? {} : { u0 }), + ...(u1 >= mergedLength - REGION_EPSILON ? {} : { u1 }), + }) + } + } + // Coalesce a region that continues another across the joint. + const merged: WallFaceRegion[] = [] + for (const region of out) { + const joined = merged.findIndex( + (other) => + sameRegionBody(other, region) && + ((other.u1 !== undefined && + Math.abs(other.u1 - (region.u0 ?? 0)) <= REGION_EPSILON && + region.u0 !== undefined) || + (region.u1 !== undefined && + Math.abs(region.u1 - (other.u0 ?? 0)) <= REGION_EPSILON && + other.u0 !== undefined)), + ) + if (joined < 0) { + merged.push(region) + continue + } + const other = merged[joined]! + const u0 = + other.u0 === undefined || region.u0 === undefined ? undefined : Math.min(other.u0, region.u0) + const u1 = + other.u1 === undefined || region.u1 === undefined ? undefined : Math.max(other.u1, region.u1) + const { u0: _a, u1: _b, ...body } = other + merged[joined] = { + ...body, + ...(u0 === undefined ? {} : { u0 }), + ...(u1 === undefined ? {} : { u1 }), + } + } + for (const face of ['a', 'b'] as const) { + if (merged.filter((region) => region.face === face).length > WALL_FACE_REGION_LIMIT) return null + } + return merged +} + +/** + * Zone references after `secondary` is absorbed into `primary` (which spans + * `mergedStart → mergedEnd`): boundary ids follow the kept wall, and override + * entries move onto it with their face read in its direction. Null when the two + * walls disagree on a room's override for a face they both border — joining + * would repaint part of that room. + */ +export function planMergedZoneReferences( + nodes: Record, + primary: WallNode, + secondary: WallNode, + mergedStart: [number, number], + mergedEnd: [number, number], +): Array<{ id: AnyNodeId; data: Partial }> | null { + const faceOf = (wall: WallNode, face: WallFace): WallFace => + readsBackwards(wall, mergedStart, mergedEnd) ? (face === 'a' ? 'b' : 'a') : face + const updates: Array<{ id: AnyNodeId; data: Partial }> = [] + for (const node of Object.values(nodes)) { + if (node?.type !== 'zone') continue + const touchesBoundary = node.boundaryWallIds?.includes(secondary.id as never) ?? false + const entries = node.wallOverrides ?? [] + const touchesOverrides = entries.some( + (entry) => entry.wallId === secondary.id || entry.wallId === primary.id, + ) + if (!(touchesBoundary || touchesOverrides)) continue + const data: Partial = {} + if (touchesBoundary) + data.boundaryWallIds = [ + ...new Set(node.boundaryWallIds.map((id) => (id === secondary.id ? primary.id : id))), + ] + if (touchesOverrides) { + const byFace = new Map>() + for (const entry of entries) { + const wall = + entry.wallId === primary.id ? primary : entry.wallId === secondary.id ? secondary : null + if (!wall) continue + const face = faceOf(wall, entry.face) + const faces = byFace.get(face) ?? new Map() + faces.set(wall.id, entry.finish) + byFace.set(face, faces) + } + const merged: NonNullable = entries.filter( + (entry) => entry.wallId !== primary.id && entry.wallId !== secondary.id, + ) + for (const [face, finishes] of byFace) { + const values = [...new Set(finishes.values())] + if (values.length > 1) return null + for (const wall of [primary, secondary]) { + if (finishes.has(wall.id)) continue + // The other wall borders this room on the same face without the override. + const spans = getWallZoneSpans(wall, [node]) + if (spans.some((span) => faceOf(wall, span.face) === face)) return null + } + merged.push({ wallId: primary.id, face, finish: values[0]! }) + } + data.wallOverrides = merged + } + updates.push({ id: node.id as AnyNodeId, data }) + } + return updates +} + export function areWallStylesCompatible(a: WallNode, b: WallNode) { return wallStyleMismatch(a, b, { sides: true }) === null } @@ -115,10 +316,10 @@ export function resolveMergedWallEndpoints( // where they are. Meeting start-to-start or end-to-end, the absorbed wall is // the one read backwards. if (primaryEndpoint === 'start' && secondaryEndpoint === 'start') { - return { start: secondary.end, end: primary.end } + return { start: reverseWallDirection(secondary).start!, end: primary.end } } - return { start: primary.start, end: secondary.start } + return { start: primary.start, end: reverseWallDirection(secondary).end! } } /** @@ -267,6 +468,13 @@ export function planWallMerge( if (mismatch) throw Error(`These walls have a different ${mismatch}.`) const { start, end } = resolveMergedWallEndpoints(merged, next, joint) + const faceRegions = mergeWallFaceRegions([merged, next], start, end) + if (!faceRegions) + throw Error( + `Merging would leave more than ${WALL_FACE_REGION_LIMIT} paint regions on a side.`, + ) + const zoneUpdates = planMergedZoneReferences(virtual, merged, next, start, end) + if (!zoneUpdates) throw Error('These walls have a different room finish.') for (const update of buildMergedWallAttachmentUpdates( merged, next, @@ -277,8 +485,10 @@ export function planWallMerge( )) { virtual[update.id] = { ...virtual[update.id]!, ...update.data } as AnyNode } + const { faceRegions: _regions, ...kept } = merged merged = { - ...merged, + ...kept, + ...(faceRegions.length > 0 ? { faceRegions } : {}), start, end, // Ids without a node are dropped rather than carried onto the kept wall. @@ -291,15 +501,8 @@ export function planWallMerge( } as WallNode virtual[merged.id] = merged delete virtual[next.id] - for (const node of Object.values(virtual)) { - if (node?.type !== 'zone' || !node.boundaryWallIds?.includes(next.id)) continue - virtual[node.id] = { - ...node, - boundaryWallIds: [ - ...new Set(node.boundaryWallIds.map((id) => (id === next.id ? merged.id : id))), - ], - } - } + for (const update of zoneUpdates) + virtual[update.id] = { ...virtual[update.id]!, ...update.data } as AnyNode remaining = remaining.filter((wall) => wall !== next) } diff --git a/packages/core/src/systems/wall/wall-mitering.ts b/packages/core/src/systems/wall/wall-mitering.ts index b1fd5a6bd7..65a6cfbf09 100644 --- a/packages/core/src/systems/wall/wall-mitering.ts +++ b/packages/core/src/systems/wall/wall-mitering.ts @@ -1,5 +1,6 @@ import type { WallNode } from '../../schema' import { getWallCurveFrameAt, isCurvedWall } from './wall-curve' +import { getWallBodyCenterOffset, getWallFaceOffsets } from './wall-frame' // ============================================================================ // TYPES @@ -11,10 +12,10 @@ export interface Point2D { } export interface WallMiterBoundaryPoints { - startLeft: Point2D - startRight: Point2D endLeft: Point2D endRight: Point2D + startLeft: Point2D + startRight: Point2D } interface LineEquation { @@ -24,7 +25,7 @@ interface LineEquation { } // Map of wallId -> { left?: Point2D, right?: Point2D } for each junction -type WallIntersections = Map +type WallIntersections = Map // Map of junctionKey -> WallIntersections type JunctionData = Map @@ -96,8 +97,8 @@ function pointOnWallSegment(point: Point2D, wall: WallNode, tolerance = TOLERANC // ============================================================================ interface Junction { - meetingPoint: Point2D connectedWalls: Array<{ wall: WallNode; endType: 'start' | 'end' | 'passthrough' }> + meetingPoint: Point2D } // --- Uniform grid used to prefilter T-junction candidates -------------------- @@ -286,23 +287,26 @@ function getWallBoundaryFrame(wall: WallNode, endType: 'start' | 'end') { // ============================================================================ interface ProcessedWall { - wallId: string angle: number edgeA: LineEquation // Left edge edgeB: LineEquation // Right edge - isPassthrough: boolean // True if wall passes through junction (T-junction) halfThickness: number // Used to bound the miter joint against runaway spikes + isPassthrough: boolean // True if wall passes through junction (T-junction) + wallId: string } function calculateJunctionIntersections( junction: Junction, - getThickness: (wall: WallNode) => number, + facePadding: number, ): WallIntersections { const { meetingPoint, connectedWalls } = junction const processedWalls: ProcessedWall[] = [] for (const { wall, endType } of connectedWalls) { - const halfT = getThickness(wall) / 2 + const faces = getWallFaceOffsets(wall) + const offsets = + facePadding === 0 ? faces : { a: faces.a + facePadding, b: faces.b - facePadding } + const halfT = Math.max(offsets.a, -offsets.b) if (endType === 'passthrough') { // For passthrough walls (T-junctions), add both directions @@ -315,8 +319,10 @@ function calculateJunctionIntersections( if (L < 1e-9) continue const nUnit = { x: -v.y / L, y: v.x / L } - const pA = { x: meetingPoint.x + nUnit.x * halfT, y: meetingPoint.y + nUnit.y * halfT } - const pB = { x: meetingPoint.x - nUnit.x * halfT, y: meetingPoint.y - nUnit.y * halfT } + const a = v === v1 ? offsets.a : -offsets.b + const b = v === v1 ? offsets.b : -offsets.a + const pA = { x: meetingPoint.x + nUnit.x * a, y: meetingPoint.y + nUnit.y * a } + const pB = { x: meetingPoint.x - nUnit.x * -b, y: meetingPoint.y - nUnit.y * -b } const edgeA = createLineFromPointAndVector(pA, v) const edgeB = createLineFromPointAndVector(pB, v) @@ -339,8 +345,10 @@ function calculateJunctionIntersections( if (L < 1e-9) continue const nUnit = { x: -v.y / L, y: v.x / L } - const pA = { x: meetingPoint.x + nUnit.x * halfT, y: meetingPoint.y + nUnit.y * halfT } - const pB = { x: meetingPoint.x - nUnit.x * halfT, y: meetingPoint.y - nUnit.y * halfT } + const a = endType === 'start' ? offsets.a : -offsets.b + const b = endType === 'start' ? offsets.b : -offsets.a + const pA = { x: meetingPoint.x + nUnit.x * a, y: meetingPoint.y + nUnit.y * a } + const pB = { x: meetingPoint.x - nUnit.x * -b, y: meetingPoint.y - nUnit.y * -b } const edgeA = createLineFromPointAndVector(pA, v) const edgeB = createLineFromPointAndVector(pB, v) @@ -365,7 +373,7 @@ function calculateJunctionIntersections( return a.wallId < b.wallId ? -1 : a.wallId > b.wallId ? 1 : 0 }) - const wallIntersections = new Map() + const wallIntersections: WallIntersections = new Map() const n = processedWalls.length if (n < 2) return wallIntersections @@ -420,6 +428,49 @@ function calculateJunctionIntersections( } } + if (connectedWalls.some(({ wall }) => wall.justification !== undefined)) { + const host = connectedWalls.find(({ endType }) => endType === 'passthrough') + for (const entry of connectedWalls) { + if (entry.endType === 'passthrough') continue + const edges = wallIntersections.get(entry.wall.id) + if (!edges) continue + if (host && edges.left && edges.right) { + // Both edges already meet the host's near face. Closing through the + // reference vertex would add a triangular sliver inside the host. + edges.closing = { + x: (edges.left.x + edges.right.x) / 2, + y: (edges.left.y + edges.right.y) / 2, + } + } else if (connectedWalls.length === 2) { + const other = connectedWalls.find((candidate) => candidate !== entry)! + if (other.endType === 'passthrough') continue + const bodyLine = (candidate: typeof entry) => { + const frame = getWallBoundaryFrame(candidate.wall, candidate.endType as 'start' | 'end') + const offset = getWallBodyCenterOffset(candidate.wall) + return createLineFromPointAndVector( + { + x: frame.point.x + frame.normal.x * offset, + y: frame.point.y + frame.normal.y * offset, + }, + frame.tangent, + ) + } + const first = bodyLine(entry) + const second = bodyLine(other) + const det = first.a * second.b - second.a * first.b + if (Math.abs(det) < 1e-9) continue + const closing = { + x: (first.b * second.c - second.b * first.c) / det, + y: (second.a * first.c - first.a * second.c) / det, + } + const limit = MITER_LIMIT * Math.max(...processedWalls.map((wall) => wall.halfThickness)) + if (Math.hypot(closing.x - meetingPoint.x, closing.y - meetingPoint.y) <= limit) { + edges.closing = closing + } + } + } + } + return wallIntersections } @@ -437,13 +488,12 @@ export interface WallMiterData { /** * Calculates miter data for all walls on a level */ -export function calculateLevelMiters(walls: WallNode[]): WallMiterData { - const getThickness = (wall: WallNode) => wall.thickness ?? 0.1 +export function calculateLevelMiters(walls: WallNode[], facePadding = 0): WallMiterData { const junctions = findJunctions(walls) const junctionData: JunctionData = new Map() for (const [key, junction] of junctions.entries()) { - const wallIntersections = calculateJunctionIntersections(junction, getThickness) + const wallIntersections = calculateJunctionIntersections(junction, facePadding) junctionData.set(key, wallIntersections) } @@ -453,9 +503,11 @@ export function calculateLevelMiters(walls: WallNode[]): WallMiterData { export function getWallMiterBoundaryPoints( wall: WallNode, miterData: WallMiterData, + facePadding = 0, ): WallMiterBoundaryPoints | null { - const thickness = wall.thickness ?? 0.1 - const halfThickness = thickness / 2 + const faces = getWallFaceOffsets(wall) + const { a, b } = + facePadding === 0 ? faces : { a: faces.a + facePadding, b: faces.b - facePadding } const startFrame = getWallBoundaryFrame(wall, 'start') const endFrame = getWallBoundaryFrame(wall, 'end') const startJunction = miterData.junctionData.get(pointToKey(startFrame.point))?.get(wall.id) @@ -463,20 +515,20 @@ export function getWallMiterBoundaryPoints( return { startLeft: startJunction?.left ?? { - x: startFrame.point.x + startFrame.normal.x * halfThickness, - y: startFrame.point.y + startFrame.normal.y * halfThickness, + x: startFrame.point.x + startFrame.normal.x * a, + y: startFrame.point.y + startFrame.normal.y * a, }, startRight: startJunction?.right ?? { - x: startFrame.point.x - startFrame.normal.x * halfThickness, - y: startFrame.point.y - startFrame.normal.y * halfThickness, + x: startFrame.point.x - startFrame.normal.x * -b, + y: startFrame.point.y - startFrame.normal.y * -b, }, endLeft: endJunction?.right ?? { - x: endFrame.point.x + endFrame.normal.x * halfThickness, - y: endFrame.point.y + endFrame.normal.y * halfThickness, + x: endFrame.point.x + endFrame.normal.x * a, + y: endFrame.point.y + endFrame.normal.y * a, }, endRight: endJunction?.left ?? { - x: endFrame.point.x - endFrame.normal.x * halfThickness, - y: endFrame.point.y - endFrame.normal.y * halfThickness, + x: endFrame.point.x - endFrame.normal.x * -b, + y: endFrame.point.y - endFrame.normal.y * -b, }, } } diff --git a/packages/core/src/systems/wall/wall-operations.ts b/packages/core/src/systems/wall/wall-operations.ts index 516f65fd9b..6177761e3c 100644 --- a/packages/core/src/systems/wall/wall-operations.ts +++ b/packages/core/src/systems/wall/wall-operations.ts @@ -84,6 +84,7 @@ export function planWallDivision( nodes: Record, wallId: WallNode['id'], distance: number, + mintId?: () => string, ) { const wall = nodes[wallId] if (wall?.type !== 'wall' || !wall.parentId) throw Error('Select a wall.') @@ -95,6 +96,7 @@ export function planWallDivision( levelId: wall.parentId as AnyNodeId, point: [point.x, point.y], radius: 0.001, + mintId, ignoreWallIds: Object.values(nodes) .filter((n) => n.type === 'wall' && n.id !== wallId) .map((n) => n.id), diff --git a/packages/core/src/systems/wall/wall-reference-line.test.ts b/packages/core/src/systems/wall/wall-reference-line.test.ts new file mode 100644 index 0000000000..65afca4fae --- /dev/null +++ b/packages/core/src/systems/wall/wall-reference-line.test.ts @@ -0,0 +1,185 @@ +import { describe, expect, test } from 'bun:test' +import { lockOutsideFaces } from '../../commands/structure/lock-outside-faces' +import { setWallGeometry } from '../../commands/structure/set-wall-geometry' +import { applyToScratch, structureChangeBatch } from '../../commands/structure/shared' +import { area, intersection, union } from '../../lib/polygon-boolean' +import { reconcileSceneStructure } from '../../lib/structure-reconcile' +import { type AnyNode, LevelNode, WallNode } from '../../schema' +import { calculateLevelMiters, getWallPlanFootprint } from './wall-footprint' +import { faceOnLine, justificationForFaceOnLine, planWallJustification } from './wall-frame' +import { roomSideFaces } from './wall-room-sides' + +const grid: [number, number][] = [ + [4, -11], + [9, -11], + [9, -5], + [4, -5], +] +function house(reverse = false) { + const level = LevelNode.parse({ id: 'level_reference' }) + const walls = grid.map((start, i) => + WallNode.parse({ + id: `wall_reference${i}`, + parentId: level.id, + thickness: 0.2, + start: reverse ? grid[(i + 1) % 4]! : start, + end: reverse ? start : grid[(i + 1) % 4]!, + frontSide: 'exterior', + backSide: 'exterior', + }), + ) + const nodes: Record = Object.fromEntries( + [level, ...walls].map((node) => [node.id, node]), + ) + return { level, walls, nodes } +} +const vertices = (points: [number, number][]) => + new Set(points.map(([x, z]) => `${Number(x.toFixed(12))},${Number(z.toFixed(12))}`)) + +function expectGridMiters(walls: WallNode[], thickness: number) { + const miters = calculateLevelMiters(walls) + const footprints = walls.map((wall) => + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ) + for (const corner of grid) + expect( + footprints.filter((polygon) => + polygon.some((point) => point[0] === corner[0] && point[1] === corner[1]), + ), + ).toHaveLength(2) + for (let i = 0; i < footprints.length; i++) + for (let j = i + 1; j < footprints.length; j++) + expect(area(intersection(footprints[i]!, footprints[j]!))).toBeCloseTo(0, 12) + const body = union(footprints) + expect(body).toHaveLength(1) + expect(vertices(body[0]!.outer)).toEqual(vertices(grid)) + expect(body[0]!.holes).toHaveLength(1) + expect(vertices(body[0]!.holes[0]!)).toEqual( + vertices([ + [4 + thickness, -11 + thickness], + [9 - thickness, -11 + thickness], + [9 - thickness, -5 - thickness], + [4 + thickness, -5 - thickness], + ]), + ) + expect(area(body)).toBeCloseTo(30 - (5 - 2 * thickness) * (6 - 2 * thickness), 10) +} + +describe('fixed wall reference lines', () => { + test('face-on-line helpers map body sides to the opposite anchored face', () => { + for (const face of ['a', 'b', 'center'] as const) { + const justification = justificationForFaceOnLine(face) + expect(justification).toBe(face === 'a' ? 'b' : face === 'b' ? 'a' : undefined) + expect(faceOnLine({ justification })).toBe(face) + } + }) + + for (const reverse of [false, true]) { + test(`room sides come from spans, not stored classifications (reverse=${reverse})`, () => { + const { nodes, walls } = house(reverse) + for (const wall of walls) + expect(roomSideFaces(nodes, wall.id)).toEqual({ + inside: reverse ? 'b' : 'a', + outside: reverse ? 'a' : 'b', + }) + }) + + test(`outside-face locking and thickness 0.2→0.4 keep grid corners and clean inner miters (reverse=${reverse})`, () => { + const { nodes, walls, level } = house(reverse) + const references = JSON.stringify(walls.map(({ start, end }) => ({ start, end }))) + const plan = lockOutsideFaces(nodes, { levelId: level.id }) + expect(plan.conflicts).toBeUndefined() + expect(plan.wallIds.sort()).toEqual(walls.map((wall) => wall.id).sort()) + for (const change of plan.changes) { + expect(change.op).toBe('update') + if (change.op === 'update') expect(Object.keys(change.data)).toEqual(['justification']) + } + let after = applyToScratch(nodes, structureChangeBatch(plan.changes)) + const currentWalls = () => walls.map((wall) => after[wall.id] as WallNode) + expectGridMiters(currentWalls(), 0.2) + for (const wall of walls) + after = applyToScratch( + after, + structureChangeBatch( + setWallGeometry(after, { + wallId: wall.id, + thickness: 0.4, + mintId: () => { + throw Error('No new boundary IDs') + }, + }).changes, + ), + ) + expectGridMiters(currentWalls(), 0.4) + expect(JSON.stringify(currentWalls().map(({ start, end }) => ({ start, end })))).toBe( + references, + ) + expect(lockOutsideFaces(after, { levelId: level.id })).toEqual({ changes: [], wallIds: [] }) + }) + } + + test('shared and unbounded walls have no unique inside or outside face and are not locked', () => { + const { nodes, level } = house() + const shared = WallNode.parse({ + id: 'wall_shared', + parentId: level.id, + start: [6, -11], + end: [6, -5], + }) + const loose = WallNode.parse({ + id: 'wall_loose', + parentId: level.id, + start: [20, 0], + end: [25, 0], + }) + const anotherLevel = WallNode.parse({ + id: 'wall_otherlevel', + parentId: 'level_other', + start: [4, -11], + end: [9, -11], + }) + const graph = { + ...nodes, + [shared.id]: shared, + [loose.id]: loose, + [anotherLevel.id]: anotherLevel, + } + for (const wall of [shared, loose, anotherLevel]) + expect(roomSideFaces(graph, wall.id)).toEqual({ inside: null, outside: null }) + const plan = lockOutsideFaces(graph, { levelId: level.id }) + expect(plan.wallIds).toHaveLength(4) + expect(plan.wallIds).not.toContain(shared.id) + expect(plan.wallIds).not.toContain(loose.id) + }) + + test('zone-scoped locking leaves other rooms untouched and reports only changed walls', () => { + const { nodes, walls } = house() + const other = walls.map((wall, i) => ({ + ...wall, + id: `wall_other${i}` as WallNode['id'], + start: [wall.start[0] + 20, wall.start[1]] as [number, number], + end: [wall.end[0] + 20, wall.end[1]] as [number, number], + })) + let serial = 0 + const graph = reconcileSceneStructure({ + nodes: { ...nodes, ...Object.fromEntries(other.map((wall) => [wall.id, wall])) }, + mintId: (kind) => `${kind}_reference${++serial}`, + }).nodes + const zone = Object.values(graph).find( + (node) => node.type === 'zone' && node.boundaryWallIds.includes(walls[0]!.id), + )! + const plan = lockOutsideFaces(graph, { zoneIds: [zone.id] }) + expect(plan.wallIds.sort()).toEqual(walls.map((wall) => wall.id).sort()) + const after = applyToScratch(graph, structureChangeBatch(plan.changes)) + for (const wall of other) expect(after[wall.id]).toEqual(graph[wall.id]) + }) + + test('justification planner rejects a missing wall and never mutates its input', () => { + const { nodes, walls } = house() + const before = JSON.stringify(nodes) + expect(() => planWallJustification(nodes, 'wall_missing', 'a')).toThrow('Select a wall') + const plan = planWallJustification(nodes, walls[0]!.id, 'a') + expect(plan).toEqual([{ id: walls[0]!.id, data: { justification: 'a' } }]) + expect(JSON.stringify(nodes)).toBe(before) + }) +}) diff --git a/packages/core/src/systems/wall/wall-room-sides.ts b/packages/core/src/systems/wall/wall-room-sides.ts new file mode 100644 index 0000000000..9eee932461 --- /dev/null +++ b/packages/core/src/systems/wall/wall-room-sides.ts @@ -0,0 +1,25 @@ +import { extractRooms } from '../../lib/room-graph' +import type { BoundaryNode } from '../../lib/room-topology-index' +import type { SceneNodes } from '../../lib/structure-kernel' + +export function roomSideFaces( + nodes: SceneNodes, + wallId: string, +): { inside: 'a' | 'b' | null; outside: 'a' | 'b' | null } { + const wall = nodes[wallId] + if (wall?.type !== 'wall') throw Error('Select a wall.') + const boundaries = Object.values(nodes).filter( + (node): node is BoundaryNode => + node.parentId === wall.parentId && (node.type === 'wall' || node.type === 'separator'), + ) + const sides = new Set( + extractRooms(boundaries).flatMap((room) => + room.spans + .filter((span) => span.boundaryId === wallId && span.t1 > span.t0) + .map((span) => span.face), + ), + ) + if (sides.size !== 1) return { inside: null, outside: null } + const inside = [...sides][0]! + return { inside, outside: inside === 'a' ? 'b' : 'a' } +} diff --git a/packages/core/src/systems/wall/wall-step-openings.ts b/packages/core/src/systems/wall/wall-step-openings.ts new file mode 100644 index 0000000000..27f4c64c6a --- /dev/null +++ b/packages/core/src/systems/wall/wall-step-openings.ts @@ -0,0 +1,46 @@ +import type { WallNode } from '../../schema' +import type { WallSlabSupportSegment } from '../slab/slab-support' +import { getWallCurveFrameAt } from './wall-curve' + +export function wallDoorStepRuns( + wall: WallNode, + opening: { type: string; width?: number; height?: number; position?: [number, number, number] }, + faceBase: { a: readonly WallSlabSupportSegment[]; b: readonly WallSlabSupportSegment[] }, + elevation: number, +): Array<{ start: number; end: number; bottom: number; top: number }> { + if ((opening.type !== 'door' && opening.type !== 'window') || !opening.position) return [] + const sill = opening.position[1] - (opening.height ?? 0) / 2 + if (sill > 0.01) return [] + const dx = wall.end[0] - wall.start[0] + const dy = wall.end[1] - wall.start[1] + const length = Math.hypot(dx, dy) + if (length < 1e-9) return [] + const station = (t: number) => { + const { point } = getWallCurveFrameAt(wall, t) + return ((point.x - wall.start[0]) * dx + (point.y - wall.start[1]) * dy) / length + } + const runs: Array<{ start: number; end: number; bottom: number; top: number }> = [] + for (const a of faceBase.a) + for (const b of faceBase.b) { + const from = Math.max(a.start, b.start) + const to = Math.min(a.end, b.end) + const low = Math.min( + a.elevation, + a.endElevation ?? a.elevation, + b.elevation, + b.endElevation ?? b.elevation, + ) + const high = Math.max( + a.elevation, + a.endElevation ?? a.elevation, + b.elevation, + b.endElevation ?? b.elevation, + ) + if (to <= from || high - low < 1e-6) continue + const start = Math.max(station(from), opening.position[0] - (opening.width ?? 0) / 2) + const end = Math.min(station(to), opening.position[0] + (opening.width ?? 0) / 2) + if (end > start) + runs.push({ start, end, bottom: low - elevation, top: Math.max(sill, high - elevation) }) + } + return runs +} diff --git a/packages/core/src/systems/wall/wall-top.test.ts b/packages/core/src/systems/wall/wall-top.test.ts index a743dcad21..e27feb10d0 100644 --- a/packages/core/src/systems/wall/wall-top.test.ts +++ b/packages/core/src/systems/wall/wall-top.test.ts @@ -10,8 +10,8 @@ describe('resolveWallTop', () => { expect(resolveWallTop({ height: 2.5 }, 3, 0.6)).toBeCloseTo(3.1) }) - test('explicit height on sunken base keeps the absolute top', () => { - expect(resolveWallTop({ height: 2.5 }, 3, -0.4)).toBe(2.5) + test('explicit height on sunken support follows its actual support', () => { + expect(resolveWallTop({ height: 2.5 }, 3, -0.4)).toBe(2.1) }) test('ground-hosted explicit height remains body-relative in a terrain depression', () => { diff --git a/packages/core/src/systems/wall/wall-top.ts b/packages/core/src/systems/wall/wall-top.ts index 2bbf475da7..461af204d0 100644 --- a/packages/core/src/systems/wall/wall-top.ts +++ b/packages/core/src/systems/wall/wall-top.ts @@ -14,12 +14,8 @@ export const MIN_WALL_HEIGHT = 0.5 * `height` is plane-bound — its top sits at the storey plane (level-local * Y = the level's stored height), so a slab lifting the wall's base makes * the wall shorter, never taller, and no gap can open at the top of a - * level. A wall WITH `height` is an explicit exception (half wall, - * parapet) and keeps the legacy semantics: the top rides a raised elected - * base (`electedBase + height`), while a zero or sunken slab base leaves - * the top at `height` (the legacy negative-slab constraint). Explicit - * ground-hosted walls are the terrain exception: `height` is always body - * height, including below datum, so sculpting cannot stretch the wall. + * level. Explicit walls stand on their elected support; room floor datums do not + * change their tops. Ground-hosted walls retain their authored body height. * * Returns the top in level-local Y (same frame as `electedBase`). */ @@ -29,8 +25,7 @@ export function resolveWallTop( electedBase: number, ): number { if (wall.height == null) return storeyHeight - if (wall.supportSlabId === 'ground') return electedBase + wall.height - return electedBase > 0 ? electedBase + wall.height : wall.height + return electedBase + wall.height } /** diff --git a/packages/core/src/systems/wall/wall-topology.ts b/packages/core/src/systems/wall/wall-topology.ts index d97477a9ed..8091a842d2 100644 --- a/packages/core/src/systems/wall/wall-topology.ts +++ b/packages/core/src/systems/wall/wall-topology.ts @@ -201,6 +201,7 @@ export function planWallSplitAtPoint( point: WallPlanPoint radius: number ignoreWallIds?: readonly string[] + mintId?: () => string }, ): WallPointSplitResult { if (!args.levelId) return { ok: false, reason: 'no-host' } @@ -221,7 +222,7 @@ export function planWallSplitAtPoint( } } - const split = splitWall(projection.wall, [projection.wallT], nodes) + const split = splitWall(projection.wall, [projection.wallT], nodes, args.mintId) if (!split) { return { ok: true, @@ -410,6 +411,7 @@ function splitWall( wall: WallNode, splitParameters: number[], nodes: Record, + mintId?: () => string, ): { create: WallNode[]; update: WallTopologyChanges['update'] } | null { const parameters = [ 0, @@ -423,6 +425,7 @@ function splitWall( const endT = parameters[index + 1]! return WallSchema.parse({ ...properties, + id: mintId?.(), start: wallPointAt(wall, startT), end: wallPointAt(wall, endT), curveOffset: segmentCurveOffset(wall, startT, endT), @@ -483,6 +486,7 @@ export function planWallInsertion( end: WallPlanPoint joinRadius: number wallDefaults?: Partial + mintId?: () => string }, ): WallInsertionResult { const walls = Object.values(nodes).filter( @@ -533,6 +537,7 @@ export function planWallInsertion( const insertedWalls = vertices.slice(0, -1).map((start, index) => WallSchema.parse({ ...wallProperties, + id: args.mintId?.(), name: `Wall ${existingWallCount + index + 1}`, start, end: vertices[index + 1]!, @@ -562,7 +567,7 @@ export function planWallInsertion( } const splitPlans = [...splitWalls].flatMap(([wallId, parameters]) => { const wall = walls.find((candidate) => candidate.id === wallId) - const split = wall ? splitWall(wall, parameters, nodes) : null + const split = wall ? splitWall(wall, parameters, nodes, args.mintId) : null return split ? [[wallId, split] as const] : [] }) const replacementWalls = splitPlans.flatMap(([, split]) => split.create) diff --git a/packages/core/src/utils/__fixtures__/project_hrY3qVVq16yo5Out.json b/packages/core/src/utils/__fixtures__/project_hrY3qVVq16yo5Out.json new file mode 100644 index 0000000000..16ce5c7239 --- /dev/null +++ b/packages/core/src/utils/__fixtures__/project_hrY3qVVq16yo5Out.json @@ -0,0 +1,1684 @@ +{ + "building_5v9otmci5xp1wnhh": { + "id": "building_5v9otmci5xp1wnhh", + "type": "building", + "object": "node", + "visible": true, + "children": ["level_49wv4wg9qwu8cdk9"], + "metadata": {}, + "parentId": "site_mvx8m7yyc39e1smp", + "position": [0, 0, 0], + "rotation": [0, 0, 0] + }, + "level_49wv4wg9qwu8cdk9": { + "id": "level_49wv4wg9qwu8cdk9", + "type": "level", + "level": 0, + "height": 3, + "object": "node", + "visible": true, + "children": [ + "wall_fpx8o075hq6y0b51", + "wall_waukxmbz1xgpo3uz", + "wall_9wdfdhzy4qz68ilm", + "slab_6fqcmyumgepzz4j2", + "zone_s8w1h8ts08zbm0b1", + "wall_hmlcr6q6v0aruavb", + "wall_j319mkwc1vi4cl6m", + "wall_sma964h5z3k0ynlk", + "wall_whesh84hbmzk9p49", + "wall_c9xx17ktxy51nui5", + "wall_41jffy2tnmdl0gc0", + "wall_hvjnal61prxmk6x4", + "zone_mmzxkt8um9no5cll", + "wall_snscx5m2kic1hqw2", + "wall_mnoueqhnf0aexcu5", + "wall_akkayrvsc1pb6hjr", + "wall_2600142xho00v4fk", + "wall_v9jvvk057lebisg5", + "slab_65xint1844mjfpq3", + "zone_h4qclonp6vouqlqm", + "wall_wqi5tg89q8zv0m9w", + "wall_zu4ebpy79h7gk7r4", + "wall_y0hxdxg4kza4gt8o", + "wall_kyvo0oiqs99d02pv", + "wall_omk0tc4npjlsvntq", + "wall_rt14i8czy34wr26q", + "wall_c7jk752xvqsnizqk", + "wall_04rrl8mtji8cf1z7", + "wall_eggqb82wyybewfk9", + "slab_wnihmajd74hdhvcr", + "zone_0kzuwr4ui78ielwl", + "wall_ciz8erukqrywghdb", + "wall_mpjxrwzo00no6wrg", + "wall_ctalbahlmd3vnmng", + "slab_dx57cusmtetbabnt", + "zone_kvc4i5vnlk4d08yf", + "wall_clmz7s4si6009k82", + "wall_blbamxukj5bso79i", + "wall_oesf7bdw7cj3hntc", + "slab_4je1h0urbc2381ot", + "zone_zmv4bjoua1ahtpdn", + "wall_sjray90wzrf8yia8", + "wall_u5xwascyhkhtdf5m", + "zone_3w782992d6tv00h5", + "wall_d2wimkt9g4zd584i", + "wall_kdjc2ughv4aisaxp", + "wall_6tyy4eohr25wofta", + "wall_n7gamfwj6irb0dsc", + "zone_6jt3eph1iiu4hqi3", + "wall_abdgum6am7aqoqwg", + "wall_fmyqg07i29x3nw5o", + "wall_d23z0a3o5u4nfcsv", + "zone_w96chgxaqu67c23c", + "wall_wq05x337zwwk7r42", + "wall_3j7hcksl6y2rsm39", + "wall_p9s2fpf9avxxi2vt", + "wall_i07i0ufmf1dsmgjv", + "wall_8li7fg3u9ghxd4sa", + "wall_d4ec8qu116hpf9l7", + "slab_1qje0juga31onkln", + "zone_z5f9lvn4m7h5jtrk", + "wall_thkpqe1od6aqrxhe", + "wall_apb9q249sol18q4z", + "wall_ar1bpcjqq8s7ncy2", + "wall_kxys17u4xyces94y", + "slab_2j9823emfbp5e7ig", + "zone_fwjqak0yxy07jgs9", + "wall_4u44u7ip1lqd2xvl", + "wall_pc57959ci5p3d0rz", + "wall_vinisg7m07bld3ov", + "wall_sn5fql4rclj1g9vs", + "slab_nh9pgajr35qw2muf", + "wall_ulgfa6txtf5yh69p", + "wall_z8kfjunz24xutwpx", + "zone_pay55xzusiol0e2v", + "wall_w1vjmei9mmynvxlx", + "wall_158ezcg8ypcmjd22", + "slab_vfnmte9mpbg8xhr1", + "slab_mnei6ci9p5w192fs", + "wall_dqotyps20fj3qv0f", + "wall_o2prcvlxmpsgwcsy", + "wall_ogqe6lyv9h0isd8e", + "wall_mj6lr1gxatm7pcf4", + "wall_uc138w3km1qpypgd", + "wall_oricpf6gwb5nc5m0", + "wall_t0vbmksu3txdxi58", + "wall_embuuvuakc3y0o7c", + "slab_cddqctwjp3vj685p", + "slab_x8s2lexms1y89l9f", + "slab_zr59sk2exixa4ld3", + "slab_dtohj2wghfnlf1mf", + "slab_1zsna49glc8ez1at", + "wall_1cipacj9vfe22kde" + ], + "metadata": {}, + "parentId": "building_5v9otmci5xp1wnhh", + "baseElevation": 0 + }, + "site_mvx8m7yyc39e1smp": { + "id": "site_mvx8m7yyc39e1smp", + "type": "site", + "object": "node", + "polygon": { "type": "polygon", "points": [[-15, -15], [15, -15], [15, 15], [-15, 15]] }, + "visible": true, + "children": ["building_5v9otmci5xp1wnhh"], + "metadata": {}, + "parentId": null + }, + "slab_1qje0juga31onkln": { + "id": "slab_1qje0juga31onkln", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [3.1318685080276216, -4.3412497001265], + [11.261660174864861, -4.341249992437693], + [11.26165987489183, -1.3166851233565569], + [3.131868208054532, -1.3166857310453555], + [1.7318390128066048, -1.3166857522417288], + [1.7318388127796835, -4.341249921322843] + ], + "visible": true, + "metadata": { + "source": "roomplan-capture", + "roomPlanId": "AFD15E8A-B925-49F2-99C8-DDCE3BCD9631" + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_1zsna49glc8ez1at": { + "id": "slab_1zsna49glc8ez1at", + "name": "Room 8 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-5.578990643128957, -2.311886306999239], + [-3.500141666851124, -2.3118863053824557], + [-3.5000130168096093, -1.2052976147296652], + [-5.578990662706296, -1.211886194285928] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_2j9823emfbp5e7ig": { + "id": "slab_2j9823emfbp5e7ig", + "name": "Slab 11", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [10.690862825949877, -6], + [3.5, -6.000000000000001], + [3.5, -9], + [10.690862825949877, -9] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": true, + "elevation": -1, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_4je1h0urbc2381ot": { + "id": "slab_4je1h0urbc2381ot", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-1.9456099538637213, 1.0880206383535302], + [-2.7178443830805836, 1.0880207008194727], + [-2.717844548767803, -1.164702899180534], + [-1.9456100195509443, -1.164702861646473] + ], + "visible": true, + "metadata": { + "source": "roomplan-capture", + "roomPlanId": "2A5C927D-730B-4DAE-BAE8-D62AEBEEB779" + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_65xint1844mjfpq3": { + "id": "slab_65xint1844mjfpq3", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [2.5716767943763723, 2.3510191118422874], + [4.822475421882922, 2.351019432399015], + [4.822475671597212, -1.3824471185683471], + [7.721551752267856, -1.3824467290333047], + [7.763055661504598, 5.985278163001843], + [2.5716767489987946, 6.014654330796113] + ], + "visible": true, + "metadata": { + "source": "roomplan-capture", + "roomPlanId": "9CA92DA2-51DC-47D5-884B-5A5DBEE8EF79" + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_6fqcmyumgepzz4j2": { + "id": "slab_6fqcmyumgepzz4j2", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-1.9350279515296496, 2.287666572716621], + [-1.9350281705311942, -4.381449889032432], + [1.7318390044139351, -4.3814499610074895], + [1.7318391543420888, -1.342338648438425], + [4.800937538262154, -1.3423390071707155], + [4.769960447800703, 2.2876665268412326] + ], + "visible": true, + "metadata": { + "source": "roomplan-capture", + "roomPlanId": "C3C744EF-CB39-423F-B1D7-3B727EC5EA4A" + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_cddqctwjp3vj685p": { + "id": "slab_cddqctwjp3vj685p", + "name": "Room 3 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [2.548658053581587, 5.204869548847936], + [0.6159617243111328, 5.204557895486837], + [0.6140376853951405, 2.291596129389948], + [1.8336350037710347, 2.2917924498244733], + [1.8334994922723538, 3.133093138910797], + [2.548991673055299, 3.133208248275566] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_dtohj2wghfnlf1mf": { + "id": "slab_dtohj2wghfnlf1mf", + "name": "Room 7 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-5.5748472989710995, 4.204273690952256], + [-5.578990662706296, -1.211886194285928], + [-2.801613898394682, -1.2030842873459955], + [-2.8078975889650617, -2.3118863048440765], + [-5.578990643128957, -2.311886306999239], + [-5.5789903056528, -4.327654944240413], + [-1.8999994866085048, -4.327655377317596], + [-1.9448824989711035, 4.204273518791197] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_dx57cusmtetbabnt": { + "id": "slab_dx57cusmtetbabnt", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [9.667784381795945, 5.985240833463578], + [9.667784552703587, 3.3576415343044177], + [11.290862944581027, 3.357641638840282], + [11.290862873673385, 5.985240937999448] + ], + "visible": true, + "metadata": { + "source": "roomplan-capture", + "roomPlanId": "0D18D0D2-EF44-4472-BD3E-04A979EAAB09" + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_mnei6ci9p5w192fs": { + "id": "slab_mnei6ci9p5w192fs", + "name": "Slab 14", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-1.0573241952891939, 11], + [0.6159615786939349, 11], + [0.8715094819068874, 10.64999848401666], + [0.8715329119984998, 5.204654469581486], + [1.8727098148056258, 5.2065555018517085], + [1.9488500549625487, 11.706555501851708], + [1.2238363505409455, 12.204784949064807], + [-1.0438286098140714, 12.204784949064807] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "elevation": 0, + "thickness": 0, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_nh9pgajr35qw2muf": { + "id": "slab_nh9pgajr35qw2muf", + "name": "Room 1 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [0.6154957222742798, 4.253847574926246], + [0.615961578693935, 5.204557989712588], + [0.2, 5.204557989712587], + [0.2, 10.25], + [-5.634038421306065, 10.25], + [-5.5748472989710995, 4.204273690952256] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_vfnmte9mpbg8xhr1": { + "id": "slab_vfnmte9mpbg8xhr1", + "name": "Slab 13", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-5, 10.5], + [-5, 13.1], + [-6.909188309203678, 15.009188309203678], + [0.6159615786939349, 15.009188309203678], + [-1.1076205322687251, 13.241421356237309], + [-1.1076205322687251, 10.35], + [-5.007620532268725, 10.35] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "elevation": 0, + "thickness": 0, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_wnihmajd74hdhvcr": { + "id": "slab_wnihmajd74hdhvcr", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [7.7686878927486775, -1.3569634958739516], + [11.268719631136921, -1.3542782528149302], + [11.265133518016642, 3.3206733565574496], + [9.57573976436087, 3.319377341174972], + [9.667784345207762, 5.985241013872873], + [7.763055661504598, 5.985278163001843], + [7.775512187765003, 3.334486855075343], + [7.765089128937167, 3.3344785085923254] + ], + "visible": true, + "metadata": { + "source": "roomplan-capture", + "roomPlanId": "7724F97F-BEE1-4225-B8A0-3D2E2960117F" + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": false + }, + "slab_x8s2lexms1y89l9f": { + "id": "slab_x8s2lexms1y89l9f", + "name": "Room 4 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-1.0800002058335794, 4.2243063427133665], + [-1.0431927931216172, 2.291329286056133], + [0.6140375223634358, 2.291596068677496], + [0.6154957222742798, 4.253847574926246] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "slab_zr59sk2exixa4ld3": { + "id": "slab_zr59sk2exixa4ld3", + "name": "Room 6 Slab", + "type": "slab", + "holes": [], + "object": "node", + "polygon": [ + [-2.801613898394682, -1.2030842873459955], + [-3.5000130168096093, -1.2052976147296652], + [-3.500141666851124, -2.3118863053824557], + [-2.8078975889650617, -2.3118863048440765] + ], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "recessed": false, + "elevation": 0.05, + "thickness": 0.05, + "holeMetadata": [], + "autoFromWalls": true + }, + "wall_04rrl8mtji8cf1z7": { + "id": "wall_04rrl8mtji8cf1z7", + "end": [7.765128850581156, 3.2830311846132973], + "type": "wall", + "start": [8.497532635063607, 3.2835930491762335], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": { "roomPlanId": "FD2D8D32-1541-4922-95F3-AB1DB2B04C4D" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_158ezcg8ypcmjd22": { + "id": "wall_158ezcg8ypcmjd22", + "end": [4, 10.25], + "name": "Wall 71", + "type": "wall", + "start": [0.2, 10.25], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_5aj0f9dc9wzigfsm"], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "unknown" + }, + "wall_1cipacj9vfe22kde": { + "id": "wall_1cipacj9vfe22kde", + "end": [7.765128850581156, 3.2830311846132973], + "type": "wall", + "start": [7.763055661504598, 5.985278163001843], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_v7y0nyvtvpyrfm9q", "wall_zj7kn4dpskexv48q"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_2600142xho00v4fk": { + "id": "wall_2600142xho00v4fk", + "end": [2.582157822264498, 6.013681255286715], + "type": "wall", + "start": [7.763055661504598, 5.985278163001843], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_wxf5yq022k7qqxi4", "window_g10a3tgqczm1hbno", "window_jrd1o2xlhfxqz089"], + "metadata": { "roomPlanId": "CBFF863A-B5DF-4FAF-A9E9-5D7A00C346DC" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_3j7hcksl6y2rsm39": { + "id": "wall_3j7hcksl6y2rsm39", + "end": [-1.9000000171688924, 1.1474862007346474], + "type": "wall", + "start": [-2.80789750521557, 1.1474861333516475], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_edmshjkbqyogya1s", "door_bj5huobxgqiqk3lz"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_05fkpjoafiqq206e", "wall_xpzb6fvdr568w784"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_41jffy2tnmdl0gc0": { + "id": "wall_41jffy2tnmdl0gc0", + "end": [0.6161330816873696, 4.140102009279494], + "type": "wall", + "start": [0.6159617243111328, 5.204557895486837], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": { "roomPlanId": "DDB42CCD-E1BD-42C1-8A1F-798AB4F8A43C" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_4u44u7ip1lqd2xvl": { + "id": "wall_4u44u7ip1lqd2xvl", + "end": [0.2, 10.25], + "name": "Wall 63", + "type": "wall", + "start": [0.2, 5.204557989712587], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior" + }, + "wall_6tyy4eohr25wofta": { + "id": "wall_6tyy4eohr25wofta", + "end": [-1.8999994866085048, -4.327655377317596], + "type": "wall", + "start": [-5.5789903056528, -4.327654944240413], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_athnjz1yuhbhlvvu"], + "metadata": { "roomPlanId": "C53899AA-6BB3-40EC-A870-220D075C6F47" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_8li7fg3u9ghxd4sa": { + "id": "wall_8li7fg3u9ghxd4sa", + "end": [-1.944882281572331, 4.2042735000631115], + "type": "wall", + "start": [-1.9448822528957115, 2.2876661927133712], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_tbps4166xov26u8o"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_mawm4iqhmkbhrfob", "wall_t5z21c117nejqtdo"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_9wdfdhzy4qz68ilm": { + "id": "wall_9wdfdhzy4qz68ilm", + "end": [4.80093770478662, -1.3423387158354236], + "type": "wall", + "start": [1.7318392047866256, -1.3423385258079605], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_1ajl77t17boow4x8"], + "metadata": { "roomPlanId": "35C0C24C-1174-44D2-A450-D5405EA465FD" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "skirting": { + "proud": 0.02, + "sides": "exterior", + "height": 0.12, + "enabled": true, + "profile": "flat" + }, + "frontSide": "exterior", + "thickness": 0.28 + }, + "wall_abdgum6am7aqoqwg": { + "id": "wall_abdgum6am7aqoqwg", + "end": [-2.8078975783991944, -2.3000000272654164], + "type": "wall", + "start": [-1.8999999776664016, -2.300000018449495], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_c2op5jm4jf3txjg5", "door_7xx7c4l2v3nnu39y"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_risz1xyod6nyieox", "wall_comgpyrow0kdq00q"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_akkayrvsc1pb6hjr": { + "id": "wall_akkayrvsc1pb6hjr", + "end": [1.8336350156867507, 2.2917924324215804], + "type": "wall", + "start": [0.6140376853951405, 2.291596129389948], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_c0xv8gz79r3ct0b0", "door_xu06vmivdjmqy8p1"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_jgi6cgg6fbb5fltz", "wall_qizoheh4d85h2gmr"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_apb9q249sol18q4z": { + "id": "wall_apb9q249sol18q4z", + "end": [4.8224755862814614, -1.3166855446829522], + "type": "wall", + "start": [7.721551586281452, -1.316685511616987], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_7rejaajyks3u9bis"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_d6n2c10fl9wsps2v", "wall_4nvh8ys1hlox0v6v"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_ar1bpcjqq8s7ncy2": { + "id": "wall_ar1bpcjqq8s7ncy2", + "end": [-5.57484788604425, 1.1500000000042818], + "type": "wall", + "start": [-5.5748472989710995, 4.204273690952256], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { "roomPlanId": "C7196FDB-636D-4901-A5DD-49063737389B" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_blbamxukj5bso79i": { + "id": "wall_blbamxukj5bso79i", + "end": [9.667784335264285, 5.348373607576446], + "type": "wall", + "start": [9.667784345207762, 5.985241013872873], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_epem91hxq2vho2cu", "wall_ar8ujn4t0aejl2p1"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_c7jk752xvqsnizqk": { + "id": "wall_c7jk752xvqsnizqk", + "end": [8.497532635063607, 3.2835930491762335], + "type": "wall", + "start": [8.49594906478511, 5.347547054977929], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_5xlzcplcu7kgu0a8"], + "metadata": { "roomPlanId": "3F7B302B-D589-4FE9-B7D2-8AE35C4A7E70" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_c9xx17ktxy51nui5": { + "id": "wall_c9xx17ktxy51nui5", + "end": [2.548991673055299, 3.133208248275566], + "type": "wall", + "start": [1.8334994922723538, 3.133093138910797], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { "roomPlanId": "45F2FFE2-8081-4CAB-8289-5A0C3B1B7EE9" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_ciz8erukqrywghdb": { + "id": "wall_ciz8erukqrywghdb", + "end": [7.768707427709234, -1.382410628636749], + "type": "wall", + "start": [7.765128850581156, 3.2830311846132973], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_0c1fxzah4jxprks1"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_v7y0nyvtvpyrfm9q", "wall_zj7kn4dpskexv48q"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_clmz7s4si6009k82": { + "id": "wall_clmz7s4si6009k82", + "end": [11.265133048804717, 3.2749217710150456], + "type": "wall", + "start": [9.667784335264285, 3.2752561569213867], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["item_l2lc23p7zvex5x4q"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_yqwulu52g1smj2n7", "wall_ii9p7xo0kqhqtl1p"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_ctalbahlmd3vnmng": { + "id": "wall_ctalbahlmd3vnmng", + "end": [9.667784345207762, 5.985241013872873], + "type": "wall", + "start": [11.300000459144922, 5.985241112606367], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { "roomPlanId": "B8FDE747-9F35-47E7-9C8F-3A684A424CD8" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_d23z0a3o5u4nfcsv": { + "id": "wall_d23z0a3o5u4nfcsv", + "end": [-5.5748472989710995, 4.204273690952256], + "type": "wall", + "start": [-1.9448824989711035, 4.204273518791197], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": { "roomPlanId": "C51B793D-007A-47EA-9901-CB45E3827AE7" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_d2wimkt9g4zd584i": { + "id": "wall_d2wimkt9g4zd584i", + "end": [-2.8016138734244334, -0.45308425881444286], + "type": "wall", + "start": [-2.8016138709797285, -1.1647029951880918], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_nzybpa0huug7jfoy", "wall_osnvm2pm20nrsrpd"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_d4ec8qu116hpf9l7": { + "id": "wall_d4ec8qu116hpf9l7", + "end": [11.300000015017705, -1.316685231281994], + "type": "wall", + "start": [11.300000049514956, -4.341249931281993], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { "roomPlanId": "AD5E2ED9-C8BC-4BC3-98F7-EB3FFF1E01B1" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_dqotyps20fj3qv0f": { + "id": "wall_dqotyps20fj3qv0f", + "end": [-2.8078975889650617, -2.3118863048440765], + "name": "Wall 71", + "type": "wall", + "start": [-2.801613898394682, -1.2030842873459955], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_53dzhid6gutd5d7l"], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior" + }, + "wall_eggqb82wyybewfk9": { + "id": "wall_eggqb82wyybewfk9", + "end": [8.500446319580078, 3.2750013083533087], + "type": "wall", + "start": [9.667784335264285, 3.2752561569213867], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_qsuj2usvb3bumvui"], + "metadata": { "roomPlanId": "5226D7C6-0291-4D65-8536-AC4557E752AD" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_embuuvuakc3y0o7c": { + "id": "wall_embuuvuakc3y0o7c", + "end": [-1.9000000342284684, 2.287666193384907], + "name": "Wall 72", + "type": "wall", + "start": [-1.9448822528957115, 2.2876661927133712], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_mawm4iqhmkbhrfob", "wall_t5z21c117nejqtdo"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_fmyqg07i29x3nw5o": { + "id": "wall_fmyqg07i29x3nw5o", + "end": [-1.8999997271500808, -2.3000000133658403], + "type": "wall", + "start": [-1.8999994866085048, -4.327655377317596], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_8gzduhgdpghq8p7w", "wall_fzujh3g4u8180jdz"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_fpx8o075hq6y0b51": { + "id": "wall_fpx8o075hq6y0b51", + "end": [1.7318387751077626, -4.323741654294752], + "type": "wall", + "start": [-1.9350282248922328, -4.323741465405526], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { "roomPlanId": "804A3E9B-39F5-4D49-BAF5-991DACDA4FC8" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_hmlcr6q6v0aruavb": { + "id": "wall_hmlcr6q6v0aruavb", + "end": [-1.0431927538540173, 2.2913291065877464], + "type": "wall", + "start": [-1.0800002058335794, 4.2243063427133665], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { "roomPlanId": "319C90FF-90DE-4C32-9576-9ED1A26498B2" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_hvjnal61prxmk6x4": { + "id": "wall_hvjnal61prxmk6x4", + "end": [0.6140375223634358, 2.291596068677496], + "type": "wall", + "start": [0.6161329915003526, 4.140102080964428], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_6bymfmxodu2ydhxj"], + "metadata": { "roomPlanId": "B9398D05-44F0-4E0D-9DC3-69CBE9796B6F" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_i07i0ufmf1dsmgjv": { + "id": "wall_i07i0ufmf1dsmgjv", + "end": [-1.9000000342284684, 2.287666193384907], + "type": "wall", + "start": [-1.9000000171688924, 1.1474862007346474], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_mawm4iqhmkbhrfob", "wall_t5z21c117nejqtdo"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_j319mkwc1vi4cl6m": { + "id": "wall_j319mkwc1vi4cl6m", + "end": [0.615961578693935, 5.204557989712588], + "type": "wall", + "start": [2.548658053581587, 5.204869548847936], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_tydhrlkuv1wmnrac", "window_zzlciq824af6umc8"], + "metadata": { "roomPlanId": "2CACB381-3B1B-4AC2-9A51-EE497A0D9D39" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_kdjc2ughv4aisaxp": { + "id": "wall_kdjc2ughv4aisaxp", + "end": [-2.801613878718767, 1.0880207048119088], + "type": "wall", + "start": [-2.8016138734244334, -0.45308425881444286], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_h5jnfrwr3dou8e6n"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_nzybpa0huug7jfoy", "wall_osnvm2pm20nrsrpd"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_kxys17u4xyces94y": { + "id": "wall_kxys17u4xyces94y", + "end": [11.300000049514956, -4.341249931281993], + "type": "wall", + "start": [1.7318387751077626, -4.323741654294752], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_olqu7wsbyf66rtrv", "door_6jan2z8wolc86p5k"], + "metadata": { "roomPlanId": "99E1A189-C3DD-45A6-9988-82860F0AD26F" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_kyvo0oiqs99d02pv": { + "id": "wall_kyvo0oiqs99d02pv", + "end": [4.8224756325497715, -1.3824468588203151], + "type": "wall", + "start": [4.822475581078503, -0.43974861559867984], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_846rvyr9xa8q4gy4"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_1p41tryz65xt42kv", "wall_1w06aa037thqvuqo"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_mj6lr1gxatm7pcf4": { + "id": "wall_mj6lr1gxatm7pcf4", + "end": [-3.5000130168096093, -1.2052976147296652], + "type": "wall", + "start": [-5.578990662706296, -1.211886194285928], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": { "roomPlanId": "CBFBC9A7-24E0-47A2-9E5F-77B03A2A2B08" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_mnoueqhnf0aexcu5": { + "id": "wall_mnoueqhnf0aexcu5", + "end": [0.6140376853943497, 2.2915961343032163], + "type": "wall", + "start": [-1.0431927931216172, 2.291329286056133], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["item_wjdczhq0rp8e8f6m"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_a0hd9872frjzc2wr", "wall_j52mxun9aq5co4se"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_mpjxrwzo00no6wrg": { + "id": "wall_mpjxrwzo00no6wrg", + "end": [11.300000459144922, 5.985241112606367], + "type": "wall", + "start": [11.300000257574268, 3.357641412606375], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_jw669w7j3dku7eyn"], + "metadata": { "roomPlanId": "DA674933-A90F-4B4D-A142-4E1F6AEF61B2" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_n7gamfwj6irb0dsc": { + "id": "wall_n7gamfwj6irb0dsc", + "end": [-5.578990607253156, -4.327654894285926], + "type": "wall", + "start": [-5.578990662706296, -1.211886194285928], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_kcfk09dxfraefzrp"], + "metadata": { "roomPlanId": "C7196FDB-636D-4901-A5DD-49063737389B" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_o2prcvlxmpsgwcsy": { + "id": "wall_o2prcvlxmpsgwcsy", + "end": [-3.500141666851124, -2.3118863053824557], + "name": "Wall 72", + "type": "wall", + "start": [-2.8078975889650617, -2.3118863048440765], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior" + }, + "wall_oesf7bdw7cj3hntc": { + "id": "wall_oesf7bdw7cj3hntc", + "end": [9.667784335264285, 3.2752561569213867], + "type": "wall", + "start": [9.667784335264285, 5.348373607576446], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_1jyha8a6j8v2tq42", "door_oi7b479ko5049rq6"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_epem91hxq2vho2cu", "wall_ar8ujn4t0aejl2p1"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_ogqe6lyv9h0isd8e": { + "id": "wall_ogqe6lyv9h0isd8e", + "end": [-5.578990643128957, -2.311886306999239], + "name": "Wall 72", + "type": "wall", + "start": [-3.500141666851124, -2.3118863053824557], + "object": "node", + "visible": true, + "backSide": "unknown", + "children": ["door_zso3sb5g2xcdkw2a"], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "unknown" + }, + "wall_omk0tc4npjlsvntq": { + "id": "wall_omk0tc4npjlsvntq", + "end": [11.300000257574268, 3.357641412606375], + "type": "wall", + "start": [11.301042299390152, -1.3542536621611174], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_0g6c4ah14kz7ix3n"], + "metadata": { "roomPlanId": "6C414E61-CF2C-4BFE-88D8-F2B1682D5ACC" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_oricpf6gwb5nc5m0": { + "id": "wall_oricpf6gwb5nc5m0", + "end": [-3.500141666851124, -2.3118863053824557], + "name": "Wall 74", + "type": "wall", + "start": [-3.5000130168096093, -1.2052976147296652], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior" + }, + "wall_p9s2fpf9avxxi2vt": { + "id": "wall_p9s2fpf9avxxi2vt", + "end": [-1.9448822358361357, 1.1474862000631119], + "type": "wall", + "start": [-1.9448822349464028, 1.0880207289888417], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_mawm4iqhmkbhrfob", "wall_t5z21c117nejqtdo"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_pc57959ci5p3d0rz": { + "id": "wall_pc57959ci5p3d0rz", + "end": [-5.634038421306065, 10.25], + "name": "Wall 64", + "type": "wall", + "start": [0.2, 10.25], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_ogyltqowu8feiapo"], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior" + }, + "wall_rt14i8czy34wr26q": { + "id": "wall_rt14i8czy34wr26q", + "end": [8.495948906295682, 5.347546944668012], + "type": "wall", + "start": [9.667784335264285, 5.348373607576446], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_dd1tjfsufhq87jr8"], + "metadata": { "roomPlanId": "2C439C17-4EAE-4A3D-A3B1-CCAF751ED93B" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_sjray90wzrf8yia8": { + "id": "wall_sjray90wzrf8yia8", + "end": [-1.9000000171688924, 1.1474862007346474], + "type": "wall", + "start": [-1.8999999776664016, -2.300000018449495], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_u53nrydpjcu6u5nz"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_cejt3xw376i6bv9f", "wall_jgzql1zkdt5ud34l"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_sma964h5z3k0ynlk": { + "id": "wall_sma964h5z3k0ynlk", + "end": [-1.0800002058335794, 4.2243063427133665], + "type": "wall", + "start": [0.6154957222742798, 4.253847574926246], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_hjezvkefhfiw3q7v"], + "metadata": { "roomPlanId": "AA0D1E64-AF12-4612-86AC-7DD51B9C9719" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_sn5fql4rclj1g9vs": { + "id": "wall_sn5fql4rclj1g9vs", + "end": [-1.9448824989711035, 4.204273518791197], + "name": "Wall 66", + "type": "wall", + "start": [-1.0800002058335794, 4.2243063427133665], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior" + }, + "wall_snscx5m2kic1hqw2": { + "id": "wall_snscx5m2kic1hqw2", + "end": [-1.0431927931216172, 2.291329286056133], + "type": "wall", + "start": [-1.9350283421750092, 2.2911856821603345], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_a0hd9872frjzc2wr", "wall_j52mxun9aq5co4se"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_t0vbmksu3txdxi58": { + "id": "wall_t0vbmksu3txdxi58", + "end": [-1.9000000171688924, 1.1474862007346474], + "name": "Wall 71", + "type": "wall", + "start": [-1.9448822358361357, 1.1474862000631119], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_05fkpjoafiqq206e", "wall_xpzb6fvdr568w784"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_thkpqe1od6aqrxhe": { + "id": "wall_thkpqe1od6aqrxhe", + "end": [7.721551586281452, -1.316685511616987], + "type": "wall", + "start": [11.300000015017705, -1.316685231281994], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_x6u0ei0py9pfxdlz"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_d6n2c10fl9wsps2v", "wall_4nvh8ys1hlox0v6v"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_u5xwascyhkhtdf5m": { + "id": "wall_u5xwascyhkhtdf5m", + "end": [-5.578990662706296, -1.211886194285928], + "type": "wall", + "start": [-5.57484788604425, 1.1500000000042818], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["window_68pf46ke7imzyhgl"], + "metadata": { "roomPlanId": "90ED3B0B-9FC9-4EB0-B06E-3902179D3F86" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_uc138w3km1qpypgd": { + "id": "wall_uc138w3km1qpypgd", + "end": [-2.801613898394682, -1.2030842873459955], + "type": "wall", + "start": [-3.5000130168096093, -1.2052976147296652], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": { "roomPlanId": "CBFBC9A7-24E0-47A2-9E5F-77B03A2A2B08" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_ulgfa6txtf5yh69p": { + "id": "wall_ulgfa6txtf5yh69p", + "end": [-5.634038421306065, 10.25], + "name": "Wall 68", + "type": "wall", + "start": [-5.634038421306065, 9.204557989712587], + "object": "node", + "visible": true, + "backSide": "interior", + "children": [], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior" + }, + "wall_v9jvvk057lebisg5": { + "id": "wall_v9jvvk057lebisg5", + "end": [2.562588899808481, 2.350046011235656], + "type": "wall", + "start": [2.582157822264498, 6.013681255286715], + "object": "node", + "visible": true, + "backSide": "interior", + "children": ["door_wcmyciambrwcbw10"], + "metadata": { "roomPlanId": "B69237F8-6D37-4609-8AD0-DFD5DBEFE17C" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "exterior", + "thickness": 0.1 + }, + "wall_vinisg7m07bld3ov": { + "id": "wall_vinisg7m07bld3ov", + "end": [-5.5748472989710995, 4.204273690952256], + "name": "Wall 65", + "type": "wall", + "start": [-5.634038421306065, 9.204557989712587], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_ln7nj1c2n8i8ijls"], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior" + }, + "wall_w1vjmei9mmynvxlx": { + "id": "wall_w1vjmei9mmynvxlx", + "end": [0.2, 5.204557989712587], + "name": "Wall 70", + "type": "wall", + "start": [0.615961578693935, 5.204557989712588], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { "roomPlanId": "DDB42CCD-E1BD-42C1-8A1F-798AB4F8A43C" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_waukxmbz1xgpo3uz": { + "id": "wall_waukxmbz1xgpo3uz", + "end": [1.7318387751077626, -4.323741654294752], + "type": "wall", + "start": [1.7318390499398904, -1.3423386099552734], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_hmbyfsbf807qfvic"], + "metadata": { "roomPlanId": "D2F23B5B-30D2-4DF0-A176-266DAEF22541" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_whesh84hbmzk9p49": { + "id": "wall_whesh84hbmzk9p49", + "end": [1.8334994922723538, 3.133093138910797], + "type": "wall", + "start": [1.8336350037710347, 2.2917924498244733], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["door_p99j9yohdumfjpbk"], + "metadata": { "roomPlanId": "BB3D1F4E-04E0-43CE-9C4D-AFE42F03412E" }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_wq05x337zwwk7r42": { + "id": "wall_wq05x337zwwk7r42", + "end": [-2.80789750521557, 1.1474861333516475], + "type": "wall", + "start": [-5.574847374432729, 1.147486037380639], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_05fkpjoafiqq206e", "wall_xpzb6fvdr568w784"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_wqi5tg89q8zv0m9w": { + "id": "wall_wqi5tg89q8zv0m9w", + "end": [4.769958976670685, 2.351019236291708], + "type": "wall", + "start": [2.562588899808481, 2.350046011235656], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["item_526kwbg5lh2otqsn"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_9ogf15sevknvb98w", "wall_ss21locvn0hgp3kl"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_y0hxdxg4kza4gt8o": { + "id": "wall_y0hxdxg4kza4gt8o", + "end": [4.822475581078503, -0.43974861559867984], + "type": "wall", + "start": [4.822475428702728, 2.3510195411796797], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": ["item_bfe2rkz2lvbhmzge"], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_1p41tryz65xt42kv", "wall_1w06aa037thqvuqo"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "wall_z8kfjunz24xutwpx": { + "id": "wall_z8kfjunz24xutwpx", + "end": [7.763055661504598, 5.985278163001843], + "name": "Wall 69", + "type": "wall", + "start": [9.667784345207762, 5.985241013872873], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior" + }, + "wall_zu4ebpy79h7gk7r4": { + "id": "wall_zu4ebpy79h7gk7r4", + "end": [4.822475456548942, 2.351019242892958], + "type": "wall", + "start": [4.769958976670685, 2.351019236291708], + "object": "node", + "visible": true, + "backSide": "exterior", + "children": [], + "metadata": { + "source": "capture-merge", + "spawnedFrom": ["wall_9ogf15sevknvb98w", "wall_ss21locvn0hgp3kl"] + }, + "parentId": "level_49wv4wg9qwu8cdk9", + "frontSide": "interior", + "thickness": 0.1 + }, + "zone_0kzuwr4ui78ielwl": { + "id": "zone_0kzuwr4ui78ielwl", + "name": "Master Bedroom", + "type": "zone", + "color": "#22c55e", + "object": "node", + "polygon": [ + [7.7686878927486775, -1.3569634958739516], + [11.268719631136921, -1.3542782528149302], + [11.265133518016642, 3.3206733565574496], + [9.57573976436087, 3.319377341174972], + [9.574184045438464, 5.348373638164016], + [8.495949202435884, 5.347546472241667], + [8.497492906590153, 3.3350406708343963], + [7.765089128937167, 3.3344785085923254] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_3w782992d6tv00h5": { + "id": "zone_3w782992d6tv00h5", + "name": "Bathroom 2", + "type": "zone", + "color": "#64748b", + "object": "node", + "polygon": [ + [-2.8016140379985215, -0.4530841526173152], + [-2.801614190882038, 1.0304451158307564], + [-5.392407158171387, 1.0304451286887375], + [-5.39240700528787, -0.453084139759334] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_6jt3eph1iiu4hqi3": { + "id": "zone_6jt3eph1iiu4hqi3", + "name": "Bedroom 2", + "type": "zone", + "color": "#a855f7", + "object": "node", + "polygon": [ + [-1.9466727767552643, -4.327655194029761], + [-1.946672810263086, -1.211886220622606], + [-5.578990490186267, -1.2118863721198667], + [-5.578990556678436, -4.327654945527024] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_fwjqak0yxy07jgs9": { + "id": "zone_fwjqak0yxy07jgs9", + "name": "Swimming Pool", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [[12.75, -10], [12.75, -4.5], [2.25, -4.500000000000001], [2.2500000000000004, -10]], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_h4qclonp6vouqlqm": { + "id": "zone_h4qclonp6vouqlqm", + "name": "Living Room", + "type": "zone", + "color": "#f97316", + "object": "node", + "polygon": [ + [2.3804312113178847, 2.3510191094735307], + [4.822475421882922, 2.351019432399015], + [4.822475671597212, -1.3824471185683471], + [7.721551752267856, -1.3824467290333047], + [7.721551667204937, 6.014653772892679], + [2.380431165940307, 6.014654328427357] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_kvc4i5vnlk4d08yf": { + "id": "zone_kvc4i5vnlk4d08yf", + "name": "Bathroom", + "type": "zone", + "color": "#64748b", + "object": "node", + "polygon": [ + [9.667784381795945, 5.985240833463578], + [9.667784552703587, 3.3576415343044177], + [11.190862944581028, 3.3576416361417105], + [11.190862873673385, 5.985240935300877] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_mmzxkt8um9no5cll": { + "id": "zone_mmzxkt8um9no5cll", + "name": "Entrance", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [1.8336350556170218, 2.291792303178883], + [1.8334996499439085, 3.13309302842723], + [2.548991670066572, 3.133208215221589], + [2.548657948536108, 5.204869347438328], + [0.6159615741475906, 5.204557984790318], + [0.6161330341174658, 4.140102022824073], + [-1.0434903525719479, 4.139834749159698], + [-1.0431925252840353, 2.2913292136367565], + [0.6140375513313971, 2.291596057700538] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_pay55xzusiol0e2v": { + "id": "zone_pay55xzusiol0e2v", + "name": "Garage", + "type": "zone", + "color": "#10b981", + "object": "node", + "polygon": [[-5.5, 10.25], [-5.5, 4.25], [0.75, 4.25], [0.7500000000000003, 10.25]], + "visible": true, + "metadata": {}, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_s8w1h8ts08zbm0b1": { + "id": "zone_s8w1h8ts08zbm0b1", + "name": "Kitchen / Office", + "type": "zone", + "color": "#ef4444", + "object": "node", + "polygon": [ + [-1.9350279515296496, 2.287666572716621], + [-1.9350281705311942, -4.381449889032432], + [1.7318390044139351, -4.3814499610074895], + [1.7318391543420888, -1.342338648438425], + [4.800937538262154, -1.3423390071707155], + [4.769960447800703, 2.2876665268412326] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_w96chgxaqu67c23c": { + "id": "zone_w96chgxaqu67c23c", + "name": "Bedroom 3", + "type": "zone", + "color": "#cccccc", + "object": "node", + "polygon": [ + [-1.9448822108135841, 1.1474862023505743], + [-1.9448822046431806, 4.204273508648356], + [-5.574847604747045, 4.204273685960075], + [-5.574847610917358, 1.1474859796622927] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_z5f9lvn4m7h5jtrk": { + "id": "zone_z5f9lvn4m7h5jtrk", + "name": "Lanai", + "type": "zone", + "color": "#6366f1", + "object": "node", + "polygon": [ + [3.1318685080276216, -4.3412497001265], + [12.761660140939227, -4.341249843669339], + [12.761659840966196, -1.316684974588203], + [3.131868208054532, -1.3166857310453555], + [1.7091916179659687, -1.316685750743963], + [1.7091914179390475, -4.341249919825078] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + }, + "zone_zmv4bjoua1ahtpdn": { + "id": "zone_zmv4bjoua1ahtpdn", + "name": "Hallway", + "type": "zone", + "color": "#3b82f6", + "object": "node", + "polygon": [ + [-1.905936748308022, 1.0880206371966983], + [-2.807897388308025, 1.0880207074428472], + [-2.8078975539952444, -1.1647028925571594], + [-1.905936813995245, -1.164702862803305] + ], + "visible": true, + "metadata": { "source": "roomplan-capture" }, + "parentId": "level_49wv4wg9qwu8cdk9" + } +} diff --git a/packages/core/src/utils/clone-scene-graph-fork.test.ts b/packages/core/src/utils/clone-scene-graph-fork.test.ts new file mode 100644 index 0000000000..7085e35015 --- /dev/null +++ b/packages/core/src/utils/clone-scene-graph-fork.test.ts @@ -0,0 +1,259 @@ +import { afterEach, expect, test } from 'bun:test' +import { mezzanineFixture } from '../lib/__fixtures__/mezzanine' +import { reconcileSceneStructure } from '../lib/structure-reconcile' +import { + type AnyNode, + BuildingNode, + LevelNode, + SiteNode, + StairNode, + StairSegmentNode, + WallNode, +} from '../schema' +import type { AnyNodeId } from '../schema/types' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { forkSceneGraph } from './clone-scene-graph' + +const previous = useScene.getState() +afterEach(() => { + useScene.setState(previous, true) + clearSceneHistory() +}) + +function load(nodes: Record, rootNodeIds: string[]) { + clearSceneHistory() + useScene.getState().setScene(structuredClone(nodes) as never, rootNodeIds as never) + return JSON.parse(JSON.stringify(useScene.getState().nodes)) as Record +} + +/** + * A two-storey building as the editor saves it: a mezzanine room on the ground + * floor, a room upstairs, and a stair between them that cuts its opening + * through the upper floor. + */ +function savedScene() { + const { nodes: ground } = mezzanineFixture() + let serial = 0 + const mintId = (kind: string) => `${kind}_fork${++serial}` + const ring: [number, number][] = [ + [0, 0], + [8, 0], + [8, 6], + [0, 6], + ] + const upper = LevelNode.parse({ id: 'level_upper', level: 1, height: 3 }) + const walls = ring.map((start, i) => + WallNode.parse({ + id: mintId('wall'), + parentId: upper.id, + start, + end: ring[(i + 1) % 4], + thickness: 0.2, + }), + ) + upper.children = walls.map((wall) => wall.id) + const stair = StairNode.parse({ + id: 'stair_fork', + parentId: 'level_mezz', + fromLevelId: 'level_mezz', + toLevelId: upper.id, + slabOpeningMode: 'destination', + position: [6, 0, 3], + }) + const segment = StairSegmentNode.parse({ + id: 'sseg_fork', + parentId: stair.id, + height: 5, + length: 4, + width: 1, + }) + stair.children = [segment.id] + const site = SiteNode.parse({ id: 'site_fork', children: ['building_fork'] }) + const building = BuildingNode.parse({ + id: 'building_fork', + parentId: site.id, + children: ['level_mezz', upper.id], + }) + const level = ground.level_mezz as LevelNode + const nodes: Record = { + ...ground, + level_mezz: { ...level, parentId: building.id, children: [...level.children, stair.id] }, + [site.id]: site, + [building.id]: building, + [upper.id]: upper, + [stair.id]: stair, + [segment.id]: segment, + } + for (const wall of walls) nodes[wall.id] = wall + const reconciled = reconcileSceneStructure({ nodes, mintId }).nodes + // What autosave stores after the first open. + return { nodes: load(reconciled, [site.id]), rootNodeIds: [site.id] } +} + +/** Every string value and object key anywhere in a node, except its own id. */ +function references(node: AnyNode): string[] { + const out: string[] = [] + const walk = (value: unknown) => { + if (typeof value === 'string') out.push(value) + else if (Array.isArray(value)) for (const entry of value) walk(entry) + else if (value && typeof value === 'object') + for (const [key, entry] of Object.entries(value)) { + out.push(key) + walk(entry) + } + } + for (const [key, value] of Object.entries(node)) if (key !== 'id') walk(value) + return out +} + +test('a forked scene keeps no reference to the source ids and opens as a no-op', () => { + const saved = savedScene() + // The fixture carries the references a fork has to rewrite. + const kinds = Object.values(saved.nodes) + expect( + kinds.some( + (node) => + (node.type === 'slab' || node.type === 'ceiling') && + node.holeMetadata?.some((entry) => entry.source === 'stair' || entry.openingId), + ) || kinds.some((node) => node.type === 'floor-opening' && node.ownerId === 'stair_fork'), + ).toBe(true) + expect(kinds.some((node) => node.type === 'zone' && node.hostZoneId)).toBe(true) + expect(kinds.some((node) => node.type === 'zone' && node.boundaryWallIds?.length)).toBe(true) + // The saved scene is canonical: opening it again changes nothing. + expect(load(saved.nodes, saved.rootNodeIds)).toEqual(saved.nodes) + + const fork = forkSceneGraph({ + nodes: saved.nodes as Record, + rootNodeIds: saved.rootNodeIds as AnyNodeId[], + }) + const sourceIds = new Set(Object.keys(saved.nodes)) + const leaked = Object.values(fork.nodes).flatMap((node) => + references(node) + .filter((value) => sourceIds.has(value)) + .map((value) => `${node.type}: ${value}`), + ) + expect(leaked).toEqual([]) + expect(Object.keys(fork.nodes).length).toBe(sourceIds.size) + + // First open of the fork: reconcile has nothing to write. + expect(load(fork.nodes, fork.rootNodeIds)).toEqual( + JSON.parse(JSON.stringify(fork.nodes)) as Record, + ) +}) + +/** Slab and ceiling cuts and floor openings, without ids: what a viewer sees. */ +function openingShapes(nodes: Record) { + const round = (value: unknown): unknown => + typeof value === 'number' + ? Math.round(value * 1e4) / 1e4 + : Array.isArray(value) + ? value.map(round) + : value + const shapes: string[] = [] + for (const node of Object.values(nodes)) { + if (node.type === 'slab' || node.type === 'ceiling') + shapes.push( + JSON.stringify([ + node.type, + round(node.polygon), + round(node.holes ?? []), + (node.holeMetadata ?? []).map((m) => m.source), + ]), + ) + if (node.type === 'floor-opening') + shapes.push(JSON.stringify([node.type, round(node.polygon), node.source])) + } + return shapes.sort() +} + +test('a fork of a legacy scene with a stair cut opens with the same cuts as its source', () => { + // As production stores it: no level heights, and the stair's cut kept as + // slab and ceiling holes tagged with the stair id. + const node = ( + id: string, + type: string, + parentId: string | null, + extra: Record = {}, + ) => ({ + object: 'node', + id, + type, + parentId, + visible: true, + metadata: {}, + ...extra, + }) + const outline = [ + [0, 0], + [8, 0], + [8, 6], + [0, 6], + ] + // Wider than the stair's own footprint, as saved cuts often are. + const cut = [ + [4.5, 1.5], + [7.5, 1.5], + [7.5, 5.5], + [4.5, 5.5], + ] + const nodes: Record> = { + site_legacy: node('site_legacy', 'site', null, { children: ['building_legacy'] }), + building_legacy: node('building_legacy', 'building', 'site_legacy', { + children: ['level_legacy0', 'level_legacy1'], + }), + level_legacy0: node('level_legacy0', 'level', 'building_legacy', { + level: 0, + children: ['slab_legacy0', 'ceiling_legacy0', 'stair_legacy'], + }), + level_legacy1: node('level_legacy1', 'level', 'building_legacy', { + level: 1, + children: ['slab_legacy1'], + }), + slab_legacy0: node('slab_legacy0', 'slab', 'level_legacy0', { + polygon: outline, + elevation: 0.05, + }), + slab_legacy1: node('slab_legacy1', 'slab', 'level_legacy1', { + polygon: outline, + elevation: 0.05, + holes: [cut], + holeMetadata: [{ source: 'stair', stairId: 'stair_legacy' }], + }), + ceiling_legacy0: node('ceiling_legacy0', 'ceiling', 'level_legacy0', { + polygon: outline, + height: 2.5, + holes: [cut], + holeMetadata: [{ source: 'stair', stairId: 'stair_legacy' }], + }), + stair_legacy: node('stair_legacy', 'stair', 'level_legacy0', { + position: [6, 0, 2], + rotation: 0, + fromLevelId: 'level_legacy0', + toLevelId: 'level_legacy1', + slabOpeningMode: 'destination', + children: ['sseg_legacy'], + }), + sseg_legacy: node('sseg_legacy', 'stair-segment', 'stair_legacy', { + width: 2, + length: 3, + height: 2.5, + stepCount: 14, + segmentType: 'stair', + attachmentSide: 'front', + position: [0, 0, 0], + rotation: 0, + }), + } + const source = load(nodes, ['site_legacy']) + const fork = forkSceneGraph({ + nodes: nodes as unknown as Record, + rootNodeIds: ['site_legacy' as AnyNodeId], + }) + const forkStair = Object.values(fork.nodes).find((n) => n.type === 'stair')! + const forkSlab = Object.values(fork.nodes).find((n) => n.type === 'slab' && n.holes?.length)! + expect(forkSlab.type === 'slab' && forkSlab.holeMetadata?.[0]).toEqual({ + source: 'stair', + stairId: forkStair.id, + }) + expect(openingShapes(load(fork.nodes, fork.rootNodeIds))).toEqual(openingShapes(source)) +}) diff --git a/packages/core/src/utils/clone-scene-graph.ts b/packages/core/src/utils/clone-scene-graph.ts index 56b787ca28..3b45e5eeb2 100644 --- a/packages/core/src/utils/clone-scene-graph.ts +++ b/packages/core/src/utils/clone-scene-graph.ts @@ -1,4 +1,6 @@ import { GROUND_SUPPORT_ID } from '../hooks/spatial-grid/floor-placed-elevation' +import { floorFootprintCreatorId, mintFloorFootprintKey } from '../lib/floor-footprint-key' +import { keyedFloorPlateId } from '../lib/floor-plate-id' import { remapConstructionDimensionReferences, remapMeasurementReferences, @@ -24,6 +26,112 @@ function extractIdPrefix(id: string): string { return underscoreIndex === -1 ? 'node' : id.slice(0, underscoreIndex) } +function remapFloorOpeningReferences(node: AnyNode, ids: Map) { + if ('hostZoneId' in node && typeof node.hostZoneId === 'string') + node.hostZoneId = ids.get(node.hostZoneId) ?? node.hostZoneId + if (node.type === 'floor-opening') { + if (node.ownerId) { + node.ownerId = ids.get(node.ownerId) + if (!node.ownerId && node.source === 'plugin:pool') node.source = 'manual' + } + if (node.legacyPlateCuts) + node.legacyPlateCuts = Object.fromEntries( + Object.entries(node.legacyPlateCuts).flatMap(([id, cuts]) => + ids.has(id) ? [[ids.get(id)!, cuts]] : [], + ), + ) + } + if ((node.type === 'slab' || node.type === 'ceiling') && node.holeMetadata) + node.holeMetadata = node.holeMetadata.map((entry) => + entry.openingId && ids.has(entry.openingId) + ? { ...entry, openingId: ids.get(entry.openingId) } + : entry, + ) +} + +/** + * Rewrites every other node reference: node ids live in many fields that are + * data rather than schema (hole metadata stair ids, stair level ids, room + * boundaries and plates, plugin and metadata links, id-keyed maps), so a whole + * graph clone swaps any string or key that is exactly a cloned node id. + */ +function remapNodeIdStrings(value: unknown, ids: Map): unknown { + if (typeof value === 'string') return ids.get(value) ?? value + if (Array.isArray(value)) return value.map((entry) => remapNodeIdStrings(entry, ids)) + if (value && typeof value === 'object') + return Object.fromEntries( + Object.entries(value).map(([key, entry]) => [ + ids.get(key) ?? key, + remapNodeIdStrings(entry, ids), + ]), + ) + return value +} + +// Id lists the structure kernel stores sorted; a remap must keep them sorted +// or the first load re-sorts them and the clone saves a change. +const SORTED_ID_LISTS = ['boundaryWallIds', 'boundarySeparatorIds', 'zoneIds', 'openingIds'] + +function remapNodeReferences(node: AnyNode, ids: Map): AnyNode { + // Provenance source ids are history, not links: clones carry them verbatim (D5). + const { provenance, ...links } = node as AnyNode & { provenance?: unknown } + const remapped = remapNodeIdStrings(links, ids) as Record + if (provenance !== undefined) remapped.provenance = provenance + for (const key of SORTED_ID_LISTS) { + const before = (node as Record)[key] + const after = remapped[key] + if ( + Array.isArray(before) && + Array.isArray(after) && + before.every((id, i) => i === 0 || String(before[i - 1]) <= String(id)) + ) + remapped[key] = [...after].sort() + } + return remapped as AnyNode +} + +function copiedFloorKeys(nodes: Record, ids: Map) { + const keys = new Map() + const identity = (level: string, key: string) => JSON.stringify([level, key]) + for (const node of Object.values(nodes)) { + if (node.type !== 'zone' || !node.floor?.footprint || !node.parentId || !ids.has(node.parentId)) + continue + const old = identity(node.parentId, node.floor.footprint) + if (!keys.has(old)) { + const creatorId = floorFootprintCreatorId(node.floor.footprint) + keys.set(old, mintFloorFootprintKey(creatorId ? ids.get(creatorId) : undefined)) + } + } + const plates = Object.values(nodes).filter( + (node) => node.type === 'slab' && node.plateRole === 'base', + ) + for (const plate of plates) { + if (plate.type !== 'slab' || !plate.parentId || !ids.has(plate.id)) continue + const room = (plate.zoneIds ?? []) + .map((id) => nodes[id as AnyNodeId]) + .find((node) => node?.type === 'zone' && node.floor?.footprint) + if (room?.type !== 'zone' || !room.floor?.footprint) continue + const key = keys.get(identity(plate.parentId, room.floor.footprint)) + if (!key) continue + for (let component = 0; component <= plates.length; component++) { + if (plate.id !== keyedFloorPlateId(plate.parentId, room.floor.footprint, component)) continue + ids.set(plate.id, keyedFloorPlateId(ids.get(plate.parentId)!, key, component)) + break + } + } + return (source: AnyNode, copy: AnyNode) => { + if ( + source.type !== 'zone' || + copy.type !== 'zone' || + !source.parentId || + !source.floor?.footprint + ) + return + const key = keys.get(identity(source.parentId, source.floor.footprint)) + if (key) copy.floor = { ...copy.floor, footprint: key } + } +} + /** * Deep clones a scene graph with all node IDs regenerated while preserving * parent-child relationships and other internal references. @@ -50,6 +158,8 @@ export function cloneSceneGraph(sceneGraph: SceneGraph): SceneGraph { idMap.set(nodeId, generateId(prefix)) } + const copyFloor = copiedFloorKeys(nodes, idMap) + // Pass 2: Deep clone nodes with remapped references const clonedNodes = {} as Record @@ -137,6 +247,7 @@ export function cloneSceneGraph(sceneGraph: SceneGraph): SceneGraph { | string | undefined } + remapFloorOpeningReferences(clonedNode, idMap) if (clonedNode.type === 'measurement') { clonedNode.measurement = remapMeasurementReferences(clonedNode.measurement, idMap) @@ -144,7 +255,8 @@ export function cloneSceneGraph(sceneGraph: SceneGraph): SceneGraph { if (clonedNode.type === 'construction-dimension') { clonedNode = remapConstructionDimensionReferences(clonedNode, idMap) } - clonedNodes[newId] = clonedNode + copyFloor(node, clonedNode) + clonedNodes[newId] = remapNodeReferences(clonedNode, idMap) } // Remap root node IDs @@ -249,6 +361,7 @@ export function cloneLevelSubtree( idMap.set(oldId, generateId(prefix)) } + const copyFloor = copiedFloorKeys(nodes, idMap) const newLevelId = idMap.get(levelId)! as AnyNodeId // Clone each node with remapped references. @@ -327,6 +440,7 @@ export function cloneLevelSubtree( ;(cloned as Record).deckSlabId = idMap.get(cloned.deckSlabId) ?? cloned.deckSlabId } + remapFloorOpeningReferences(cloned, idMap) if (cloned.type === 'measurement') { cloned.measurement = remapMeasurementReferences(cloned.measurement, idMap) @@ -334,6 +448,7 @@ export function cloneLevelSubtree( if (cloned.type === 'construction-dimension') { cloned = remapConstructionDimensionReferences(cloned, idMap) } + copyFloor(node, cloned) clonedNodes.push(cloned) } diff --git a/packages/core/src/utils/ensure-scene-openings.test.ts b/packages/core/src/utils/ensure-scene-openings.test.ts new file mode 100644 index 0000000000..2a5c3b61f8 --- /dev/null +++ b/packages/core/src/utils/ensure-scene-openings.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from 'bun:test' +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import * as Bun from 'bun' + +test('scene migrations import in Node without stores, React, Three.js or Zustand', async () => { + const cache = join(import.meta.dir, '.turbo') + mkdirSync(cache, { recursive: true }) + const directory = mkdtempSync(join(cache, 'opening-import-')) + try { + const bundle = join(directory, 'scene-migrations.mjs') + const build = Bun.spawnSync([ + 'bun', + 'build', + join(import.meta.dir, 'scene-migrations.ts'), + '--target=node', + '--packages=external', + `--outfile=${bundle}`, + ]) + expect({ code: build.exitCode, error: build.stderr.toString() }).toEqual({ code: 0, error: '' }) + expect(readFileSync(bundle, 'utf8')).not.toMatch( + /from ["'](?:@react-three\/[^"']+|react(?:-dom)?|three|zustand)["']/, + ) + const probe = Bun.spawnSync( + [ + 'node', + '--input-type=module', + '-e', + ` + const { ensureSceneOpenings, reconcileStructureOnLoad } = await import(process.argv[1]); + const nodes = {}; + if (ensureSceneOpenings(nodes).nodes !== nodes) throw new Error('No-op identity changed'); + if (reconcileStructureOnLoad(nodes).nodes !== nodes) throw new Error('Structure no-op identity changed'); + `, + pathToFileURL(bundle).href, + ], + { stdout: 'pipe', stderr: 'pipe' }, + ) + expect({ code: probe.exitCode, error: probe.stderr.toString() }).toEqual({ code: 0, error: '' }) + } finally { + rmSync(directory, { recursive: true, force: true }) + } +}) + +test('opening repair settles another stair support change in one pure idempotent pass', async () => { + const { BuildingNode, LevelNode, SlabNode, StairNode, StairSegmentNode } = await import( + '../schema' + ) + const { ensureSceneOpenings, reconcileStructureOnLoad } = await import('./scene-migrations') + const building = BuildingNode.parse({}) + const levels = [0, 1, 2].map((level) => + LevelNode.parse({ parentId: building.id, level, height: 3 }), + ) + const polygon: [number, number][] = [ + [-5, -5], + [5, -5], + [5, 10], + [-5, 10], + ] + const slabs = levels + .slice(1) + .map((level) => SlabNode.parse({ parentId: level.id, elevation: 0.4, polygon })) + const stairs = levels.slice(0, 2).map((level, i) => + StairNode.parse({ + parentId: level.id, + fromLevelId: level.id, + toLevelId: levels[i + 1]!.id, + slabOpeningMode: 'destination', + position: [0, 0, 0], + }), + ) + const segments = stairs.map((stair) => + StairSegmentNode.parse({ parentId: stair.id, height: 1, length: 4, width: 1 }), + ) + building.children = levels.map((level) => level.id) + for (const [i, level] of levels.entries()) { + level.children = [ + ...(stairs[i] ? [stairs[i]!.id] : []), + ...(slabs[i - 1] ? [slabs[i - 1]!.id] : []), + ] + } + for (const [i, stair] of stairs.entries()) stair.children = [segments[i]!.id] + const nodes = Object.fromEntries( + [building, ...levels, ...slabs, ...stairs, ...segments].map((node) => [node.id, node]), + ) + const bytes = JSON.stringify(nodes) + const first = reconcileStructureOnLoad(nodes) + expect(JSON.stringify(nodes)).toBe(bytes) + expect((first.nodes[segments[1]!.id] as (typeof segments)[number]).height).toBeCloseTo(3) + expect(first.changed).toBe(true) + const second = reconcileStructureOnLoad(first.nodes) + expect(second.nodes).toBe(first.nodes) + expect(second.changed).toBe(false) + expect(ensureSceneOpenings(second.nodes).updates).toEqual([]) +}) diff --git a/packages/core/src/utils/ensure-scene-openings.ts b/packages/core/src/utils/ensure-scene-openings.ts new file mode 100644 index 0000000000..608eaaae86 --- /dev/null +++ b/packages/core/src/utils/ensure-scene-openings.ts @@ -0,0 +1,29 @@ +import type { AnyNode, AnyNodeId } from '../schema' +import { syncStairRises } from '../systems/stair/stair-rise-query' + +export function ensureSceneOpenings(sourceNodes: Record) { + let nodes = sourceNodes as Record + const patches = new Map>() + const kinds = new Set(Object.values(nodes).map((node) => node.type)) + const steps = kinds.has('stair') ? [syncStairRises] : [] + let pending = true + while (pending) { + pending = false + for (const derive of steps) { + const updates = derive(nodes) + if (!updates.length) continue + pending = true + nodes = { ...nodes } + for (const { id, data } of updates) { + nodes[id] = { ...nodes[id], ...data } as AnyNode + patches.set(id, { ...patches.get(id), ...data } as Partial) + } + } + } + + return { + nodes, + changed: nodes !== sourceNodes, + updates: [...patches].map(([id, data]) => ({ id, data })), + } +} diff --git a/packages/core/src/utils/exterior-threshold-migration.test.ts b/packages/core/src/utils/exterior-threshold-migration.test.ts new file mode 100644 index 0000000000..66e3fe0bef --- /dev/null +++ b/packages/core/src/utils/exterior-threshold-migration.test.ts @@ -0,0 +1,206 @@ +import { describe, expect, test } from 'bun:test' +import { + computePlateSurfacePartition, + plateLevelContext, + plateOpeningLandings, +} from '../lib/plate-surface' +import { area, containsPoint, intersection, union } from '../lib/polygon-boolean' +import { roomFloorPlate } from '../lib/room-floor-plate' +import { type AnyNode, DoorNode, type SlabNode, type ZoneNode } from '../schema' +import useScene from '../store/use-scene' +import { doorwayStepsFixture } from '../systems/slab/__fixtures__/doorway-steps' +import { migrateExteriorThresholds } from './exterior-threshold-migration' +import { normalizeLegacyStructure } from './normalize-legacy-structure' +import { reconcileStructureWithStableIds } from './structure-id' + +const WOOD = 'library:wood-woodplank48' +const TILE = 'library:flooring-tiles3' +const RED = 'library:paint-red' + +function fixture( + kind: 'door' | 'opening' = 'door', + elevations: [number, number, number] = [0.05, 0.05, 0.05], +) { + const nodes = doorwayStepsFixture(elevations) + const wall = nodes.wall_row_0! + const door = DoorNode.parse({ + parentId: wall.id, + openingKind: kind, + width: 1, + height: 2, + position: [2, 1, 0], + }) + nodes[wall.id] = { ...wall, children: [door.id] } as AnyNode + nodes[door.id] = door + nodes.zone_a = { + ...nodes.zone_a, + floor: { ...(nodes.zone_a as ZoneNode).floor, finish: TILE }, + } as ZoneNode + const plate = roomFloorPlate( + Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab'), + 'zone_a', + )! + nodes[plate.id] = { ...plate, slots: { surface: WOOD } } + return { nodes, door, plate } +} +function context(nodes: Record) { + return plateLevelContext(nodes.level_row!, (id) => nodes[id]) +} +function cellAt(nodes: Record, point: [number, number]) { + return context(nodes) + .slabs.flatMap((plate) => computePlateSurfacePartition(plate, context(nodes))?.cells ?? []) + .find((cell) => containsPoint(cell.polygons, point))! +} +function legacy(nodes: Record) { + return Object.fromEntries( + Object.entries(nodes).map(([id, node]) => { + if (node.type !== 'door' && node.type !== 'window') return [id, node] + const { floorThresholdVersion: _version, ...old } = node + return [id, old] + }), + ) +} + +describe('exterior threshold ownership and load parity', () => { + test('client parsing retains legacy provenance and reload preserves the migrated paint', () => { + const { nodes, door } = fixture() + const saved = legacy(nodes) + const normalized = normalizeLegacyStructure(saved) + expect(DoorNode.parse(normalized[door.id]).floorThresholdVersion).toBe(0) + const previous = useScene.getState() + try { + useScene.getState().setScene(saved as Record, ['level_row']) + const loaded = useScene.getState().nodes + expect(cellAt(loaded, [2, -0.05]).finish).toBe(WOOD) + expect(cellAt(loaded, [2, -0.05]).role).toStartWith('room:zone_a/threshold:') + useScene.getState().setScene(JSON.parse(JSON.stringify(loaded)), ['level_row']) + expect((useScene.getState().nodes.zone_a as ZoneNode).floor).toEqual( + (loaded.zone_a as ZoneNode).floor, + ) + } finally { + useScene.setState(previous) + useScene.temporal.getState().clear() + } + }) + test('raw pre-plate scenes preserve the original slab finish, not a merged plate fallback', () => { + const { nodes, plate } = fixture() + const saved = legacy(nodes) + const { plateRole: _role, ...oldSlab } = plate + saved[plate.id] = { ...oldSlab, slots: { surface: RED } } + const migrated = migrateExteriorThresholds(nodes, saved) + expect(cellAt(migrated, [2, -0.05]).finish).toBe(RED) + expect(cellAt(migrated, [2, 1]).finish).toBe(TILE) + }) + test.each([ + 'door', + 'opening', + ] as const)('%s belongs to the sole room across the full wall thickness', (kind) => { + const { nodes } = fixture(kind) + for (const z of [-0.09, 0, 0.09]) { + expect(cellAt(nodes, [2, z]).role).toBe('room:zone_a') + expect(cellAt(nodes, [2, z]).finish).toBe(TILE) + } + expect(cellAt(nodes, [3, 0]).role).toBe('surface') + }) + test('painted regions extend through the strip and later regions win', () => { + const { nodes } = fixture() + const zone = nodes.zone_a as ZoneNode + nodes.zone_a = { + ...zone, + floor: { + ...zone.floor, + regions: [ + { + id: 'paint', + finish: RED, + polygon: [ + [1.5, -0.1], + [2, -0.1], + [2, 1], + [1.5, 1], + ], + }, + ], + }, + } + expect(cellAt(nodes, [1.75, -0.05]).role).toBe('room:zone_a/paint') + expect(cellAt(nodes, [1.75, -0.05]).finish).toBe(RED) + expect(cellAt(nodes, [2.25, -0.05]).finish).toBe(TILE) + }) + test('interior equal-height ownership and higher-room step ownership are unchanged', () => { + for (const elevations of [ + [0.05, 0.05, 0.05], + [0.05, 0.3, 0.05], + [0.05, -0.3, 0.05], + [0.3, 0.05, 0.05], + [-0.3, 0.05, 0.05], + ] as [number, number, number][]) { + const before = doorwayStepsFixture(elevations) + const { nodes, door } = fixture('door', elevations) + const interior = (ns: Record) => + plateOpeningLandings(context(ns)).filter((l) => l.openingId !== door.id) + expect(interior(nodes)).toEqual(interior(before)) + const reconciled = reconcileStructureWithStableIds({ nodes }).nodes + for (const plate of Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab')) { + const after = reconciled[plate.id] as SlabNode + expect(after.polygon).toEqual(plate.polygon) + expect(after.elevation).toBe(plate.elevation) + } + } + }) + test('legacy finish becomes an exact room region, survives reload and is repaintable', () => { + const { nodes, door } = fixture() + const saved = JSON.stringify(nodes) + const migrated = migrateExteriorThresholds(nodes, legacy(nodes)) + expect(JSON.stringify(nodes)).toBe(saved) + const cell = cellAt(migrated, [2, -0.05]) + expect(cell.role).toStartWith('room:zone_a/threshold:') + expect(cell.finish).toBe(WOOD) + expect(cellAt(migrated, [2, 1]).finish).toBe(TILE) + const zone = migrated.zone_a as ZoneNode + const landing = plateOpeningLandings(context(nodes)).find((l) => l.openingId === door.id)! + expect(area(union(zone.floor!.regions!.map((r) => r.polygon)))).toBeCloseTo( + area(landing.polygons), + 6, + ) + expect(migrateExteriorThresholds(migrated)).toBe(migrated) + const repainted = { + ...migrated, + zone_a: { + ...zone, + floor: { ...zone.floor, regions: zone.floor!.regions!.map((r) => ({ ...r, finish: RED })) }, + }, + } + expect(cellAt(migrateExteriorThresholds(repainted), [2, -0.05]).finish).toBe(RED) + const cleared = { ...migrated, zone_a: { ...zone, floor: { finish: TILE } } } + expect(cellAt(migrateExteriorThresholds(cleared), [2, -0.05]).finish).toBe(TILE) + }) + test('new openings never acquire legacy regions, including on first reload', () => { + const { nodes } = fixture() + expect(migrateExteriorThresholds(nodes)).toBe(nodes) + expect(cellAt(nodes, [2, -0.05]).finish).toBe(TILE) + }) + test('matching finishes need no region and plate holes remain unpainted', () => { + const { nodes, plate } = fixture() + nodes[plate.id] = { ...plate, slots: { surface: TILE } } + expect( + (migrateExteriorThresholds(nodes, legacy(nodes)).zone_a as ZoneNode).floor?.regions, + ).toBeUndefined() + const hole: [number, number][] = [ + [1.8, -0.05], + [2.2, -0.05], + [2.2, 0.05], + [1.8, 0.05], + ] + nodes[plate.id] = { ...plate, slots: { surface: WOOD }, holes: [hole] } + const migrated = migrateExteriorThresholds(nodes, legacy(nodes)) + const regions = (migrated.zone_a as ZoneNode).floor!.regions! + expect(area(intersection(union(regions.map((r) => r.polygon)), hole))).toBe(0) + expect(area(union(regions.map((r) => r.polygon)))).toBeCloseTo(0.16, 5) + }) + test('wall-anchored raised openings do not claim a floor strip', () => { + const { nodes, door } = fixture() + nodes[door.id] = { ...door, verticalAnchor: 'wall', position: [2, 2, 0] } + expect(cellAt(nodes, [2, 0]).role).toBe('surface') + }) +}) diff --git a/packages/core/src/utils/exterior-threshold-migration.ts b/packages/core/src/utils/exterior-threshold-migration.ts new file mode 100644 index 0000000000..8d69780e1e --- /dev/null +++ b/packages/core/src/utils/exterior-threshold-migration.ts @@ -0,0 +1,139 @@ +import { parseSlabConstruction } from '../lib/floor-plates' +import { + computePlateSurfacePartition, + parseRoomFinishRole, + plateFinishKey, + plateLevelContext, + plateOpeningLandings, +} from '../lib/plate-surface' +import { + area, + difference, + intersection, + type MultiPolygon, + type Polygon, + type Ring, +} from '../lib/polygon-boolean' +import { getRenderableSlabPolygon, prepareSlabPolygonContext } from '../lib/slab-polygon' +import type { AnyNode, DoorNode, SlabNode, WallNode, WindowNode, ZoneNode } from '../schema' + +function slabFinish(slab: SlabNode) { + return slab.slots?.surface ?? slab.material ?? slab.materialPreset ?? 'library:wood-woodplank48' +} + +function legacySurfaces(legacy: Record, levelId: string) { + const children = Object.values(legacy).filter( + (node) => (node as AnyNode).parentId === levelId, + ) as AnyNode[] + const slabs = children.filter((node): node is SlabNode => node.type === 'slab') + if (slabs.some((slab) => slab.plateRole)) return [] + const context = prepareSlabPolygonContext({ + walls: children.filter((node): node is WallNode => node.type === 'wall'), + siblingSlabs: slabs, + }) + return slabs + .filter((slab) => slab.visible !== false && !slab.recessed) + .map(parseSlabConstruction) + .sort((a, b) => b.elevation - a.elevation || a.id.localeCompare(b.id)) + .map((slab) => ({ + elevation: slab.elevation, + polygons: { outer: getRenderableSlabPolygon(slab, context), holes: slab.holes }, + finish: slabFinish(slab), + })) +} + +function regionRings(polygon: Polygon): Ring[] { + if (!polygon.holes.length) return [polygon.outer] + const xs = [...new Set([...polygon.outer, ...polygon.holes.flat()].map(([x]) => x))].sort( + (a, b) => a - b, + ) + const zs = polygon.outer.map(([, z]) => z) + const minZ = Math.min(...zs), + maxZ = Math.max(...zs) + return xs.slice(1).flatMap((x, i) => + intersection(polygon, [ + [xs[i]!, minZ], + [x, minZ], + [x, maxZ], + [xs[i]!, maxZ], + ]).map((part) => part.outer), + ) +} + +/** Preserve the formerly plate-owned finish as ordinary, editable room paint. */ +export function migrateExteriorThresholds( + source: Record, + legacy: Record = source, +): Record { + const pending = new Set( + Object.values(source) + .filter( + (node) => + (node.type === 'door' || node.type === 'window') && + (legacy[node.id] as DoorNode | WindowNode | undefined)?.floorThresholdVersion !== 1, + ) + .map((node) => node.id as string), + ) + if (!pending.size) return source + const nodes = { ...source } + for (const level of Object.values(source)) { + if (level.type !== 'level') continue + const context = plateLevelContext(level, (id) => source[id]) + if (!context.openings?.some((opening) => pending.has(opening.id))) continue + const landings = plateOpeningLandings(context).filter( + (landing) => landing.exterior && pending.has(landing.openingId), + ) + if (!landings.length) continue + const original = legacySurfaces(legacy, level.id) + for (const plate of context.slabs) { + if (plate.visible === false) continue + const partition = computePlateSurfacePartition(plate, context) + if (!partition) continue + const fallback = slabFinish(plate) + for (const landing of landings) { + let index = 0 + for (const cell of partition.cells) { + if (parseRoomFinishRole(cell.role)?.zoneId !== landing.zoneId) continue + let remaining = intersection(cell.polygons, landing.polygons) + if (area(remaining) < 1e-6) continue + const preserved: Array<{ + polygons: MultiPolygon + finish: ReturnType + }> = [] + // Raw pre-plate scenes still have their original slabs. Reading only + // the merged plate would preserve an earlier migration's lost finish. + for (const surface of original) { + if (Math.abs(surface.elevation - plate.elevation) > 0.02 + 1e-9) continue + const polygons = intersection(remaining, surface.polygons) + if (area(polygons) < 1e-6) continue + preserved.push({ polygons, finish: surface.finish }) + remaining = difference(remaining, polygons) + } + if (area(remaining) >= 1e-6) preserved.push({ polygons: remaining, finish: fallback }) + const regions = preserved.flatMap(({ polygons, finish }) => + plateFinishKey(cell.finish ?? fallback) === plateFinishKey(finish) + ? [] + : polygons.flatMap(regionRings).map((polygon) => ({ + id: `threshold:${landing.openingId}:${plate.id}:${index++}`, + polygon, + finish, + })), + ) + if (!regions.length) continue + const zone = nodes[landing.zoneId] as ZoneNode + nodes[zone.id] = { + ...zone, + floor: { + ...zone.floor, + regions: [...(zone.floor?.regions ?? []), ...regions], + }, + } + } + } + } + } + // Stamp every existing opening, even interior ones: a later room deletion + // must not turn a newly exterior doorway into another legacy migration. + for (const id of pending) nodes[id] = { ...nodes[id], floorThresholdVersion: 1 } as AnyNode + return nodes +} diff --git a/packages/core/src/utils/floor-follow-migration.ts b/packages/core/src/utils/floor-follow-migration.ts new file mode 100644 index 0000000000..2e1007555e --- /dev/null +++ b/packages/core/src/utils/floor-follow-migration.ts @@ -0,0 +1,37 @@ +import { footprintLift } from '../lib/floor-foundation-datum' +import { wallSupportForNodes } from '../lib/opening-floor-datum' +import type { AnyNode } from '../schema' +import { getWallPlaneTop } from '../services/storey' +import { wallOverlapsSlabFootprint } from '../systems/slab/slab-support' + +export function migrateFootprintFollowing(nodes: Record): Record { + const bases = Object.values(nodes).filter( + (node) => + node.type === 'slab' && + node.plateRole === 'base' && + Math.abs(footprintLift(nodes, node)) > 1e-6, + ) + if (!bases.length) return nodes + let result = nodes + for (const wall of Object.values(nodes)) { + if ( + wall.type !== 'wall' || + wall.height === undefined || + wall.supportSlabId === 'ground' || + !bases.some( + (base) => + base.type === 'slab' && + base.parentId === wall.parentId && + wallOverlapsSlabFootprint(wall, base.polygon), + ) + ) + continue + const following = + getWallPlaneTop(wall, wall.parentId!, nodes) - wallSupportForNodes(wall, nodes).elevation + if (Math.abs(following - wall.height) > 1e-6) continue + const { height: _height, ...next } = wall + if (result === nodes) result = { ...nodes } + result[wall.id] = next + } + return result +} diff --git a/packages/core/src/utils/floor-opening-migration.ts b/packages/core/src/utils/floor-opening-migration.ts new file mode 100644 index 0000000000..eb9541e9d4 --- /dev/null +++ b/packages/core/src/utils/floor-opening-migration.ts @@ -0,0 +1,159 @@ +import { adjacentLevelId } from '../lib/floor-opening-intent' +import { area, intersection, type Ring, union } from '../lib/polygon-boolean' +import type { AnyNode, CeilingNode, SlabNode } from '../schema' +import { FloorOpeningNode } from '../schema/nodes/floor-opening' + +function polygonKey(polygon: Ring) { + return polygon.map(([x, z]) => [Math.round(x * 10_000), Math.round(z * 10_000)]) +} + +function openingId(levelId: string, hostZoneId: string | undefined, polygon: Ring) { + const seed = JSON.stringify([levelId, hostZoneId ?? '', polygonKey(polygon)]) + let hash = 0xcbf2_9ce4_8422_2325n + for (const byte of new TextEncoder().encode(seed)) + hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100_0000_01b3n) + return `floor-opening_${hash.toString(36).padStart(16, '0')}` +} + +function matchingCeilingHole(nodes: Record, levelId: string, polygon: Ring) { + const below = adjacentLevelId(nodes as Record, levelId, -1) + if (!below) return false + const size = area([{ outer: polygon, holes: [] }]) + if (size < 1e-4) return false + return Object.values(nodes).some((value) => { + const ceiling = value as CeilingNode + return ( + ceiling.type === 'ceiling' && + ceiling.parentId === below && + (ceiling.boundary === 'auto' || ceiling.autoFromWalls) && + ceiling.holes?.some( + (hole) => + Math.abs(area(intersection(polygon, hole)) - size) < 1e-4 && + Math.abs(area([{ outer: hole, holes: [] }]) - size) < 1e-4, + ) + ) + }) +} + +export function migrateFloorOpeningNodes(sourceNodes: Record) { + let nodes: Record = sourceNodes + const groups = new Map< + string, + { + levelId: string + hostZoneId?: string + ownerId?: string + cuts: Array<{ plateId: string; polygon: Ring }> + } + >() + let adoptedHoles = 0 + let dedupes = 0 + let unions = 0 + for (const value of Object.values(sourceNodes)) { + const slab = value as SlabNode + if ( + slab.type !== 'slab' || + !(slab.boundary === 'auto' || slab.autoFromWalls) || + (slab.recessed === true && slab.autoFromWalls && !slab.boundary) || + !slab.parentId || + !Array.isArray(slab.holes) + ) + continue + const kept = slab.holes.flatMap((hole, index) => { + const metadata = slab.holeMetadata?.[index] + if ((metadata?.source ?? 'manual') !== 'manual') return [{ hole, metadata }] + if (area([{ outer: hole, holes: [] }]) < 1e-4) return [] + const hostZoneId = + slab.support === 'open' && slab.zoneIds?.length === 1 ? slab.zoneIds[0] : undefined + const managed = (slab.metadata as Record | undefined)?.poolManagedOpenings + const pool = Array.isArray(managed) + ? (managed.find((entry) => { + const candidate = entry as { poolId?: unknown; holeIndex?: unknown; polygon?: unknown } + return ( + typeof candidate.poolId === 'string' && + (candidate.holeIndex === index || + JSON.stringify(candidate.polygon) === JSON.stringify(hole)) + ) + }) as { poolId: string } | undefined) + : undefined + const ownerId = pool?.poolId + const key = JSON.stringify([slab.parentId, hostZoneId ?? '', ownerId ?? '']) + const group = groups.get(key) ?? { + levelId: slab.parentId!, + hostZoneId, + ownerId, + cuts: [], + } + group.cuts.push({ plateId: slab.id, polygon: hole }) + groups.set(key, group) + adoptedHoles++ + return [] + }) + if (kept.length === slab.holes.length) continue + if (nodes === sourceNodes) nodes = { ...sourceNodes } + nodes[slab.id] = { + ...slab, + holes: kept.map(({ hole }) => hole), + holeMetadata: kept.map(({ metadata }) => metadata ?? { source: 'manual' }), + } + } + let created = 0 + for (const group of [...groups.values()].sort((a, b) => + JSON.stringify([a.levelId, a.hostZoneId, a.ownerId]).localeCompare( + JSON.stringify([b.levelId, b.hostZoneId, b.ownerId]), + ), + )) { + const unique = [ + ...new Map( + group.cuts.map(({ polygon }) => [JSON.stringify(polygonKey(polygon)), polygon]), + ).values(), + ] + const parts = union(unique) + dedupes += group.cuts.length - unique.length + unions += unique.length - parts.length + for (const part of parts) { + if (area([part]) < 1e-4) continue + const id = openingId(group.levelId, group.hostZoneId, part.outer) + const legacyPlateCuts: Record = {} + for (const cut of group.cuts) { + if (area(intersection(cut.polygon, part)) < 1e-6) continue + const stored = legacyPlateCuts[cut.plateId] ?? [] + if (!stored.some((ring) => JSON.stringify(ring) === JSON.stringify(cut.polygon))) + stored.push(cut.polygon) + legacyPlateCuts[cut.plateId] = stored + } + const existing = nodes[id] as FloorOpeningNode | undefined + if (existing?.type === 'floor-opening') { + if (nodes === sourceNodes) nodes = { ...sourceNodes } + nodes[id] = { + ...existing, + legacyPlateCuts: { ...existing.legacyPlateCuts, ...legacyPlateCuts }, + ...(group.ownerId ? { source: 'plugin:pool', ownerId: group.ownerId } : {}), + } + continue + } + if (nodes === sourceNodes) nodes = { ...sourceNodes } + nodes[id] = FloorOpeningNode.parse({ + id, + parentId: group.levelId, + name: 'Floor opening', + polygon: part.outer, + ...(group.hostZoneId ? { hostZoneId: group.hostZoneId } : {}), + legacyPlateCuts, + source: group.ownerId ? 'plugin:pool' : 'manual', + ownerId: group.ownerId, + drawnOn: 'floor', + cutsPrimary: true, + cutsAdjacent: + !group.ownerId && + !group.hostZoneId && + matchingCeilingHole(sourceNodes, group.levelId, part.outer), + }) + const level = nodes[group.levelId] as AnyNode | undefined + if (level?.type === 'level' && !level.children.includes(id as never)) + nodes[group.levelId] = { ...level, children: [...level.children, id as never] } + created++ + } + } + return { nodes, changed: nodes !== sourceNodes, adoptedHoles, created, dedupes, unions } +} diff --git a/packages/core/src/utils/floor-piece-adoption.test.ts b/packages/core/src/utils/floor-piece-adoption.test.ts new file mode 100644 index 0000000000..6fe0e3a065 --- /dev/null +++ b/packages/core/src/utils/floor-piece-adoption.test.ts @@ -0,0 +1,204 @@ +import { expect, test } from 'bun:test' +import { slabFootprint } from '../lib/floor-plates' +import { area, containsPoint, difference } from '../lib/polygon-boolean' +import { type AnyNode, LevelNode, SlabNode, WallNode, type ZoneNode } from '../schema' +import type { FloorPlateMigrationReport } from './floor-plate-migration' +import * as migrations from './scene-migrations' + +type Nodes = Record + +// Two rooms (0..4 and 4..8 by 0..4) inside 0.2 m walls: outer faces at -0.1 / 8.1 / 4.1. +function house(pieces: Array & { id: string; polygon: [number, number][] }>) { + const ring: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ] + const walls = [ + ...ring.map((start, i) => + WallNode.parse({ + id: `wall_${i}`, + parentId: 'level_house', + start, + end: ring[(i + 1) % 4], + thickness: 0.2, + }), + ), + WallNode.parse({ + id: 'wall_divider', + parentId: 'level_house', + start: [4, 0], + end: [4, 4], + thickness: 0.2, + }), + ] + const slabs = pieces.map((piece) => SlabNode.parse({ parentId: 'level_house', ...piece })) + const level = LevelNode.parse({ + id: 'level_house', + children: [...walls, ...slabs].map((node) => node.id), + }) + return Object.fromEntries([level, ...walls, ...slabs].map((node) => [node.id, node])) as Nodes +} + +function load(source: Nodes) { + const vertical = migrations.migrateVerticalSceneNodes( + migrations.healSceneNodes(migrations.normalizeLegacyStructure(source)).nodes, + ).nodes + const rooms = migrations.migrateCeilingRoomLinks( + migrations.migrateRoomZones(vertical).nodes, + ).nodes + const plates = migrations.migrateFloorPlates(rooms) + const openings = migrations.ensureSceneOpenings( + migrations.migrateSlabSlots(plates.nodes).nodes, + ).nodes + const walls = migrations.migrateWallFaceBands( + migrations.migrateWallFaceKeys(openings).nodes, + ).nodes + return { + reports: plates.reports as FloorPlateMigrationReport[], + nodes: migrations.reconcileStructureOnLoad(walls, vertical).nodes as Nodes, + } +} + +const slabs = (nodes: Nodes) => + Object.values(nodes).filter((node): node is SlabNode => node.type === 'slab') +const rooms = (nodes: Nodes) => + Object.values(nodes).filter((node): node is ZoneNode => node.type === 'zone') +const roomAt = (nodes: Nodes, x: number) => + rooms(nodes).find((room) => containsPoint([slabFootprint(room)], [x, 2]))! + +const left = (overrides: Partial = {}) => ({ + id: 'slab_left', + // Drawn 8 cm past the north facade: more than the renderer snaps to the wall. + polygon: [ + [-0.1, -0.1], + [4, -0.1], + [4, 4.18], + [-0.1, 4.18], + ] as [number, number][], + slots: { surface: 'library:oak' }, + ...overrides, +}) +const right = (overrides: Partial = {}) => ({ + id: 'slab_right', + polygon: [ + [4, -0.1], + [8.1, -0.1], + [8.1, 4.1], + [4, 4.1], + ] as [number, number][], + slots: { surface: 'library:tiles' }, + ...overrides, +}) + +// Furniture standing on a piece moves onto the plate. +function furnished() { + const source = house([left(), right()]) + source.item_chair = { + id: 'item_chair', + type: 'item', + object: 'node', + parentId: 'level_house', + position: [6, 0.05, 2], + supportSlabId: 'slab_right', + } as unknown as AnyNode + return source +} + +test('hand-drawn floor slabs covering the house become one generated floor plate', () => { + const source = furnished() + const { nodes, reports } = load(source) + const floors = slabs(nodes) + expect(floors).toHaveLength(1) + const [plate] = floors + expect(plate).toMatchObject({ + plateRole: 'base', + boundary: 'auto', + elevation: 0.05, + thickness: 0.05, + referenceFloorElevation: 0.05, + }) + expect(plate!.zoneIds).toHaveLength(2) + // Each room keeps the finish its piece showed. + expect(roomAt(nodes, 2).floor?.finish).toBe('library:oak') + expect(roomAt(nodes, 6).floor?.finish).toBe('library:tiles') + expect((nodes.item_chair as { supportSlabId?: string }).supportSlabId).toBe(plate!.id) + // Only the 8 cm overshoot past the facade is dropped. + const [absorbed] = reports.filter((report) => report.code === 'floor-pieces-absorbed') + expect(absorbed).toMatchObject({ nodeId: 'level_house', holes: 0, closed: 0 }) + expect(absorbed!.pieces!.sort()).toEqual(['slab_left', 'slab_right']) + expect(absorbed!.trimmed).toBeGreaterThan(0.2) + expect(absorbed!.trimmed).toBeLessThan(0.4) + // Idempotent and deterministic: a second load and an independent first load agree. + expect(load(nodes).nodes).toEqual(nodes) + expect(load(furnished()).nodes).toEqual(nodes) +}) + +test('an uncovered closet inside a room stays open, as a hole in the plate', () => { + // The left piece skips a 1 m square in the room's corner. + const { nodes } = load( + house([ + left({ + polygon: [ + [-0.1, -0.1], + [4, -0.1], + [4, 4.1], + [1.1, 4.1], + [1.1, 3], + [-0.1, 3], + ], + }), + right(), + ]), + ) + const [plate] = slabs(nodes) + expect(plate!.plateRole).toBe('base') + const top = difference(slabFootprint(plate!), []) + expect(containsPoint(top, [0.5, 3.5])).toBe(false) + expect(containsPoint(top, [2, 2])).toBe(true) + expect(area(top)).toBeLessThan(8.2 * 4.2 - 0.9) +}) + +test('a floor drawn on through the facade as a terrace keeps the hand-drawn slabs', () => { + const source = house([ + left({ + polygon: [ + [-0.1, -0.1], + [4, -0.1], + [4, 6], + [-0.1, 6], + ], + }), + right(), + ]) + const { nodes, reports } = load(source) + expect(reports.some((report) => report.code === 'floor-pieces-absorbed')).toBe(false) + expect(nodes.slab_left).toMatchObject({ polygon: (source.slab_left as SlabNode).polygon }) + expect(nodes.slab_right).toBeDefined() + expect(slabs(nodes).some((slab) => slab.plateRole === 'base')).toBe(false) +}) + +test('a raised platform inside a room keeps the hand-drawn slabs', () => { + const { nodes, reports } = load( + house([ + left(), + right(), + { + id: 'slab_stage', + elevation: 0.3, + thickness: 0.3, + polygon: [ + [5, 1], + [7, 1], + [7, 3], + [5, 3], + ], + }, + ]), + ) + expect(reports.some((report) => report.code === 'floor-pieces-absorbed')).toBe(false) + expect(nodes.slab_left).toBeDefined() + expect(nodes.slab_right).toBeDefined() + expect(nodes.slab_stage).toBeDefined() +}) diff --git a/packages/core/src/utils/floor-piece-adoption.ts b/packages/core/src/utils/floor-piece-adoption.ts new file mode 100644 index 0000000000..455054ce15 --- /dev/null +++ b/packages/core/src/utils/floor-piece-adoption.ts @@ -0,0 +1,234 @@ +import { + area, + containsPoint, + difference, + distanceToBoundary, + intersection, + type MultiPolygon, + type Polygon, + type Ring, + union, +} from '../lib/polygon-boolean' +import { getRenderableSlabPolygon, prepareSlabPolygonContext } from '../lib/slab-polygon' +import type { AnyNode, SlabNode, WallNode, ZoneNode } from '../schema' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' + +/** + * Hand-drawn floor pieces: legacy manual slabs someone drew to be the house + * floor before rooms generated one. A level's pieces are adopted, all or + * nothing, when they are the level's only floor inside its rooms: one top and + * one construction, grounded, no platform or step at another height, nothing + * reaching more than PIECE_TRIM_DEPTH past the rooms and walls. The load + * migration then treats them like legacy wall-generated slabs, so one plate + * replaces the patchwork and each room keeps the finish its piece showed. + * Drawing noise is the only visible change: strips at most PIECE_TRIM_DEPTH + * past a facade go, cracks at most PIECE_GAP_WIDTH wide close, and wider + * uncovered room floor stays open as a hole in the plate. + */ +export const PIECE_TRIM_DEPTH = 0.1 +export const PIECE_GAP_WIDTH = 0.05 + +export type FloorPieceAdoption = { + /** Adopted piece id → its level id. */ + pieces: Map + /** Per adopted level: uncovered room floor wider than a crack (plate holes). */ + levels: Map +} + +export function floorPieceFinish(slab: SlabNode) { + return slab.slots?.surface ?? slab.material ?? slab.materialPreset +} + +function tryArea(compute: () => MultiPolygon) { + try { + return area(compute()) + } catch { + return Number.NaN + } +} + +/** Mean width of a part: 2·area / perimeter (the width of a long strip). */ +export function partWidth(part: Polygon) { + let perimeter = 0 + for (const ring of [part.outer, ...part.holes]) + for (const [i, [x, z]] of ring.entries()) { + const [nx, nz] = ring[(i + 1) % ring.length]! + perimeter += Math.hypot(nx - x, nz - z) + } + return perimeter > 0 ? (2 * area([part])) / perimeter : 0 +} + +function depthOutside(part: Polygon, from: MultiPolygon) { + let depth = 0 + for (const point of part.outer) + if (!containsPoint(from, point)) depth = Math.max(depth, distanceToBoundary(from, point)) + return depth +} + +function planLevel(children: AnyNode[]): { pieces: SlabNode[]; voids: Ring[] } | undefined { + const slabs = children.filter((node): node is SlabNode => node.type === 'slab') + const walls = children.filter((node): node is WallNode => node.type === 'wall') + const rooms = children.filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.spaceRole === 'room' && + node.enclosureStatus !== 'open' && + node.hasFloor !== false && + node.floor?.support !== 'open' && + node.polygon.length >= 3, + ) + if (!rooms.length || !walls.length) return + const floorish = slabs.filter( + (slab) => + slab.visible !== false && + slab.support !== 'open' && + !slab.recessed && + !slab.plateRole && + slab.polygon.length >= 3 && + slab.elevation - slab.thickness <= 0.01, + ) + const miters = calculateLevelMiters(walls) + const wallArea = union( + walls.map((wall) => ({ + outer: getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + holes: [], + })), + ) + const roomArea = union(rooms.map((room) => ({ outer: room.polygon, holes: room.holes ?? [] }))) + const context = prepareSlabPolygonContext({ walls, siblingSlabs: slabs }) + const rendered = new Map( + floorish.map((slab) => [ + slab.id, + { outer: getRenderableSlabPolygon(slab, context), holes: slab.holes ?? [] } as Polygon, + ]), + ) + const weights = new Map() + const cover = new Map() + for (const slab of floorish) { + const inRooms = area(intersection(rendered.get(slab.id)!, roomArea)) + cover.set(slab.id, inRooms) + if (inRooms <= 1e-3) continue + const top = Math.round(slab.elevation * 1e6) / 1e6 + weights.set(top, (weights.get(top) ?? 0) + inRooms) + } + const [datum] = [...weights].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0] ?? [] + if (datum === undefined) return + const floor = floorish.filter((slab) => (cover.get(slab.id) ?? 0) > 1e-3) + // A second floor height inside the rooms (a platform, a step, a raised floor + // reaching down to the floor) is custom construction. + const stepped = slabs.some( + (slab) => + slab.visible !== false && + slab.support !== 'open' && + !slab.recessed && + slab.polygon.length >= 3 && + Math.abs(slab.elevation - datum) > 1e-3 && + slab.elevation - slab.thickness <= datum + 1e-3 && + area( + intersection( + rendered.get(slab.id) ?? { outer: slab.polygon, holes: slab.holes ?? [] }, + roomArea, + ), + ) > 1e-3, + ) + if (stepped) return + // One construction: the generated plate has one thickness and foundation. + const [first] = floor + if ( + !first || + floor.some( + (slab) => + Math.abs(slab.thickness - first.thickness) > 1e-3 || + !!slab.fillToTerrain !== !!first.fillToTerrain, + ) + ) + return + const decks = new Set( + children.flatMap((node) => { + const deck = (node as { deckSlabId?: string }).deckSlabId + return deck ? [deck] : [] + }), + ) + const autos = floor.filter((slab) => slab.autoFromWalls || slab.boundary === 'auto') + const autoArea = union(autos.map((slab) => rendered.get(slab.id)!)) + const inside = union([roomArea, wallArea]) + const pieces: SlabNode[] = [] + for (const slab of floor) { + if (slab.autoFromWalls || slab.boundary === 'auto') continue + if (slab.metadata?.plateMigration !== undefined || decks.has(slab.id)) return + const surface = rendered.get(slab.id)! + // A finish laid on a wall-generated slab: the finish migration owns it. + if (autos.length && tryArea(() => difference(surface, autoArea)) <= 1e-4) continue + const outside = difference(surface, inside) + // The whole floor or nothing: a level keeping one hand-drawn floor keeps them all. + if ( + outside.some( + (part) => + partWidth(part) > PIECE_TRIM_DEPTH || + depthOutside(part, inside) > PIECE_TRIM_DEPTH + 1e-9, + ) + ) + return + pieces.push(slab) + } + if (!pieces.length) return + const covered = union([...autos, ...pieces].map((slab) => rendered.get(slab.id)!)) + const floored = union( + rooms + .filter( + (room) => + area(intersection({ outer: room.polygon, holes: room.holes ?? [] }, covered)) > 1e-3, + ) + .map((room) => ({ outer: room.polygon, holes: room.holes ?? [] })), + ) + const uncovered = difference(difference(floored, covered), wallArea).filter( + (part) => area([part]) > 1e-4, + ) + return { + pieces, + voids: uncovered + .filter((part) => partWidth(part) > PIECE_GAP_WIDTH + 1e-9) + .map((part) => part.outer), + } +} + +/** + * Plans which legacy manual slabs the floor-plate migration adopts. Runs only + * on scenes that have no floor plates yet (the same guard as the legacy floor + * migration), so a migrated scene never re-plans. + */ +export function planFloorPieceAdoption( + nodes: Readonly>, + skipLevels: ReadonlySet = new Set(), +): FloorPieceAdoption { + const adoption: FloorPieceAdoption = { pieces: new Map(), levels: new Map() } + const all = Object.values(nodes) + if (all.some((node) => node.type === 'slab' && node.plateRole)) return adoption + const byParent = new Map() + for (const node of all) { + if (!node.parentId) continue + const list = byParent.get(node.parentId) ?? [] + list.push(node) + byParent.set(node.parentId, list) + } + for (const level of all) { + // Levels the floor migration already settled (a saved, migrated scene) never re-plan. + if ( + level.type !== 'level' || + skipLevels.has(level.id) || + level.metadata?.floorOwnershipMigrated === true + ) + continue + const children = byParent.get(level.id) ?? [] + let planned: ReturnType + try { + planned = planLevel(children) + } catch { + continue + } + if (!planned) continue + adoption.levels.set(level.id, { voids: planned.voids }) + for (const piece of planned.pieces) adoption.pieces.set(piece.id, level.id) + } + return adoption +} diff --git a/packages/core/src/utils/floor-plate-corpus.test.ts b/packages/core/src/utils/floor-plate-corpus.test.ts new file mode 100644 index 0000000000..50c2935bc9 --- /dev/null +++ b/packages/core/src/utils/floor-plate-corpus.test.ts @@ -0,0 +1,422 @@ +import { describe, expect, spyOn, test } from 'bun:test' +import { readdirSync, readFileSync } from 'node:fs' +import clipping from 'polygon-clipping' +import { buildFloorPlates, footprintIoU, slabFootprint } from '../lib/floor-plates' +import { plateFootprint } from '../lib/level-footprints' +import { + area, + containsPoint, + difference, + distanceToBoundary, + intersection, + type Ring, + union, +} from '../lib/polygon-boolean' +import { extractRooms } from '../lib/room-graph' +import { getRenderableSlabPolygon } from '../lib/slab-polygon' +import { createRoomTopologyIndex } from '../lib/space-detection' +import type { AnyNode, SlabNode, WallNode, ZoneNode } from '../schema' +import { getWallCurveFrameAt } from '../systems/wall/wall-curve' +import { getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { getWallFaceOffsets } from '../systems/wall/wall-frame' +import { calculateLevelMiters, getWallMiterBoundaryPoints } from '../systems/wall/wall-mitering' +import { + healSceneNodes, + migrateCeilingRoomLinks, + migrateFloorPlates, + migrateRoomZones, + migrateSlabSlots, + migrateVerticalSceneNodes, +} from './scene-migrations' + +type Fixture = { sceneId: string; levelId: string; nodes: Record } +const directory = new URL('../lib/__fixtures__/plate-corpus/migrations/', import.meta.url) +const fixtures: Fixture[] = readdirSync(directory) + .filter((file) => file.endsWith('.json')) + .sort() + .map((file) => JSON.parse(readFileSync(new URL(file, directory), 'utf8'))) +function rooms(nodes: Record) { + return migrateCeilingRoomLinks(migrateRoomZones(nodes).nodes).nodes as Record +} +function migrate(nodes: Record) { + return migrateSlabSlots(migrateFloorPlates(rooms(nodes)).nodes).nodes as Record +} +function plates(nodes: Record): SlabNode[] { + return Object.values(nodes) + .filter( + (node): node is SlabNode => + (node as AnyNode).type === 'slab' && (node as SlabNode).boundary === 'auto', + ) + .sort((a, b) => a.id.localeCompare(b.id)) +} +function visible(nodes: Record) { + const walls = Object.values(nodes).filter((node): node is WallNode => node.type === 'wall') + const slabs = Object.values(nodes).filter((node): node is SlabNode => node.type === 'slab') + const miters = calculateLevelMiters(walls) + const quantize = (ring: Ring) => + ring.map(([x, z]) => [Math.round(x * 1e7) / 1e7, Math.round(z * 1e7) / 1e7] as [number, number]) + const polygons = slabs.map((slab) => [ + quantize(getRenderableSlabPolygon(slab, { walls, siblingSlabs: slabs })), + ...(slab.holes ?? []).map(quantize), + ]) + const boundaries = walls.map((wall) => [ + quantize(getWallPlanFootprint(wall, miters).map(({ x, y }) => [x, y])), + ]) + if (!polygons.length) return 0 + const floor = clipping.union(polygons[0]!, ...polygons.slice(1)) + const result = boundaries.length ? clipping.difference(floor, ...boundaries) : floor + const ringArea = (ring: Ring) => + Math.abs( + ring.reduce((sum, p, i) => { + const q = ring[(i + 1) % ring.length]! + return sum + p[0] * q[1] - q[0] * p[1] + }, 0), + ) / 2 + return result.reduce( + (sum, [outer, ...holes]) => + sum + ringArea(outer!) - holes.reduce((total, hole) => total + ringArea(hole), 0), + 0, + ) +} + +function expectPreservedSlab( + before: Record, + after: Record, + source: SlabNode, + demoted = false, +) { + const current = after[source.id] as SlabNode + const { associatedZoneIds, ...construction } = current + const reason = (current.metadata?.plateMigration as { demoted?: string } | undefined)?.demoted + const oldWalls = Object.values(before).filter((node): node is WallNode => node.type === 'wall') + const oldSlabs = Object.values(before).filter((node): node is SlabNode => node.type === 'slab') + const rendered = + reason === 'wall-supported-floor' && + JSON.stringify(current.polygon) !== JSON.stringify(source.polygon) + ? getRenderableSlabPolygon(source, { walls: oldWalls, siblingSlabs: oldSlabs }) + : source.polygon + expect(construction).toEqual( + demoted + ? { + ...source, + polygon: rendered, + autoFromWalls: false, + metadata: { ...source.metadata, plateMigration: { demoted: expect.any(String) } }, + } + : source, + ) + if (associatedZoneIds !== undefined) + expect(associatedZoneIds).toEqual( + Object.values(after) + .filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.spaceRole === 'room' && + area(intersection(slabFootprint(node), slabFootprint(current))) > 1e-4, + ) + .map((zone) => zone.id) + .sort(), + ) +} + +describe('M4/M5 trimmed production levels', () => { + test.each( + fixtures, + )('$sceneId $levelId is deterministic, pure and stable across the server reload', ({ nodes }) => { + const original = JSON.stringify(nodes) + const warning = spyOn(console, 'warn').mockImplementation(() => {}) + try { + const after = migrate(nodes) + expect(JSON.stringify(nodes)).toBe(original) + const reversed = migrate(Object.fromEntries(Object.entries(nodes).reverse())) + expect(plates(reversed)).toEqual(plates(after)) + const reloaded = migrate(migrateVerticalSceneNodes(healSceneNodes(after).nodes).nodes) + expect(reloaded).toEqual(after) + expect( + warning.mock.calls.filter( + ([message, details]) => + message === '[floor plates] Keeping existing level construction' && + (details as { error: unknown }).error !== 'recessed-legacy: preserved verbatim', + ), + ).toEqual([]) + for (const plate of plates(after)) { + if (!plate.zoneIds!.length) expect(plate.plateRole).toBe('base') + expect(plate.zoneIds).toEqual([...plate.zoneIds!].sort()) + expect( + (after[plate.parentId!] as { children: string[] }).children.filter( + (id) => id === plate.id, + ), + ).toHaveLength(1) + } + } finally { + warning.mockRestore() + } + }) + + test.each(fixtures)('$sceneId $levelId preserves visible floor area within 1%', ({ nodes }) => { + const before = visible(nodes), + after = visible(migrate(nodes)) + expect(Math.abs(after - before)).toBeLessThanOrEqual(Math.max(1e-6, before * 0.01)) + }) + + test.each([ + 'scene-23', + ])('%s keeps stale small floors without filling larger moved rooms', (sceneId) => { + const fixture = fixtures.find((fixture) => fixture.sceneId === sceneId)! + const after = migrate(fixture.nodes) + expect(plates(after)).toEqual([]) + for (const slab of Object.values(fixture.nodes).filter((node) => node.type === 'slab')) + expectPreservedSlab(fixture.nodes, after, slab, !!slab.autoFromWalls) + }) + + test('a room buried inside thick walls stays at zero visible floor area', () => { + const fixture = fixtures.find(({ sceneId }) => sceneId === 'scene-11')! + const after = migrate(fixture.nodes) + expect(visible(fixture.nodes)).toBe(0) + expect(visible(after)).toBe(0) + expect(plates(after)).toEqual([]) + for (const slab of Object.values(fixture.nodes).filter((node) => node.type === 'slab')) + expectPreservedSlab(fixture.nodes, after, slab, !!slab.autoFromWalls) + }) + + test.each(['scene-03'])('%s keeps one real room and one floor supplier', (sceneId) => { + const fixture = fixtures.find((fixture) => fixture.sceneId === sceneId)! + const after = migrate(fixture.nodes) + const zones = Object.values(after).filter( + (node): node is ZoneNode => node.type === 'zone' && node.spaceRole === 'room', + ) + expect(zones).toHaveLength(1) + expect(zones[0]!.holes).toEqual([]) + const suppliers = Object.values(after).filter( + (node): node is SlabNode => + node.type === 'slab' && + (node.zoneIds?.includes(zones[0]!.id) || node.associatedZoneIds?.includes(zones[0]!.id)), + ) + expect(suppliers).toHaveLength(1) + expect(suppliers[0]!.plateRole === 'base' || !suppliers[0]!.autoFromWalls).toBe(true) + expect(Math.abs(visible(after) - visible(fixture.nodes))).toBeLessThan(0.01) + }) + + test.each( + fixtures.filter(({ sceneId }) => ['scene-05', 'scene-08'].includes(sceneId)), + )('$sceneId IDs do not depend on legacy material representation', ({ nodes }) => { + const materialized = Object.fromEntries( + Object.entries(nodes).map(([id, node]) => [ + id, + node.type === 'slab' && node.material !== undefined + ? { ...node, material: undefined, slots: { surface: `scene:material_${id}` } } + : node, + ]), + ) + const raw = migrate(nodes), + resolved = migrate(materialized) + expect(plates(raw).map((plate) => plate.id)).toEqual(plates(resolved).map((plate) => plate.id)) + if (Object.values(nodes).some((node) => node.type === 'slab' && node.autoFromWalls)) + expect( + plates(raw).length > 0 || + Object.values(nodes) + .filter((node) => node.type === 'slab' && node.autoFromWalls) + .every((slab) => raw[slab.id]?.type === 'slab' && !raw[slab.id].autoFromWalls), + ).toBe(true) + for (const source of Object.values(nodes)) { + if (source.type !== 'slab' || source.material === undefined || raw[source.id]) continue + const retained = Object.values(raw).flatMap((node) => + node.type === 'slab' + ? [node.material] + : node.type === 'zone' + ? [node.floor?.finish, ...(node.floor?.regions ?? []).map((region) => region.finish)] + : [], + ) + expect( + retained.some((finish) => JSON.stringify(finish) === JSON.stringify(source.material)), + ).toBe(true) + } + }) + + test('recessed legacy construction is byte-identical and its room is excluded', () => { + const fixture = fixtures.find(({ nodes }) => + Object.values(nodes).some((node) => node.type === 'slab' && node.recessed), + )! + const before = rooms(fixture.nodes), + after = migrate(fixture.nodes) + const pools = Object.values(before).filter( + (node): node is SlabNode => node.type === 'slab' && node.recessed, + ) + expect(pools.length).toBeGreaterThan(0) + for (const pool of pools) { + expect(after[pool.id]).toEqual(pool) + for (const plate of plates(after)) + for (const id of plate.zoneIds!) + expect( + footprintIoU({ outer: pool.polygon, holes: [] }, slabFootprint(after[id] as ZoneNode)), + ).toBeLessThan(0.6) + } + }) + + test.each(['scene-27'])('%s emits every disconnected component with stable IDs', (sceneId) => { + const fixture = fixtures.find((fixture) => fixture.sceneId === sceneId)! + const nodes = rooms(fixture.nodes), + index = createRoomTopologyIndex() + index.rebuild(nodes) + const topology = index.getLevelTopology(fixture.levelId)! + const zones = Object.values(nodes).filter( + (node): node is ZoneNode => node.type === 'zone' && node.spaceRole === 'room', + ) + const room = topology.rooms.find((room) => plateFootprint([room]).length > 1)! + expect(room).toBeDefined() + const zone = zones.find((zone) => footprintIoU(slabFootprint(zone), slabFootprint(room)) > 0.9)! + const members = [{ ...room, zone }] + const footprint = plateFootprint(members) + const input = { + levelId: fixture.levelId, + rooms: members, + slabs: [] as SlabNode[], + mintId: (_ids: string[], component = 0) => `slab_component_${component}`, + } + const plan = buildFloorPlates(input) + expect(plan.plates).toHaveLength(footprint.length) + expect(new Set(plan.plates.map((plate) => plate.id)).size).toBe(footprint.length) + expect(area(difference(footprint, union(plan.plates.map(slabFootprint))))).toBeLessThan(1e-6) + expect(buildFloorPlates({ ...input, slabs: plan.plates }).plates).toEqual(plan.plates) + }) + + test('M3 does not adopt an oversized generic zone over a real production face', () => { + const fixture = fixtures.find(({ sceneId }) => sceneId === 'scene-03')! + const generic = { + id: 'zone_generic_site', + type: 'zone', + name: 'Site analysis', + spaceRole: 'generic', + parentId: fixture.levelId, + polygon: [ + [-100, -100], + [100, -100], + [100, 100], + [-100, 100], + ], + holes: [], + } + const migrated = migrateRoomZones({ ...fixture.nodes, [generic.id]: generic }) + expect(migrated.nodes[generic.id]).toBe(generic) + expect(migrated.createdZoneIds).toHaveLength(1) + expect(migrated.adoptedZoneIds).not.toContain(generic.id) + }) + + test('snapped production junctions produce the same rooms in M3 and either index insertion order', () => { + const fixture = fixtures.find(({ sceneId }) => sceneId === 'scene-12')! + const nodes = rooms(fixture.nodes) + const forward = createRoomTopologyIndex(), + reverse = createRoomTopologyIndex() + forward.rebuild(nodes) + reverse.rebuild(Object.fromEntries(Object.entries(nodes).reverse())) + const snapshot = (index: ReturnType) => + index + .getLevelTopology(fixture.levelId)! + .rooms.map(({ polygon, holes, spans }) => ({ polygon, holes, spans })) + expect(snapshot(forward)).toEqual(snapshot(reverse)) + expect(snapshot(forward)).toHaveLength(4) + const result = plates(migrate(nodes)) + expect(result).toHaveLength(1) + expect(result[0]!.zoneIds).toHaveLength(4) + }) + + test.each([ + 'scene-20', + ])('%s does not plate a room entirely inside a legacy opening', (sceneId) => { + const fixture = fixtures.find((fixture) => fixture.sceneId === sceneId)! + const after = migrate(fixture.nodes) + for (const plate of plates(after)) { + expect(area(union([slabFootprint(plate)]))).toBeGreaterThan(1e-6) + for (const id of plate.zoneIds!) { + const zone = after[id] as ZoneNode + expect( + Object.values(fixture.nodes).some( + (node) => + node.type === 'slab' && + node.autoFromWalls && + footprintIoU(slabFootprint(node), slabFootprint(zone)) > 0, + ), + ).toBe(true) + } + } + }) + + test.each([ + 'scene-01', + ])('%s demotes unmatched construction without changing its geometry or id', (sceneId) => { + const fixture = fixtures.find((fixture) => fixture.sceneId === sceneId)! + const after = migrate(fixture.nodes) + let demoted = 0 + for (const source of Object.values(fixture.nodes)) { + if ( + source.type !== 'slab' || + !source.autoFromWalls || + !after[source.id] || + (after[source.id] as SlabNode).plateRole + ) + continue + expectPreservedSlab(fixture.nodes, after, source, true) + demoted++ + } + expect(demoted).toBeGreaterThan(0) + }) + + test.each( + fixtures.filter(({ sceneId }) => sceneId === 'scene-25'), + )('$sceneId $levelId stored plates cover mitered faces outside existing cutouts', ({ nodes }) => { + const before = rooms(nodes), + after = migrate(nodes) + const walls = Object.values(nodes).filter((node): node is WallNode => node.type === 'wall') + const miters = calculateLevelMiters(walls), + faces = extractRooms(walls) + const stored = plates(after) + if (!stored.length) { + for (const source of Object.values(nodes).filter( + (node) => node.type === 'slab' && node.autoFromWalls, + )) + expectPreservedSlab(nodes, after, source, true) + expect(Math.abs(visible(after) - visible(nodes))).toBeLessThanOrEqual( + Math.max(1e-6, visible(nodes) * 0.01), + ) + return + } + const cutouts = Object.values(nodes) + .filter((node): node is SlabNode => node.type === 'slab') + .flatMap((slab) => (slab.holes ?? []).map((outer) => ({ outer, holes: [] }))) + let checked = 0 + for (const room of faces) { + const plate = stored.find((plate) => + plate.zoneIds!.some( + (id) => + footprintIoU(slabFootprint(before[id] as ZoneNode), { + outer: room.referencePolygon, + holes: room.holes, + }) >= 0.9, + ), + ) + if (!plate) continue + for (const span of room.spans) { + const wall = walls.find((wall) => wall.id === span.boundaryId)! + const endpoints = getWallMiterBoundaryPoints(wall, miters)! + for (let i = 0; i <= 8; i++) { + const t = span.t0 + ((span.t1 - span.t0) * i) / 8 + const start = span.face === 'a' ? endpoints.startLeft : endpoints.startRight + const end = span.face === 'a' ? endpoints.endLeft : endpoints.endRight + const frame = getWallCurveFrameAt(wall, t), + offset = getWallFaceOffsets(wall)[span.face] + const p: [number, number] = wall.curveOffset + ? [frame.point.x + frame.normal.x * offset, frame.point.y + frame.normal.y * offset] + : [start.x + (end.x - start.x) * t, start.y + (end.y - start.y) * t] + if (containsPoint(cutouts, p)) continue + const geometry = stored.map(slabFootprint) + expect( + containsPoint(geometry, p) || distanceToBoundary(geometry, p) <= 0.005, + `${wall.id} ${span.face} ${t}`, + ).toBe(true) + checked++ + } + } + } + expect(checked).toBeGreaterThan(0) + }) +}) diff --git a/packages/core/src/utils/floor-plate-load.test.ts b/packages/core/src/utils/floor-plate-load.test.ts new file mode 100644 index 0000000000..a196146a5a --- /dev/null +++ b/packages/core/src/utils/floor-plate-load.test.ts @@ -0,0 +1,262 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { readdirSync, readFileSync } from 'node:fs' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + ElevatorNode, + LevelNode, + SlabNode, + StairNode, + StairSegmentNode, +} from '../schema' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { initializeElevatorOpeningSync } from '../systems/elevator/elevator-opening-system' +import { initializeStairOpeningSync } from '../systems/stair/stair-opening-system' +import { materializeLegacyAutoOpenings } from './owned-floor-opening-migration' +import { + ensureSceneOpenings, + healSceneNodes, + materializeNodeDefaults, + migrateCeilingRoomLinks, + migrateFloorPlates, + migrateRoomZones, + migrateSlabSlots, + migrateVerticalSceneNodes, + migrateWallFaceBands, + migrateWallFaceKeys, + normalizeLegacyStructure, + reconcileStructureOnLoad, +} from './scene-migrations' + +const directory = new URL('../lib/__fixtures__/plate-corpus/legacy-load/', import.meta.url) +const fixtures = readdirSync(directory) + .filter((file) => file.endsWith('.json')) + .map( + (file) => + JSON.parse(readFileSync(new URL(file, directory), 'utf8')) as { + sceneId: string + levelId: string + rootNodeIds: AnyNodeId[] + nodes: Record + }, + ) +for (const sceneId of ['scene-19', 'scene-10']) { + fixtures.push( + JSON.parse( + readFileSync( + new URL(`../lib/__fixtures__/plate-corpus/frozen-gate/${sceneId}.json`, import.meta.url), + 'utf8', + ), + ), + ) +} +function migrate(source: Record) { + const healed = healSceneNodes(normalizeLegacyStructure(source)).nodes + const vertical = migrateVerticalSceneNodes(healed).nodes + const rooms = migrateRoomZones(vertical).nodes + const ceilings = migrateCeilingRoomLinks(rooms).nodes + const legacyOpeningsPrepared = + Object.values(ceilings).some( + (node) => node.type === 'slab' && node.autoFromWalls && !node.plateRole, + ) && Object.values(ceilings).some((node) => node.type === 'stair' || node.type === 'elevator') + const plates = migrateFloorPlates(materializeLegacyAutoOpenings(ceilings, true)).nodes + const openings = ensureSceneOpenings(migrateSlabSlots(plates).nodes).nodes + return materializeNodeDefaults( + reconcileStructureOnLoad( + migrateWallFaceBands(migrateWallFaceKeys(openings).nodes).nodes, + vertical, + { legacyOpeningsPrepared }, + ).nodes, + ).nodes +} +function geometry(nodes: Record) { + return Object.values(nodes) + .filter((node): node is SlabNode => (node as AnyNode).type === 'slab') + .map( + ({ + id, + polygon, + holes, + holeMetadata, + elevation, + thickness, + recessed = false, + boundary, + zoneIds, + autoFromWalls, + }) => ({ + id, + polygon, + holes, + holeMetadata, + elevation, + thickness, + recessed, + boundary, + zoneIds, + autoFromWalls, + }), + ) + .sort((a, b) => a.id.localeCompare(b.id)) +} +let stopOpenings = () => {} +let previous: ReturnType +const originalRaf = globalThis.requestAnimationFrame +const originalCancelRaf = globalThis.cancelAnimationFrame +beforeEach(() => { + previous = useScene.getState() + globalThis.requestAnimationFrame = (callback) => { + callback(0) + return 0 + } + globalThis.cancelAnimationFrame = () => {} + useScene.setState({ readOnly: false }) + clearSceneHistory() +}) +afterEach(() => { + stopOpenings() + stopOpenings = () => {} + useScene.setState(previous, true) + clearSceneHistory() + globalThis.requestAnimationFrame = originalRaf + globalThis.cancelAnimationFrame = originalCancelRaf +}) + +test.each( + fixtures.flatMap((fixture) => + ['none', 'before', 'after'].map((mount) => ({ ...fixture, mount })), + ), +)('$sceneId loads with opening systems mounted $mount hydration and stable floor geometry', async (fixture) => { + const bytes = JSON.stringify(fixture.nodes) + const server = migrate(fixture.nodes) + expect(JSON.stringify(fixture.nodes)).toBe(bytes) + expect(migrate(server)).toEqual(server) + const mountOpenings = () => { + const stopStair = initializeStairOpeningSync() + const stopElevator = initializeElevatorOpeningSync() + stopOpenings = () => { + stopStair() + stopElevator() + } + } + if (fixture.mount === 'before') mountOpenings() + useScene.getState().setScene(structuredClone(fixture.nodes), fixture.rootNodeIds) + await new Promise((resolve) => queueMicrotask(resolve)) + if (fixture.mount === 'after') { + mountOpenings() + await new Promise((resolve) => queueMicrotask(resolve)) + } + const client = useScene.getState().nodes + expect(geometry(client)).toEqual(geometry(server)) + for (const node of Object.values(server)) { + if (node.type === 'stair-segment') + expect((client[node.id] as StairSegmentNode).height).toBe(node.height) + } + useScene.getState().setScene(client, fixture.rootNodeIds) + await new Promise((resolve) => queueMicrotask(resolve)) + expect(geometry(useScene.getState().nodes)).toEqual(geometry(server)) +}) + +test('missing level children are reconstructed from existing parent links before height migration', () => { + const fixture = fixtures.find(({ sceneId }) => sceneId === 'scene-13')! + const healed = healSceneNodes(fixture.nodes).nodes as Record + expect(healed[fixture.levelId]).toHaveProperty('children') + expect(healSceneNodes(healed).nodes).toEqual(healed) +}) + +test.each([ + 'none', + 'stair', + 'elevator', +] as const)('load ensures missing stair/elevator holes without redrawing existing ones (%s present)', async (present) => { + const building = BuildingNode.parse({}) + const lower = LevelNode.parse({ parentId: building.id, level: 0, height: 3 }) + const upper = LevelNode.parse({ parentId: building.id, level: 1, height: 3 }) + const stair = StairNode.parse({ + parentId: lower.id, + position: [10, 0, 10], + fromLevelId: lower.id, + toLevelId: upper.id, + slabOpeningMode: 'destination', + }) + const segment = StairSegmentNode.parse({ parentId: stair.id, height: 3, length: 4 }) + const elevator = ElevatorNode.parse({ + parentId: building.id, + position: [3, 0, 3], + fromLevelId: lower.id, + toLevelId: upper.id, + }) + const savedHole: [number, number][] = [ + [1.123_456_789, 1], + [2, 1], + [2, 2], + [1.123_456_789, 2], + ] + const slab = SlabNode.parse({ + parentId: upper.id, + polygon: [ + [0, 0], + [20, 0], + [20, 20], + [0, 20], + ], + holes: present === 'none' ? [] : [savedHole], + holeMetadata: + present === 'none' + ? [] + : [ + { + source: present, + ...(present === 'stair' ? { stairId: stair.id } : { elevatorId: elevator.id }), + }, + ], + }) + if (present === 'none') delete (slab as Partial).holes + building.children = [lower.id, upper.id, elevator.id] + const floor = SlabNode.parse({ parentId: lower.id, elevation: 0.4, polygon: slab.polygon }) + lower.children = [stair.id, floor.id] + upper.children = [slab.id] + stair.children = [segment.id] + const nodes = Object.fromEntries( + [building, lower, upper, stair, segment, elevator, slab, floor].map((node) => [node.id, node]), + ) + const before = JSON.stringify(nodes) + const ensured = { nodes: materializeLegacyAutoOpenings(nodes) as Record } + expect(JSON.stringify(nodes)).toBe(before) + expect(materializeLegacyAutoOpenings(ensured.nodes)).toBe(ensured.nodes) + expect(ensured.nodes[slab.id]).toHaveProperty('holes') + useScene.getState().setScene(nodes, [building.id]) + await new Promise((resolve) => queueMicrotask(resolve)) + const result = useScene.getState().nodes[slab.id] as SlabNode + const owned = Object.values(useScene.getState().nodes).filter( + (node) => + node.type === 'floor-opening' && (node.ownerId === stair.id || node.ownerId === elevator.id), + ) + expect(owned.some((node) => node.type === 'floor-opening' && node.ownerId === stair.id)).toBe( + true, + ) + expect(owned.some((node) => node.type === 'floor-opening' && node.ownerId === elevator.id)).toBe( + true, + ) + expect(result.holes).toHaveLength(2) + expect((useScene.getState().nodes[segment.id] as StairSegmentNode).height).toBeCloseTo(2.6) + expect(result.holes).toEqual((ensured.nodes[slab.id] as SlabNode).holes) + expect(result.holeMetadata.every((entry) => entry.source === 'floor-opening')).toBe(true) + if (present !== 'none') { + expect(result.holes[0]).toEqual(savedHole) + expect(result.holeMetadata?.[0]?.openingId).toBeTruthy() + } + const snapshot = JSON.stringify(result) + const stopStair = initializeStairOpeningSync() + const stopElevator = initializeElevatorOpeningSync() + stopOpenings = () => { + stopStair() + stopElevator() + } + await new Promise((resolve) => queueMicrotask(resolve)) + expect(JSON.stringify(useScene.getState().nodes[slab.id])).toBe(snapshot) + useScene.getState().setScene(useScene.getState().nodes, [building.id]) + await new Promise((resolve) => queueMicrotask(resolve)) + expect(JSON.stringify(useScene.getState().nodes[slab.id])).toBe(snapshot) +}) diff --git a/packages/core/src/utils/floor-plate-migration.test.ts b/packages/core/src/utils/floor-plate-migration.test.ts new file mode 100644 index 0000000000..b575d746f4 --- /dev/null +++ b/packages/core/src/utils/floor-plate-migration.test.ts @@ -0,0 +1,640 @@ +import { expect, spyOn, test } from 'bun:test' +import { readdirSync, readFileSync } from 'node:fs' +import { slabFootprint } from '../lib/floor-plates' +import * as footprints from '../lib/level-footprints' +import { plateFootprint } from '../lib/level-footprints' +import { getOpeningFloorDatum } from '../lib/opening-floor-datum' +import * as polygons from '../lib/polygon-boolean' +import { area, difference, union } from '../lib/polygon-boolean' +import { getRenderableSlabPolygon } from '../lib/slab-polygon' +import { createRoomTopologyIndex } from '../lib/space-detection' +import type { AnyNode, ZoneNode } from '../schema' +import { DoorNode, LevelNode, SlabNode, WallNode } from '../schema' +import { + migrateCeilingRoomLinks, + migrateFloorPlates, + migrateRoomZones, + migrateSlabSlots, + reconcileStructureOnLoad, +} from './scene-migrations' + +function prepare(walls: WallNode[]) { + const level = LevelNode.parse({ id: 'level_test', children: walls.map((wall) => wall.id) }) + const nodes = migrateCeilingRoomLinks( + migrateRoomZones(Object.fromEntries([level, ...walls].map((node) => [node.id, node]))).nodes, + ).nodes as Record + const zones = Object.values(nodes).filter((node): node is ZoneNode => node.type === 'zone') + for (const [i, zone] of zones.entries()) { + const slab = SlabNode.parse({ + id: `slab_source_${i}`, + parentId: level.id, + polygon: zone.polygon, + holes: zone.holes, + holeMetadata: zone.holes.map(() => ({ source: 'room' })), + autoFromWalls: true, + slots: { surface: `library:finish-${i}`, side: 'library:concrete' }, + }) + nodes[slab.id] = slab + ;(nodes[level.id] as LevelNode).children.push(slab.id) + } + return { nodes, zones } +} +function twoRooms() { + const ring: [number, number][] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ] + return prepare([ + ...ring.map((start, i) => + WallNode.parse({ + id: `wall_${i}`, + parentId: 'level_test', + start, + end: ring[(i + 1) % 4], + thickness: 0.2, + }), + ), + WallNode.parse({ + id: 'wall_divider', + parentId: 'level_test', + start: [2, 0], + end: [2, 4], + thickness: 0.2, + }), + ]) +} +function slabs(nodes: Record) { + return Object.values(nodes).filter((node): node is SlabNode => (node as AnyNode).type === 'slab') +} + +test('one complete manual slab spanning rooms becomes one owned floor volume', () => { + const { nodes, zones } = twoRooms() + for (const slab of slabs(nodes)) { + delete nodes[slab.id] + ;(nodes.level_test as LevelNode).children = (nodes.level_test as LevelNode).children.filter( + (id) => id !== slab.id, + ) + } + const shared = SlabNode.parse({ + id: 'slab_shared_manual', + parentId: 'level_test', + polygon: [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ], + slots: { surface: 'library:shared-floor' }, + }) + nodes[shared.id] = shared + ;(nodes.level_test as LevelNode).children.push(shared.id) + const first = reconcileStructureOnLoad(migrateFloorPlates(nodes).nodes, nodes).nodes + expect(slabs(first)).toHaveLength(1) + expect(first[shared.id]).toMatchObject({ + plateRole: 'base', + zoneIds: zones.map((zone) => zone.id).sort(), + }) + for (const zone of zones) { + const room = first[zone.id] as ZoneNode + expect(room.floor?.sourceSlabId).toBeUndefined() + expect(room.floor?.finish).toBe('library:shared-floor') + } + expect(reconcileStructureOnLoad(first).nodes).toEqual(first) +}) + +test('load clears a missing floor supplier so the room can regain its floor', () => { + const { nodes, zones } = twoRooms() + const room = zones[0]! + nodes[room.id] = { + ...room, + floor: { ...room.floor, sourceSlabId: 'slab_missing_supplier' }, + } + const migrated = migrateFloorPlates(nodes).nodes + expect((migrated[room.id] as ZoneNode).floor?.sourceSlabId).toBeUndefined() + const loaded = reconcileStructureOnLoad(migrated).nodes + expect( + slabs(loaded).some((slab) => slab.plateRole === 'base' && slab.zoneIds?.includes(room.id)), + ).toBe(true) + expect(migrateFloorPlates(migrated).nodes).toBe(migrated) + expect(reconcileStructureOnLoad(loaded).nodes).toEqual(loaded) +}) + +test('a small legacy auto slab remains the room supplier without growing into a new floor', () => { + const { nodes, zones } = twoRooms() + const room = zones[0]! + const source = slabs(nodes).find( + (slab) => JSON.stringify(slab.polygon) === JSON.stringify(room.polygon), + )! + const cx = room.polygon.reduce((sum, [x]) => sum + x, 0) / room.polygon.length + const cz = room.polygon.reduce((sum, [, z]) => sum + z, 0) / room.polygon.length + nodes[source.id] = { + ...source, + polygon: [ + [cx - 0.5, cz - 0.5], + [cx + 0.5, cz - 0.5], + [cx + 0.5, cz + 0.5], + [cx - 0.5, cz + 0.5], + ], + } + const first = migrateFloorPlates(nodes).nodes + expect((first[room.id] as ZoneNode).hasFloor).not.toBe(false) + expect((first[room.id] as ZoneNode).floor?.sourceSlabId).toBe(source.id) + expect(first[source.id]).toMatchObject({ + autoFromWalls: false, + polygon: (nodes[source.id] as SlabNode).polygon, + }) + expect( + slabs(first).some((slab) => slab.plateRole === 'base' && slab.zoneIds?.includes(room.id)), + ).toBe(false) + expect(migrateFloorPlates(first).nodes).toBe(first) +}) + +test('an outside deck under one wall does not lift the migrated footprint above its rooms', () => { + const { nodes, zones } = twoRooms() + const deck = SlabNode.parse({ + id: 'slab_outside_deck', + parentId: 'level_test', + polygon: [ + [7.9, 0.5], + [8.5, 0.5], + [8.5, 3.5], + [7.9, 3.5], + ], + elevation: 0.5, + }) + const door = DoorNode.parse({ + id: 'door_equal_floors', + parentId: 'wall_divider', + position: [2, 1, 0], + height: 2, + width: 0.8, + }) + nodes[deck.id] = deck + nodes[door.id] = door + nodes.wall_divider = { ...nodes.wall_divider, children: [door.id] } as WallNode + ;(nodes.level_test as LevelNode).children.push(deck.id) + const load = (source: Record) => + reconcileStructureOnLoad(migrateFloorPlates(source).nodes, source).nodes + const first = load(nodes) + expect(slabs(first).find((slab) => slab.plateRole === 'base')?.elevation).toBeCloseTo(0.05) + expect(slabs(first).filter((slab) => slab.plateRole && slab.plateRole !== 'base')).toEqual([]) + for (const zone of zones) expect((first[zone.id] as ZoneNode).floor?.elevation).toBeCloseTo(0.05) + expect(getOpeningFloorDatum(first.wall_divider as WallNode, door, first)).toBeCloseTo(0.05) + expect(slabs(first).every((slab) => slab.floorHeight === undefined)).toBe(true) + expect(load(first)).toEqual(first) +}) + +test('reloading an unchanged room preserves fractional finish-region coordinates', () => { + const { nodes, zones } = twoRooms() + const first = reconcileStructureOnLoad(migrateFloorPlates(nodes).nodes, nodes).nodes + const zone = first[zones[0]!.id] as ZoneNode + const x = Math.min(...zone.polygon.map(([x]) => x)) + 1 / 3 + const regions = [ + { + id: 'fractional-finish', + polygon: [ + [x, 1], + [x + 1 / 3, 1], + [x + 1 / 3, 2], + [x, 2], + ] as [number, number][], + finish: 'library:tile', + }, + ] + const painted = { ...first, [zone.id]: { ...zone, floor: { ...zone.floor, regions } } } + const loaded = reconcileStructureOnLoad(painted).nodes + expect((loaded[zone.id] as ZoneNode).floor?.regions).toEqual(regions) + expect(reconcileStructureOnLoad(loaded).nodes).toEqual(loaded) +}) + +test('M4/M5 are pure, deterministic and idempotent; finishes, holes and hosts survive', () => { + const { nodes, zones } = twoRooms() + const sources = slabs(nodes) + nodes.wall_0 = { ...nodes.wall_0, supportSlabId: sources[0]!.id } as AnyNode + nodes.stair_ref = { id: 'stair_ref', type: 'stair', deckSlabId: sources[1]!.id } as AnyNode + const minX = Math.min(...sources[0]!.polygon.map(([x]) => x)) + const hole: [number, number][] = [ + [minX + 0.5, 1], + [minX + 1, 1], + [minX + 1, 2], + [minX + 0.5, 2], + ] + nodes[sources[0]!.id] = { + ...sources[0]!, + holes: [hole], + holeMetadata: [{ source: 'stair', stairId: 'stair_ref' }], + } + const bytes = JSON.stringify(nodes) + const first = migrateFloorPlates(nodes) + expect(JSON.stringify(nodes)).toBe(bytes) + expect(migrateFloorPlates(Object.fromEntries(Object.entries(nodes).reverse()))).toEqual(first) + expect(migrateFloorPlates(first.nodes).nodes).toBe(first.nodes) + const plate = slabs(first.nodes)[0]! + expect(slabs(first.nodes)).toHaveLength(1) + expect(plate.slots?.surface).toBe( + sources.reduce((largest, source) => + area([slabFootprint(source)]) > area([slabFootprint(largest)]) ? source : largest, + ).slots!.surface, + ) + expect(plate.zoneIds).toEqual(zones.map((zone) => zone.id).sort()) + expect(plate.holeMetadata).toEqual([{ source: 'stair', stairId: 'stair_ref' }]) + expect(first.nodes.wall_0).toMatchObject({ supportSlabId: plate.id }) + expect((first.nodes.stair_ref as { deckSlabId?: string }).deckSlabId).toBeUndefined() + sources.forEach((source, i) => { + if (source.id !== plate.id) expect(first.nodes[source.id]).toBeUndefined() + else expect(first.nodes[source.id]).toMatchObject({ plateRole: 'base' }) + expect(first.nodes[zones[i]!.id]).toMatchObject({ floor: { finish: source.slots!.surface } }) + }) + const slots = migrateSlabSlots(first.nodes) + expect(slabs(slots.nodes)[0]!.slots).toMatchObject({ + edge: 'library:concrete', + riser: 'library:concrete', + underside: 'library:concrete', + }) + expect(migrateSlabSlots(slots.nodes).nodes).toBe(slots.nodes) +}) + +test.each([ + 'elevation', + 'thickness', + 'fillToTerrain', +] as const)('legacy %s keeps its wall support or derives one base', (field) => { + const { nodes } = twoRooms() + const source = slabs(nodes)[0]! + nodes[source.id] = { + ...source, + [field]: field === 'elevation' || field === 'thickness' ? 0.4 : true, + } + const result = migrateFloorPlates(nodes) + expect(slabs(result.nodes)).toHaveLength(field === 'elevation' ? 2 : 1) + if (field === 'elevation') { + expect(result.nodes[source.id]).toMatchObject({ + elevation: 0.4, + autoFromWalls: false, + polygon: source.polygon, + }) + expect(slabs(result.nodes).some((slab) => slab.plateRole === 'base')).toBe(false) + } else + expect(slabs(result.nodes).find((slab) => slab.plateRole === 'base')?.zoneIds).toHaveLength(2) + expect(migrateFloorPlates(result.nodes).nodes).toBe(result.nodes) +}) + +test('hand-split floor becomes a finish region; a raised platform stays manual', () => { + const { nodes, zones } = twoRooms() + const zone = zones[0]! + const manual = SlabNode.parse({ + id: 'slab_manual', + parentId: 'level_test', + polygon: zone.polygon, + elevation: 0.07, + slots: { surface: 'library:tile' }, + }) + const raised = { ...manual, id: 'slab_raised' as const, elevation: 0.4 } + nodes[manual.id] = manual + nodes[raised.id] = raised + ;(nodes.level_test as LevelNode).children.push(manual.id, raised.id) + const result = migrateFloorPlates(nodes) + expect(result.nodes[manual.id]).toBeUndefined() + expect(result.nodes[raised.id]).toMatchObject(raised) + expect((result.nodes[raised.id] as SlabNode).associatedZoneIds).toContain(zone.id) + expect(result.nodes[zone.id]).toMatchObject({ + floor: { regions: [{ id: manual.id, polygon: manual.polygon, finish: 'library:tile' }] }, + }) + expect((result.nodes.level_test as LevelNode).children).not.toContain(manual.id) +}) + +test('M5 preserves explicit new slots', () => { + const slab = SlabNode.parse({ + id: 'slab_slots', + polygon: [], + slots: { side: 'old', edge: 'new' }, + }) + expect((migrateSlabSlots({ [slab.id]: slab }).nodes[slab.id] as SlabNode).slots).toEqual({ + side: 'old', + edge: 'new', + riser: 'old', + underside: 'old', + }) +}) + +const corpus = new URL('../lib/__fixtures__/plate-corpus/', import.meta.url) +for (const file of readdirSync(corpus).filter((name) => name.endsWith('.json'))) { + test(`M4 corpus ${file}: level union area, deterministic ids and idempotence`, () => { + const geometry = JSON.parse(readFileSync(new URL(file, corpus), 'utf8')) as Partial[] + const walls = geometry.map((wall, i) => + WallNode.parse({ ...wall, id: `wall_${i}`, parentId: 'level_test' }), + ) + const { nodes } = prepare(walls) + const before = slabs(nodes) + const legacy = union( + before.map((slab) => ({ + outer: getRenderableSlabPolygon(slab, { + walls, + siblingSlabs: before.filter((other) => other.id !== slab.id), + }), + holes: slab.holes, + })), + ) + const topology = createRoomTopologyIndex() + topology.rebuild(nodes) + const rooms = topology.getLevelTopology('level_test')!.rooms + const fullBefore = union(rooms.flatMap((room) => plateFootprint([room]))) + const wallFootprints = union([...rooms[0]!.context.wallFootprints.values()]) + const result = migrateFloorPlates(nodes) + const migratedSlabs = slabs(result.nodes) + const migrated = union( + migratedSlabs.map((slab) => ({ + outer: getRenderableSlabPolygon(slab, { + walls, + siblingSlabs: migratedSlabs.filter((other) => other.id !== slab.id), + }), + holes: slab.holes, + })), + ) + // A retained authored floor keeps its original extent; derived footprints fill the wall bands. + const expectedFootprint = slabs(result.nodes).some((slab) => slab.plateRole) + ? fullBefore + : legacy + expect( + Math.abs(area(migrated) - area(expectedFootprint)) / area(expectedFootprint), + ).toBeLessThan(0.01) + const visibleBefore = difference(legacy, wallFootprints) + const visibleAfter = difference(migrated, wallFootprints) + const visibleChange = + area(difference(visibleAfter, visibleBefore)) + area(difference(visibleBefore, visibleAfter)) + expect(visibleChange / area(visibleBefore)).toBeLessThan(0.01) + expect(migrateFloorPlates(result.nodes).nodes).toBe(result.nodes) + expect( + migrateFloorPlates(Object.fromEntries(Object.entries(nodes).reverse())).plateIds, + ).toEqual(result.plateIds) + }) +} + +test('manual finish regions preserve cutouts and inline material references', () => { + const { nodes, zones } = twoRooms() + const room = zones[0]! + const minX = Math.min(...room.polygon.map(([x]) => x)) + const manual = SlabNode.parse({ + id: 'slab_cutout', + parentId: 'level_test', + polygon: room.polygon, + holes: [ + [ + [minX + 0.5, 1], + [minX + 1, 1], + [minX + 1, 2], + [minX + 0.5, 2], + ], + ], + material: { properties: { color: '#123456' } }, + }) + nodes[manual.id] = manual + const result = migrateFloorPlates(nodes) + const regions = (result.nodes[room.id] as ZoneNode).floor!.regions! + expect(area(union(regions.map((region) => region.polygon)))).toBeCloseTo( + area([slabFootprint(manual)]), + ) + expect(regions[0]!.finish).toEqual(manual.material) + expect(result.nodes[manual.id]).toBeUndefined() + const plate = slabs(result.nodes).find((slab) => slab.boundary === 'auto')! + expect(plate.holes).toEqual([]) + expect(plate.holeMetadata).toEqual([]) + expect(slabs(result.nodes).some((slab) => slab.autoFromWalls === false)).toBe(false) +}) + +test('M4 retains suppressed legacy sources as manual construction when no plate replaces them', () => { + const { nodes, zones } = twoRooms() + const sources = slabs(nodes) + const manual = SlabNode.parse({ + id: 'slab_cover', + parentId: 'level_test', + polygon: [ + [-1, -1], + [9, -1], + [9, 5], + [-1, 5], + ], + elevation: 0.4, + }) + nodes[manual.id] = manual + nodes.wall_0 = { ...nodes.wall_0, supportSlabId: sources[0]!.id } as AnyNode + const result = migrateFloorPlates(nodes) + expect(slabs(result.nodes).filter((slab) => slab.plateRole !== 'base')).toHaveLength( + sources.length + 1, + ) + expect(result.nodes[manual.id]).toMatchObject(manual) + expect((result.nodes[manual.id] as SlabNode).associatedZoneIds).toEqual( + zones.map((zone) => zone.id).sort(), + ) + for (const source of sources) { + expect(result.nodes[source.id]).toMatchObject({ + autoFromWalls: false, + polygon: source.polygon, + metadata: { plateMigration: { demoted: 'manual-coverage' } }, + }) + } + expect((result.nodes.wall_0 as WallNode).supportSlabId).toBe(sources[0]!.id) + expect(migrateFloorPlates(result.nodes).nodes).toBe(result.nodes) +}) + +test('M4 rolls back a failing level, warns once, and leaves its legacy slabs and finishes intact', () => { + const { nodes } = twoRooms() + const failing = Object.fromEntries( + Object.entries(nodes).map(([id, node]) => [ + id === 'level_test' ? 'level_failure_m4' : id, + node.type === 'level' + ? { ...node, id: 'level_failure_m4' } + : { ...node, parentId: 'level_failure_m4' }, + ]), + ) + const bytes = JSON.stringify(failing) + const warning = spyOn(console, 'warn').mockImplementation(() => {}) + const clip = spyOn(footprints, 'plateFootprint').mockImplementation(() => { + throw new Error('fixture union failure') + }) + try { + const first = migrateFloorPlates(failing).nodes + expect(first).toMatchObject(migrateSlabSlots(failing).nodes) + expect(migrateFloorPlates(first).nodes).toBe(first) + expect(JSON.stringify(failing)).toBe(bytes) + expect( + warning.mock.calls.filter( + ([message]) => message === '[floor plates] Keeping existing level construction', + ), + ).toHaveLength(1) + } finally { + clip.mockRestore() + warning.mockRestore() + } +}) + +test('a curved finish extending beyond the floor remains separate construction', () => { + const polygon: [number, number][] = [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ] + const { nodes, zones } = prepare( + polygon.map((start, i) => + WallNode.parse({ + id: `wall_curved_${i}`, + parentId: 'level_test', + start, + end: polygon[(i + 1) % 4], + curveOffset: i === 0 ? 0.4 : 0, + }), + ), + ) + const zone = zones[0]! + const near = SlabNode.parse({ + id: 'slab_nearly_inside', + parentId: 'level_test', + polygon: zone.polygon.map(([x, z]) => [x, z + 0.0001]), + slots: { surface: 'library:tile' }, + }) + const pool = SlabNode.parse({ + ...near, + id: 'slab_pool', + recessed: true, + polygon: [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], + ], + }) + nodes[near.id] = near + nodes[pool.id] = pool + const result = migrateFloorPlates(nodes) + expect(result.nodes[near.id]).toMatchObject({ autoFromWalls: false }) + expect(result.nodes[pool.id]).toBe(pool) +}) + +test('M5 preserves side repaint across reload without overwriting explicit classified slots', () => { + const slab = SlabNode.parse({ id: 'slab_repaint', polygon: [], slots: { side: 'scene:old' } }) + const migrated = migrateSlabSlots({ [slab.id]: slab }).nodes[slab.id] as SlabNode + const painted = { ...migrated, slots: { ...migrated.slots, side: 'scene:new' } } + const nodes = { [slab.id]: painted } + expect(migrateSlabSlots(nodes).nodes).toBe(nodes) + expect(painted.slots).toMatchObject({ + side: 'scene:new', + edge: 'scene:old', + riser: 'scene:old', + underside: 'scene:old', + }) +}) + +test('hasFloor false demotes its legacy floor without generating a plate for that room', () => { + const { nodes, zones } = twoRooms() + const zone = zones[0]! + const source = slabs(nodes).find( + (slab) => JSON.stringify(slab.polygon) === JSON.stringify(zone.polygon), + )! + nodes[zone.id] = { ...zone, hasFloor: false } + const after = migrateFloorPlates(nodes).nodes + expect(after[source.id]).toEqual({ + ...(migrateSlabSlots({ [source.id]: source }).nodes[source.id] as SlabNode), + autoFromWalls: false, + associatedZoneIds: [zone.id], + metadata: { ...source.metadata, plateMigration: { demoted: 'has-floor-disabled' } }, + }) + expect( + slabs(after) + .filter((slab) => slab.boundary === 'auto') + .flatMap((slab) => slab.zoneIds!), + ).not.toContain(zone.id) + expect(migrateFloorPlates(after).nodes).toBe(after) +}) + +test('M4 keeps an entire matched source when only an unrelated manual slab covers its residual', () => { + const { nodes, zones } = twoRooms() + const source = slabs(nodes).find((slab) => Math.min(...slab.polygon.map(([x]) => x)) === 0)! + const extended = { + ...source, + metadata: { authored: true }, + polygon: source.polygon.map(([x, z]): [number, number] => [x === 0 ? -1 : x, z]), + } + nodes[source.id] = extended + const manual = SlabNode.parse({ + id: 'slab_residual_cover', + parentId: 'level_test', + polygon: [ + [-1, 0], + [0, 0], + [0, 4], + [-1, 4], + ], + }) + nodes[manual.id] = manual + nodes.wall_0 = { ...nodes.wall_0, supportSlabId: source.id } as AnyNode + const result = migrateFloorPlates(nodes) + expect(result.plateIds).toEqual([]) + expect(result.nodes[source.id]).toMatchObject({ + autoFromWalls: false, + associatedZoneIds: [zones.find((zone) => Math.min(...zone.polygon.map(([x]) => x)) === 0)!.id], + metadata: { authored: true, plateMigration: { demoted: expect.any(String) } }, + }) + expect(result.nodes[manual.id]).toMatchObject(manual) + expect((result.nodes[manual.id] as SlabNode).associatedZoneIds).toEqual([]) + expect((result.nodes.wall_0 as WallNode).supportSlabId).toBe(source.id) + expect(migrateFloorPlates(result.nodes).nodes).toBe(result.nodes) +}) + +test('M4 preserves sources and records a reason when coverage normalization fails', () => { + const { nodes } = twoRooms() + const sources = slabs(nodes) + const original = polygons.difference + const clipping = spyOn(polygons, 'difference').mockImplementation((a, b, options) => { + if (options?.throwOnError && Array.isArray(b) && b.length === 0) + throw new Error('fixture coverage failure') + return original(a, b, options) + }) + try { + const result = migrateFloorPlates(nodes) + expect(result.plateIds.length).toBeGreaterThan(0) + for (const source of sources) + expect(result.nodes[source.id]).toEqual({ + ...(migrateSlabSlots({ [source.id]: source }).nodes[source.id] as SlabNode), + autoFromWalls: false, + associatedZoneIds: Object.values(result.nodes) + .filter( + (node): node is ZoneNode => + node.type === 'zone' && + area(polygons.intersection(slabFootprint(node), slabFootprint(source))) > 1e-4, + ) + .map((zone) => zone.id) + .sort(), + metadata: { ...source.metadata, plateMigration: { demoted: 'coverage-error' } }, + }) + expect(migrateFloorPlates(result.nodes).nodes).toBe(result.nodes) + } finally { + clipping.mockRestore() + } +}) + +test('legacy mezzanine fascia moves to its zone edge finish and the second load is identical', () => { + const { nodes, zones } = twoRooms() + const zone = zones[0]! + const plate = + Object.values(nodes).find( + (node): node is SlabNode => node.type === 'slab' && node.polygon === zone.polygon, + ) ?? Object.values(nodes).find((node): node is SlabNode => node.type === 'slab')! + nodes[zone.id] = { ...zone, floor: { support: 'open', elevation: 1.5, thickness: 0.2 } } + nodes[plate.id] = { + ...plate, + boundary: 'auto', + support: 'open', + zoneIds: [zone.id], + elevation: 1.5, + slots: { side: 'library:legacy-fascia', surface: 'library:legacy-deck' }, + } + const result = migrateFloorPlates(nodes) + expect(result.nodes[zone.id]).toMatchObject({ + floorEdgeFinish: 'library:legacy-fascia', + floor: { finish: 'library:legacy-deck' }, + }) + expect(migrateFloorPlates(result.nodes).nodes).toEqual(result.nodes) +}) diff --git a/packages/core/src/utils/floor-plate-migration.ts b/packages/core/src/utils/floor-plate-migration.ts new file mode 100644 index 0000000000..6bd72fba78 --- /dev/null +++ b/packages/core/src/utils/floor-plate-migration.ts @@ -0,0 +1,1625 @@ +import { isFloorAnchoredOpening } from '../lib/floor-opening-footprints' +import { floorPlateId } from '../lib/floor-plate-id' +import { + buildFloorPlates, + footprintIoU, + type PlateRoom, + parseSlabConstruction, + slabFootprint, + warnPlateFailure, +} from '../lib/floor-plates' +import { floorRoomFaces } from '../lib/floor-room-faces' +import { plateFootprint } from '../lib/level-footprints' +import { getOpeningFloorDatum, wallSupportForNodes } from '../lib/opening-floor-datum' +import { replacementPlateFor } from '../lib/plate-reference' +import { computePlateSurfacePartition } from '../lib/plate-surface' +import { + area, + containsPoint, + difference, + distanceToBoundary, + intersection, + type MultiPolygon, + type Ring, + union, +} from '../lib/polygon-boolean' +import { autoRoomVerticalPlacements } from '../lib/room-vertical-placement' +import { getRenderableSlabPolygon, prepareSlabPolygonContext } from '../lib/slab-polygon' +import type { AnyNode, SeparatorNode, WallNode, ZoneNode } from '../schema' +import { DEFAULT_SLAB_ELEVATION, type SlabNode } from '../schema/nodes/slab' +import { getStoredLevelHeight } from '../services/storey' +import { wallOverlapsSlabFootprint } from '../systems/slab/slab-support' +import { getWallCurveLength } from '../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { resolveWallTop } from '../systems/wall/wall-top' +import { + type FloorPieceAdoption, + floorPieceFinish, + PIECE_GAP_WIDTH, + PIECE_TRIM_DEPTH, + partWidth, + planFloorPieceAdoption, +} from './floor-piece-adoption' +import { legacyWallElevations } from './legacy-wall-datums' +import { omitUndefined } from './omit-undefined' + +export type FloorPlateMigrationReport = { + code: 'floor-moved' | 'finish-not-visible' | 'region-limit' | 'floor-pieces-absorbed' + nodeId: string + finish?: unknown + /** floor-pieces-absorbed: the hand-drawn slabs one generated plate replaced. */ + pieces?: string[] + /** floor-pieces-absorbed: visible floor dropped past the walls / narrow gaps closed (m²). */ + trimmed?: number + closed?: number + /** floor-pieces-absorbed: uncovered room floor kept open as plate holes. */ + holes?: number +} + +function visibleFloorTopAreas(slabs: SlabNode[], walls: Ring[]) { + let covered = union(walls) + const tops = new Map() + for (const slab of [...slabs].sort((a, b) => b.elevation - a.elevation)) { + if (slab.visible === false || slab.support === 'open' || slab.recessed) continue + const footprint = difference( + { outer: slab.polygon, holes: [] }, + union((slab.holes ?? []).map((hole) => ({ outer: hole, holes: [] }))), + ) + const visible = difference(footprint, covered) + const top = Math.round(slab.elevation * 1000) / 1000 + tops.set(top, (tops.get(top) ?? 0) + area(visible)) + covered = union([...covered, ...footprint]) + } + return tops +} + +function visibleFloorTopChange(before: SlabNode[], after: SlabNode[], walls: Ring[]) { + const old = visibleFloorTopAreas(before, walls) + const next = visibleFloorTopAreas(after, walls) + for (const [oldTop] of old) + for (const [nextTop, nextArea] of next) { + if (Math.abs(oldTop - nextTop) > 0.02 + 1e-9) continue + const oldArea = old.get(oldTop)! + const shared = Math.min(oldArea, nextArea) + old.set(oldTop, oldArea - shared) + next.set(nextTop, nextArea - shared) + if (old.get(oldTop)! <= 1e-6) break + } + return Math.min( + [...old.values()].reduce((sum, value) => sum + value, 0), + [...next.values()].reduce((sum, value) => sum + value, 0), + ) +} + +export function associateLegacyManualFloors( + source: Record, + legacy: Readonly> = source, + finalize = true, +) { + const bounds = (ring: Ring) => ({ + minX: Math.min(...ring.map(([x]) => x)), + maxX: Math.max(...ring.map(([x]) => x)), + minZ: Math.min(...ring.map(([, z]) => z)), + maxZ: Math.max(...ring.map(([, z]) => z)), + }) + const nearby = (a: ReturnType, b: ReturnType) => + a.minX < b.maxX && b.minX < a.maxX && a.minZ < b.maxZ && b.minZ < a.maxZ + let nodes = source + for (const level of Object.values(source)) { + if (level.type !== 'level' || level.metadata?.floorOwnershipMigrated === true) continue + const children = Object.values(source).filter((node) => node.parentId === level.id) + const authored = children.filter( + (node): node is SlabNode => + node.type === 'slab' && + !node.autoFromWalls && + node.boundary !== 'auto' && + node.support !== 'open' && + !node.recessed, + ) + const manual = union(authored.map(slabFootprint)) + const original = Object.values(legacy).filter( + (node): node is SlabNode => + node.type === 'slab' && + node.parentId === level.id && + node.visible !== false && + node.support !== 'open' && + !node.recessed, + ) + const originalFaces = original.map((slab) => ({ + slab, + footprint: slabFootprint(slab), + coverageFootprint: { + outer: slab.polygon, + holes: (slab.holes ?? []).filter( + (_, index) => + slab.holeMetadata?.[index]?.source !== 'stair' && + slab.holeMetadata?.[index]?.source !== 'elevator', + ), + }, + bounds: bounds(slab.polygon), + })) + const rooms = children.filter( + (node): node is ZoneNode => node.type === 'zone' && node.spaceRole === 'room', + ) + const wallBand = + Math.max( + 0, + ...children + .filter((node) => node.type === 'wall') + .map((wall) => (wall.thickness ?? 0.1) / 2), + ) + 0.005 + for (const slab of authored) { + const associatedZoneIds = rooms + .filter((room) => area(intersection(slabFootprint(room), slabFootprint(slab))) > 1e-4) + .map((room) => room.id) + .sort() + if (JSON.stringify(slab.associatedZoneIds) === JSON.stringify(associatedZoneIds)) continue + if (nodes === source) nodes = { ...source } + nodes[slab.id] = { ...slab, associatedZoneIds } + } + for (const zone of children) { + if ( + zone.type !== 'zone' || + zone.spaceRole !== 'room' || + zone.hasFloor === false || + zone.floor?.support === 'open' || + zone.floor?.sourceSlabId + ) + continue + const face = slabFootprint(zone) + const faceArea = area([face]) + if (faceArea <= 0) continue + const faceBounds = bounds(zone.polygon) + const originalOverlaps = originalFaces + .filter((entry) => nearby(faceBounds, entry.bounds)) + .map((entry) => ({ + ...entry, + overlap: intersection(face, entry.coverageFootprint), + })) + const supportArea = area(union(originalOverlaps.flatMap((entry) => entry.overlap))) + if (supportArea <= 1e-4) { + if (nodes === source) nodes = { ...source } + nodes[zone.id] = { ...zone, hasFloor: false } + continue + } + const nearWholeAutoPlate = originalOverlaps.some((entry) => { + const plateBounds = entry.bounds + return ( + entry.slab.autoFromWalls && + area(entry.overlap) >= faceArea * 0.8 && + Math.abs(plateBounds.minX - faceBounds.minX) <= wallBand && + Math.abs(plateBounds.maxX - faceBounds.maxX) <= wallBand && + Math.abs(plateBounds.minZ - faceBounds.minZ) <= wallBand && + Math.abs(plateBounds.maxZ - faceBounds.maxZ) <= wallBand + ) + }) + if ( + !nearWholeAutoPlate && + supportArea > 1e-4 && + faceArea - supportArea > Math.max(0.02, faceArea * 0.01) + ) { + const provider = originalOverlaps + .filter((entry) => area(entry.overlap) > 1e-4) + .sort( + (a, b) => + b.slab.elevation - a.slab.elevation || + area(b.overlap) - area(a.overlap) || + a.slab.id.localeCompare(b.slab.id), + )[0]?.slab + // A partial provider that became a generated plate supplies no authored floor. + if (provider && !(nodes[provider.id] as SlabNode | undefined)?.plateRole) { + if (nodes === source) nodes = { ...source } + nodes[zone.id] = { ...zone, floor: { ...zone.floor, sourceSlabId: provider.id } } + } + continue + } + if (area(intersection(face, manual)) <= 1e-4) continue + const provider = authored + .filter((slab) => nearby(faceBounds, bounds(slab.polygon))) + .map((slab) => ({ slab, overlap: area(intersection(face, slabFootprint(slab))) })) + .filter( + ({ slab, overlap }) => + overlap >= faceArea * 0.05 || + (overlap > 1e-4 && + (slab.metadata?.plateMigration as { demoted?: string } | undefined)?.demoted !== + undefined), + ) + .sort( + (a, b) => + b.slab.elevation - a.slab.elevation || + b.overlap - a.overlap || + a.slab.id.localeCompare(b.slab.id), + )[0]?.slab + if (!provider) continue + const providerCoverage = area(intersection(face, slabFootprint(provider))) + const automaticCover = originalFaces + .filter((entry) => entry.slab.autoFromWalls && nearby(faceBounds, entry.bounds)) + .reduce((best, entry) => Math.max(best, area(intersection(face, entry.footprint))), 0) + if (automaticCover >= faceArea * 0.95 && providerCoverage < faceArea * 0.95) continue + const finishOnly = + (provider.metadata?.plateMigration as { demoted?: string } | undefined)?.demoted === + undefined && + providerCoverage >= faceArea * 0.95 && + Object.values(legacy).some( + (node) => + node.type === 'slab' && + node.parentId === level.id && + node.autoFromWalls && + Math.abs(node.elevation - provider.elevation) <= 0.02 + 1e-9 && + provider.thickness <= node.thickness + 0.02 + 1e-9 && + area(difference(slabFootprint(provider), slabFootprint(node))) <= + Math.max(1e-6, area([slabFootprint(provider)]) * 0.01), + ) + if (finishOnly) continue + if (nodes === source) nodes = { ...source } + nodes[zone.id] = { ...zone, floor: { ...zone.floor, sourceSlabId: provider.id } } + } + if (finalize) { + if (nodes === source) nodes = { ...source } + const hadLegacyAutoPlate = Object.values(legacy).some( + (node) => + node.type === 'slab' && + node.parentId === level.id && + node.autoFromWalls && + !node.plateRole, + ) + nodes[level.id] = { + ...level, + metadata: { + ...level.metadata, + floorOwnershipMigrated: true, + ...(hadLegacyAutoPlate ? { legacyAutoOpeningsMigrated: true } : {}), + }, + } + } + } + return nodes +} + +function convertLegacyFinishSlabs(source: Record) { + let nodes = source + const slabs = Object.values(source).filter((node): node is SlabNode => node.type === 'slab') + for (const slab of slabs) { + if ( + slab.autoFromWalls || + slab.boundary === 'auto' || + slab.plateRole || + slab.support === 'open' || + slab.recessed || + slab.visible === false || + slab.holes?.length || + !slab.parentId + ) + continue + const finish = slab.slots?.surface ?? slab.material ?? slab.materialPreset + if (finish === undefined) continue + if ( + Object.values(source).some( + (node) => + node.id !== slab.id && + ((node as { supportSlabId?: string }).supportSlabId === slab.id || + (node as { deckSlabId?: string }).deckSlabId === slab.id), + ) + ) + continue + const footprint = slabFootprint(slab) + const auto = slabs.filter( + (other) => + other.parentId === slab.parentId && + (other.autoFromWalls || other.boundary === 'auto') && + !other.plateRole && + Math.abs(other.elevation - slab.elevation) <= 0.02 + 1e-9 && + slab.thickness <= other.thickness + 0.02 + 1e-9, + ) + if (!auto.length || area(difference(footprint, union(auto.map(slabFootprint)))) > 1e-4) continue + const rooms = Object.values(nodes).filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.parentId === slab.parentId && + node.spaceRole === 'room' && + node.hasFloor !== false, + ) + const pieces = rooms.flatMap((room) => + intersection(footprint, slabFootprint(room)).map((part) => ({ room, part })), + ) + if ( + pieces.some(({ part }) => part.holes.length) || + area(difference(footprint, union(pieces.map(({ part }) => part)))) > 1e-4 + ) + continue + if (nodes === source) nodes = { ...source } + for (const room of rooms) { + const regions = pieces + .filter((piece) => piece.room.id === room.id) + .map(({ part }, index) => ({ + id: pieces.length === 1 ? slab.id : `${slab.id}_${room.id}_${index}`, + polygon: part.outer, + finish, + })) + if (!regions.length) continue + const { sourceSlabId, ...floor } = room.floor ?? {} + nodes[room.id] = { + ...room, + floor: { + ...floor, + ...(sourceSlabId && sourceSlabId !== slab.id ? { sourceSlabId } : {}), + regions: [...(floor.regions ?? []), ...regions], + }, + } + } + const level = nodes[slab.parentId] + if (level?.type === 'level') + nodes[level.id] = { ...level, children: level.children.filter((id) => id !== slab.id) } + delete nodes[slab.id] + } + return nodes +} + +function absorbCompleteManualFloors(source: Record) { + let nodes = source + const slabs = Object.values(source).filter((node): node is SlabNode => node.type === 'slab') + for (const slab of slabs) { + if ( + slab.autoFromWalls || + slab.boundary === 'auto' || + slab.plateRole || + slab.support === 'open' || + slab.recessed || + slab.visible === false || + (slab.metadata?.plateMigration as { demoted?: string } | undefined)?.demoted !== undefined || + !slab.parentId + ) + continue + const rooms = Object.values(source).filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.parentId === slab.parentId && + node.spaceRole === 'room' && + node.floor?.sourceSlabId === slab.id, + ) + if (!rooms.length || rooms.length !== slab.associatedZoneIds?.length) continue + const levelSlabs = slabs.filter((other) => other.parentId === slab.parentId) + const levelRooms = Object.values(source).filter( + (node): node is ZoneNode => + node.type === 'zone' && node.parentId === slab.parentId && node.spaceRole === 'room', + ) + const completeLevel = + levelRooms.length > 0 && + levelSlabs.every( + (other) => + !other.autoFromWalls && + other.boundary !== 'auto' && + !other.plateRole && + !other.recessed && + Math.abs(other.elevation - slab.elevation) <= 1e-6 && + Math.abs(other.thickness - slab.thickness) <= 1e-6 && + levelRooms.some((room) => room.floor?.sourceSlabId === other.id), + ) && + levelRooms.every((room) => levelSlabs.some((other) => room.floor?.sourceSlabId === other.id)) + if (!completeLevel) continue + if ( + rooms.some( + (room) => + room.floor?.elevation !== undefined && + Math.abs(room.floor.elevation - slab.elevation) > 0.02 + 1e-9, + ) || + slabs.some( + (other) => + other.id !== slab.id && + other.parentId === slab.parentId && + area(intersection(slabFootprint(other), slabFootprint(slab))) > 1e-4, + ) + ) + continue + const footprint = union(rooms.map(slabFootprint)) + const outside = { outer: slab.polygon, holes: [] } + const tolerance = Math.max(1e-4, area([outside]) * 1e-4) + try { + if ( + area(difference(outside, footprint, { throwOnError: true })) > tolerance || + area(difference(footprint, outside, { throwOnError: true })) > tolerance + ) + continue + } catch { + continue + } + if (nodes === source) nodes = { ...source } + nodes[slab.id] = { + ...parseSlabConstruction(slab), + boundary: 'auto', + plateRole: 'base', + autoFromWalls: true, + zoneIds: rooms.map((room) => room.id).sort(), + associatedZoneIds: undefined, + referenceFloorElevation: slab.elevation, + foundation: slab.fillToTerrain ? { type: 'solid' } : { type: 'none' }, + fillToTerrain: undefined, + } + for (const room of rooms) { + const { sourceSlabId: _sourceSlabId, ...floor } = room.floor ?? {} + nodes[room.id] = { + ...room, + floor: { + ...floor, + elevation: floor.elevation ?? slab.elevation, + finish: floor.finish ?? slab.slots?.surface ?? slab.material ?? slab.materialPreset, + }, + } + } + } + return nodes +} + +function clearDanglingFloorSources(nodes: Record) { + let changed = false + for (const zone of Object.values(nodes)) { + if (zone.type !== 'zone' || !zone.floor?.sourceSlabId) continue + if (nodes[zone.floor.sourceSlabId]?.type === 'slab') continue + const { sourceSlabId: _missing, ...floor } = zone.floor + nodes[zone.id] = { ...zone, floor } + changed = true + } + return changed +} + +/** A level whose hand-drawn floor pieces cannot be adopted exactly: migrate it without them. */ +class AdoptionRejected extends Error {} + +export function migrateFloorPlates(sourceNodes: Record) { + // Adoption is all-or-nothing per level: a level whose pieces are not all + // consumed migrates exactly as it would without adoption. + const skip = new Set() + for (;;) { + const adoption = planFloorPieceAdoption(sourceNodes as Record, skip) + const result = runFloorPlateMigration(sourceNodes, adoption) + const failed = [...adoption.levels.keys()].filter((levelId) => + [...adoption.pieces].some( + ([id, level]) => + level === levelId && + (result.nodes[id] as SlabNode | undefined)?.type === 'slab' && + !(result.nodes[id] as SlabNode).plateRole, + ), + ) + if (!failed.length) return result + for (const levelId of failed) skip.add(levelId) + } +} + +function runFloorPlateMigration( + sourceNodes: Record, + adoption: FloorPieceAdoption, +) { + const slotMigration = migrateSlabSlots(sourceNodes) + const nodes = { ...slotMigration.nodes } as Record + for (const id of adoption.pieces.keys()) + nodes[id] = { ...(nodes[id] as SlabNode), autoFromWalls: true } + const plateIds: string[] = [] + const reports: FloorPlateMigrationReport[] = [] + const remap = new Map() + let changed = slotMigration.changed + if (clearDanglingFloorSources(nodes)) changed = true + for (const level of Object.values(nodes)) { + if (level.type !== 'level' || !level.metadata?.legacyRoomMigrationPending) continue + if (Object.values(nodes).some((node) => node.type === 'slab' && node.parentId === level.id)) + continue + for (const zone of Object.values(nodes)) { + if (zone.type !== 'zone' || zone.parentId !== level.id || zone.hasFloor !== undefined) + continue + nodes[zone.id] = { ...zone, hasFloor: false } + changed = true + } + } + for (const source of Object.values(nodes)) { + if (source.type !== 'slab' || !Object.hasOwn(source, 'legacyFloor')) continue + const { legacyFloor, ...plate } = source as typeof source & { legacyFloor?: number } + nodes[source.id] = { + ...plate, + referenceFloorElevation: plate.referenceFloorElevation ?? legacyFloor, + } as SlabNode + changed = true + } + if ( + Object.values(nodes).some((node) => node.type === 'slab' && !node.plateRole) && + !Object.values(nodes).some((node) => node.type === 'slab' && node.plateRole) + ) { + const converted = convertLegacyFinishSlabs(nodes) + if (converted !== nodes) { + Object.assign(nodes, converted) + for (const id of Object.keys(nodes)) if (!(id in converted)) delete nodes[id] + changed = true + } + // Adopted pieces are still hand-drawn history: they neither mark legacy + // wall-generated openings nor hold back the level's finalisation. + const history = adoption.pieces.size + ? Object.fromEntries( + Object.entries(nodes).map(([id, node]) => [ + id, + adoption.pieces.has(id) ? { ...(node as SlabNode), autoFromWalls: false } : node, + ]), + ) + : nodes + const associated = associateLegacyManualFloors( + nodes, + history, + !Object.values(nodes).some( + (node) => + node.type === 'slab' && + node.autoFromWalls && + !node.plateRole && + !adoption.pieces.has(node.id), + ), + ) + if (associated !== nodes) { + Object.assign(nodes, associated) + changed = true + } + const absorbed = absorbCompleteManualFloors(nodes) + if (absorbed !== nodes) { + Object.assign(nodes, absorbed) + changed = true + } + } + for (const level of Object.values(nodes)) { + if (level.type !== 'level' || !Object.hasOwn(level, 'floorElevation')) continue + const { floorElevation, ...clean } = level as typeof level & { floorElevation?: number } + nodes[level.id] = clean + for (const plate of Object.values(nodes)) + if ( + plate.type === 'slab' && + plate.parentId === level.id && + (plate.plateRole === 'base' || + (!plate.plateRole && + plate.support !== 'open' && + (plate.autoFromWalls || plate.boundary === 'auto'))) + ) + nodes[plate.id] = { ...plate, floorHeight: floorElevation ?? plate.floorHeight } + changed = true + } + for (const plate of Object.values(nodes)) { + if (plate.type !== 'slab' || plate.plateRole !== 'base') continue + if (!plate.foundation || Object.hasOwn(plate, 'fillToTerrain')) { + const { fillToTerrain, ...clean } = plate + nodes[plate.id] = { + ...clean, + foundation: plate.foundation ?? { + type: fillToTerrain ? 'solid' : 'none', + ...(fillToTerrain + ? { material: plate.slots?.edge ?? plate.slots?.side ?? '#cccccc' } + : {}), + }, + } as SlabNode + changed = true + } + } + for (const plate of Object.values(nodes)) { + if (plate.type !== 'slab' || plate.support !== 'open' || plate.boundary !== 'auto') continue + for (const id of plate.zoneIds ?? []) { + const zone = nodes[id] + if (zone?.type !== 'zone') continue + const floorEdgeFinish = zone.floorEdgeFinish ?? plate.slots?.edge + const finish = + zone.floor?.finish ?? plate.slots?.surface ?? plate.material ?? plate.materialPreset + if (floorEdgeFinish === zone.floorEdgeFinish && finish === zone.floor?.finish) continue + nodes[id] = { + ...zone, + ...(floorEdgeFinish === undefined ? {} : { floorEdgeFinish }), + ...(finish === undefined ? {} : { floor: { ...zone.floor, finish } }), + } + changed = true + } + } + for (const level of Object.values(nodes) + .filter((node) => node.type === 'level') + .sort((a, b) => a.level - b.level || a.id.localeCompare(b.id))) { + const children = Object.values(nodes) + .filter((node) => node.parentId === level.id) + .sort((a, b) => a.id.localeCompare(b.id)) + if ( + !children.some( + (node) => + node.type === 'slab' && + (node.autoFromWalls || node.boundary === 'auto') && + !node.plateRole && + node.support !== 'open', + ) + ) + continue + const beforeNodes = { ...nodes } + const beforeRemap = new Map(remap) + const beforePlateCount = plateIds.length + const beforeChanged: boolean = changed + try { + const recessed = children.filter( + (node) => node.type === 'slab' && node.autoFromWalls && !node.boundary && node.recessed, + ) + if (recessed.length) + warnPlateFailure( + level.id, + recessed.map((node) => node.id), + 'recessed-legacy: preserved verbatim', + ) + const demotionReasons = new Map() + const demoteUnmatched = (reason?: string) => { + for (const node of children) { + if ( + node.type !== 'slab' || + (!node.autoFromWalls && node.boundary !== 'auto') || + node.recessed || + !nodes[node.id] || + (nodes[node.id] as SlabNode).plateRole + ) + continue + // Unmatched legacy geometry is authored construction, not a room generator. + nodes[node.id] = { + ...nodes[node.id], + autoFromWalls: false, + boundary: undefined, + metadata: { + ...node.metadata, + plateMigration: { + demoted: + demotionReasons.get(node.id) === 'has-floor-disabled' + ? 'has-floor-disabled' + : (reason ?? demotionReasons.get(node.id)!), + }, + }, + } as SlabNode + changed = true + } + } + const adopted = adoption.levels.get(level.id) + const reject = () => { + if (adopted) throw new AdoptionRejected() + } + const legacy = children + .filter( + (node): node is SlabNode => + node.type === 'slab' && + (node.autoFromWalls || node.boundary === 'auto') && + !node.plateRole && + node.support !== 'open' && + !node.recessed, + ) + .map((node) => parseSlabConstruction(node)) + if (!legacy.length) continue + const walls = children.filter((node): node is WallNode => node.type === 'wall') + const separators = children.filter((node): node is SeparatorNode => node.type === 'separator') + const zones = children.filter( + (node): node is ZoneNode => + node.type === 'zone' && + node.spaceRole === 'room' && + node.enclosureStatus !== 'open' && + node.floor?.support !== 'open', + ) + const faces = floorRoomFaces([...walls, ...separators]) + const boundsOf = (ring: Ring) => ({ + minX: Math.min(...ring.map(([x]) => x)), + maxX: Math.max(...ring.map(([x]) => x)), + minZ: Math.min(...ring.map(([, z]) => z)), + maxZ: Math.max(...ring.map(([, z]) => z)), + }) + const intersectsBounds = (a: ReturnType, b: ReturnType) => + a.minX <= b.maxX && b.minX <= a.maxX && a.minZ <= b.maxZ && b.minZ <= a.maxZ + const boundedFaces = faces.map((face) => ({ + face, + bounds: boundsOf(face.referencePolygon), + })) + const boundedLegacy = legacy.map((slab) => ({ slab, bounds: boundsOf(slab.polygon) })) + const miters = calculateLevelMiters(walls) + const context = { + revision: 0, + walls: new Map(walls.map((wall) => [wall.id, wall])), + wallFootprints: new Map( + walls.map((wall) => [ + wall.id, + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ]), + ), + } + const allSlabs = children.filter((node): node is SlabNode => node.type === 'slab') + const manualCoverage = union( + allSlabs + .filter((slab) => !slab.autoFromWalls && slab.boundary !== 'auto') + .map(slabFootprint), + ) + for (const slab of legacy) { + const surface = union([slabFootprint(slab)]) + const disabled = zones.some( + (zone) => + zone.hasFloor === false && + footprintIoU(slabFootprint(zone), slabFootprint(slab)) >= 0.6, + ) + demotionReasons.set( + slab.id, + disabled + ? 'has-floor-disabled' + : area(surface) > 0 && + area(intersection(surface, manualCoverage)) >= area(surface) * 0.6 + ? 'manual-coverage' + : faces.length + ? walls.some((wall) => wall.curveOffset) + ? 'curved-face-mismatch' + : 'stale-or-unmatched-straight' + : 'no-detected-room', + ) + } + const linked = new Set( + allSlabs + .filter((slab) => slab.boundary === 'auto' && slab.plateRole) + .flatMap((slab) => slab.zoneIds ?? []), + ) + const wallArea = union([...context.wallFootprints.values()]) + const renderContext = prepareSlabPolygonContext({ walls, siblingSlabs: allSlabs }) + const renderedSlabs = new Map( + allSlabs.map((slab) => [slab.id, getRenderableSlabPolygon(slab, renderContext)]), + ) + const legacySurfaces = new Map( + legacy.map((slab) => [ + slab.id, + { + outer: renderedSlabs.get(slab.id)!, + holes: [], + }, + ]), + ) + const sources = new Map() + const rooms: PlateRoom[] = [] + for (const zone of zones) { + if (linked.has(zone.id)) continue + const zoneFootprint = slabFootprint(zone) + const zoneBounds = boundsOf(zone.polygon) + const face = boundedFaces + .filter((entry) => intersectsBounds(zoneBounds, entry.bounds)) + .map(({ face }) => ({ + face, + iou: footprintIoU(zoneFootprint, { + outer: face.referencePolygon, + holes: face.holes, + }), + })) + .sort((a, b) => b.iou - a.iou)[0] + if (!face || face.iou < 0.9 || zone.hasFloor === false) continue + const candidates = boundedLegacy + .filter((entry) => intersectsBounds(zoneBounds, entry.bounds)) + .map(({ slab }) => ({ + slab, + overlap: area(intersection(slabFootprint(slab), zoneFootprint)), + iou: footprintIoU(slabFootprint(slab), zoneFootprint), + })) + .filter(({ overlap }) => overlap > 0) + .sort( + (a, b) => b.overlap - a.overlap || b.iou - a.iou || a.slab.id.localeCompare(b.slab.id), + ) + const source = candidates[0]?.slab + const boundaryWalls = union( + [...new Set(face.face.spans.map((span) => span.boundaryId))].flatMap((id) => + context.wallFootprints.has(id) ? [context.wallFootprints.get(id)!] : [], + ), + ) + let clear = union([slabFootprint(zone)]) + try { + clear = difference(clear, boundaryWalls, { throwOnError: true }) + } catch { + // If wall subtraction fails, require coverage of the entire reference + // face instead of treating a clipping failure as an empty room. + } + if (!clear.length) continue + // A stale/sliver slab overlap is not evidence that this whole face had a floor. + // Subtract only nearby surfaces: unioning every legacy slab can fail on + // distant self-intersections and incorrectly suppress otherwise valid rooms. + const uncovered = candidates.reduce((remaining, { slab }) => { + try { + return difference(remaining, legacySurfaces.get(slab.id)!, { throwOnError: true }) + } catch { + return remaining + } + }, clear) + const open = adopted?.voids.length + ? difference(uncovered, union(adopted.voids.map((ring) => ({ outer: ring, holes: [] })))) + : uncovered + if (area(open) > Math.max(1e-6, area(clear) * 0.01)) continue + const recessed = allSlabs.some( + (slab) => + slab.recessed && + area(intersection({ outer: slab.polygon, holes: [] }, clear)) >= area(clear) * 0.6, + ) + if (recessed) continue + if (!source) continue + const floor = { ...zone.floor } + // Partial cover by a piece is an open void in the plate, not an authored floor. + if (adopted && legacy.some((slab) => slab.id === floor.sourceSlabId)) + delete floor.sourceSlabId + const finish = source.slots?.surface ?? source.material ?? source.materialPreset + if (finish !== undefined && floor.finish === undefined) floor.finish = finish + // Keep legacy F even when it matches this room's automatic datum: + // the connected footprint can inherit a higher automatic datum. + if (floor.elevation === undefined) floor.elevation = source.elevation + const updated = Object.keys(floor).length ? { ...zone, floor } : zone + nodes[zone.id] = updated + sources.set(zone.id, source) + rooms.push({ + id: zone.id, + zone: updated, + polygon: face.face.referencePolygon, + holes: face.face.holes, + spans: face.face.spans, + context, + }) + } + if (!rooms.length) { + reject() + demoteUnmatched() + continue + } + // Legacy support uses rendered slabs, without the new room-face datums. + const oldSupports = legacyWallElevations(walls, allSlabs, beforeNodes, level.id) + const derived = autoRoomVerticalPlacements(rooms, nodes) + const defaultFloor = derived.size ? Math.max(...derived.values()) : DEFAULT_SLAB_ELEVATION + const componentFloors = new Map() + const referenceFloors = new Map() + for (const component of plateFootprint(rooms)) { + const members = rooms.filter( + (room) => area(intersection(slabFootprint(room), component)) > 0, + ) + const inherited = members + .map((room) => sources.get(room.id)?.floorHeight) + .find((height) => height !== undefined) + const boundaryIds = new Set( + members.flatMap((room) => room.spans.map((span) => span.boundaryId)), + ) + // The footprint keeps the floor height most of its floor area had (on a + // tie, the one the walls give anyway). The wall-derived datum can differ + // (a pad under one wall, an authored slab height); re-deriving it sinks + // the other rooms and lifts walls onto a band with a gap under it. + const grounded = members.filter((room) => !room.zone.floor?.sourceSlabId) + const automatic = grounded.length + ? Math.max(...grounded.map((room) => derived.get(room.zone.id) ?? DEFAULT_SLAB_ELEVATION)) + : undefined + const candidates = new Map() + for (const room of grounded) { + const source = sources.get(room.id) + if (!source) continue + const floor = Math.round(source.elevation * 1e6) / 1e6 + const entry = candidates.get(floor) ?? { area: 0, thickness: source.thickness } + entry.area += area([slabFootprint(room)]) + entry.thickness = Math.max(entry.thickness, source.thickness) + candidates.set(floor, entry) + } + const largest = Math.max(0, ...[...candidates.values()].map((entry) => entry.area)) + const [referenceFloor] = + [...candidates] + .filter(([, entry]) => entry.area >= largest * 0.99) + .sort( + ([a], [b]) => + Math.abs(a - (automatic ?? a)) - Math.abs(b - (automatic ?? b)) || a - b, + )[0] ?? [] + if ( + inherited === undefined && + referenceFloor !== undefined && + automatic !== undefined && + Math.abs(referenceFloor - automatic) > 0.005 + ) + for (const room of grounded) { + const source = sources.get(room.id) + if (source) referenceFloors.set(source.id, referenceFloor) + } + const weights = new Map() + for (const wall of walls) { + if (!boundaryIds.has(wall.id)) continue + const support = oldSupports.get(wall.id)! + const elevation = Math.round((support.elevation - (wall.supportOffset ?? 0)) * 1e6) / 1e6 + weights.set(elevation, (weights.get(elevation) ?? 0) + getWallCurveLength(wall)) + } + const height = + inherited ?? + [...weights].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]?.[0] ?? + defaultFloor + for (const room of members) componentFloors.set(room.id, height) + } + for (const room of rooms) { + const levelFloor = componentFloors.get(room.id) ?? defaultFloor + if (Math.abs((sources.get(room.id)?.elevation ?? levelFloor) - levelFloor) > 0.005) + reports.push({ code: 'floor-moved', nodeId: room.id }) + } + const preserveWallSupportedLegacy = () => { + reject() + for (const room of rooms) { + const source = sources.get(room.id) + if (!source) continue + const zone = nodes[room.id] as ZoneNode + nodes[room.id] = { ...zone, floor: { ...zone.floor, sourceSlabId: source.id } } + } + demoteUnmatched('wall-supported-floor') + } + const supportedSources = new Set( + [...oldSupports.values()].flatMap((support) => + support.electedSlabId ? [support.electedSlabId] : [], + ), + ) + if ( + rooms.some( + (room) => + room.zone.autoFromWalls && + supportedSources.has(sources.get(room.id)?.id ?? '') && + (sources.get(room.id)?.elevation ?? 0) > + (componentFloors.get(room.id) ?? defaultFloor) + 0.005, + ) + ) { + preserveWallSupportedLegacy() + continue + } + const converted = legacy + .filter((slab) => [...sources.values()].some((source) => source.id === slab.id)) + .map((slab) => ({ + ...slab, + boundary: 'auto' as const, + floorHeight: slab.floorHeight, + referenceFloorElevation: referenceFloors.get(slab.id), + foundation: slab.foundation ?? { + type: slab.fillToTerrain ? ('solid' as const) : ('none' as const), + ...(slab.fillToTerrain + ? { material: slab.slots?.edge ?? slab.slots?.side ?? '#cccccc' } + : {}), + }, + zoneIds: rooms + .filter((room) => sources.get(room.id)?.id === slab.id) + .map((room) => room.id), + })) + // Finish overlays must be consumed before manual coverage can suppress their room. + const regions = new Set() + const sourceCoverage = union(converted.map(slabFootprint)) + for (const node of children) { + if (node.type !== 'slab' || node.autoFromWalls || node.boundary === 'auto' || node.recessed) + continue + const slab = parseSlabConstruction(node) + const surface = union([slabFootprint(slab)]) + // A manual floor filling an opening in the old construction is structural, + // not a finish overlay; deleting it would expose that opening. + if (area(difference(surface, sourceCoverage)) > Math.max(1e-6, area(surface) * 0.01)) + continue + const room = rooms.find( + ({ zone }) => + Math.abs(slab.elevation - (zone.floor?.elevation ?? DEFAULT_SLAB_ELEVATION)) <= + 0.02 + 1e-9 && + area(intersection(surface, slabFootprint(zone))) >= area(surface) * (1 - 1e-3), + ) + if (!room) continue + const finish = + slab.slots?.surface ?? slab.material ?? slab.materialPreset ?? 'library:wood-woodplank48' + const polygon = slabFootprint(slab) + const xs = [...new Set(slab.holes.flatMap((hole) => hole.map(([x]) => x)))].sort( + (a, b) => a - b, + ) + const minX = Math.min(...slab.polygon.map(([x]) => x)) + const maxX = Math.max(...slab.polygon.map(([x]) => x)) + const minZ = Math.min(...slab.polygon.map(([, z]) => z)) + const maxZ = Math.max(...slab.polygon.map(([, z]) => z)) + const cuts = [...new Set([minX, ...xs, maxX])].sort((a, b) => a - b) + const regionPolygons = slab.holes.length + ? cuts.slice(1).flatMap((x, i) => + intersection(polygon, [ + [cuts[i]!, minZ], + [x, minZ], + [x, maxZ], + [cuts[i]!, maxZ], + ] as Ring).map((part) => part.outer), + ) + : [slab.polygon] + const zone = nodes[room.id] as ZoneNode + nodes[zone.id] = { + ...zone, + floor: { + ...zone.floor, + regions: [ + ...(zone.floor?.regions ?? []), + ...regionPolygons.map((polygon, i) => ({ + id: i ? `${slab.id}_${i}` : slab.id, + polygon, + finish, + })), + ], + }, + } + regions.add(slab.id) + remap.set(slab.id, sources.get(room.id)!.id) + } + const plan = buildFloorPlates({ + levelId: level.id, + nodes: Object.fromEntries(Object.entries(nodes).filter(([id]) => !regions.has(id))), + rooms, + slabs: [ + ...converted, + ...children + .filter( + (node): node is SlabNode => + node.type === 'slab' && + !node.autoFromWalls && + node.boundary !== 'auto' && + !regions.has(node.id), + ) + .map((slab) => parseSlabConstruction(slab)), + ], + mintId: (ids, component, role) => floorPlateId(level.id, role ?? 'base', ids, component), + renderedManualCuts: false, + }) + for (const source of converted) { + for (const [index, hole] of (source.holes ?? []).entries()) { + const holeArea = area([{ outer: hole, holes: [] }]) + if (holeArea < 1e-4) continue + const plateIndex = plan.plates.findIndex( + (plate) => + Math.abs(plate.elevation - source.elevation) <= 1e-6 && + area(intersection(hole, slabFootprint(plate))) >= holeArea - 1e-4, + ) + if (plateIndex < 0) continue + const plate = plan.plates[plateIndex]! + if ( + plate.holes.some( + (existing) => + area(intersection(existing, hole)) >= holeArea - 1e-4 && + Math.abs(area([{ outer: existing, holes: [] }]) - holeArea) <= 1e-4, + ) + ) + continue + plan.plates[plateIndex] = { + ...plate, + holes: [...plate.holes, hole], + holeMetadata: [ + ...plate.holeMetadata, + source.holeMetadata?.[index] ?? { source: 'manual' }, + ], + } + } + } + const expandsLegacySource = plan.plates.some((plate) => { + const source = legacySurfaces.get(plate.id) + if (!source) return false + const added = area(difference(slabFootprint(plate), [source])) + return area([source]) < 5 && added > Math.max(10, area([source]) * 5) + }) + if (expandsLegacySource) { + reject() + demoteUnmatched('excess-plate-extent') + continue + } + const retained = allSlabs.filter( + (slab) => !legacy.some((source) => source.id === slab.id) && !regions.has(slab.id), + ) + const retainedConstruction = retained.filter( + (slab) => slab.visible !== false && slab.support !== 'open' && !slab.recessed, + ) + if (retainedConstruction.length) { + const retainedFootprint = union( + retainedConstruction.map((slab) => ({ + outer: renderedSlabs.get(slab.id)!, + holes: slab.holes, + })), + ) + const oldOverlap = intersection( + retainedFootprint, + union(legacy.map((slab) => legacySurfaces.get(slab.id)!)), + ) + const newOverlap = intersection(retainedFootprint, union(plan.plates.map(slabFootprint))) + if (area(difference(newOverlap, oldOverlap)) > 1e-4) { + preserveWallSupportedLegacy() + continue + } + const nextRenderContext = prepareSlabPolygonContext({ + walls, + siblingSlabs: [...retained, ...plan.plates], + }) + if ( + retainedConstruction.some((slab) => { + if (slab.boundary === 'auto') return false + const before = renderedSlabs.get(slab.id)! + const after = getRenderableSlabPolygon(slab, nextRenderContext) + return area(difference(before, after)) + area(difference(after, before)) > 1e-4 + }) + ) { + preserveWallSupportedLegacy() + continue + } + } + const wallSupports = new Set( + [...oldSupports.values()].flatMap((support) => + support.electedSlabId ? [support.electedSlabId] : [], + ), + ) + if ( + rooms.some((room) => room.zone.autoFromWalls) && + (plan.plates.some( + (plate) => + plate.plateRole !== 'base' && + wallSupports.has(plate.id) && + legacy.some((source) => source.id === plate.id), + ) || + walls.some((wall) => { + const sourceId = oldSupports.get(wall.id)?.electedSlabId + if (!sourceId || !legacy.some((source) => source.id === sourceId)) return false + const next = plan.plates.find((plate) => plate.id === sourceId) + return next !== undefined && !wallOverlapsSlabFootprint(wall, next.polygon, next.holes) + })) + ) { + preserveWallSupportedLegacy() + continue + } + const nextSlabs = [...retained, ...plan.plates] + const visibleTops = (slabs: SlabNode[]) => + new Set( + slabs + .filter((slab) => slab.visible !== false && slab.support !== 'open' && !slab.recessed) + .map((slab) => Math.round(slab.elevation * 1000)), + ) + const oldTops = visibleTops(allSlabs) + const newTops = visibleTops(nextSlabs) + const sameSingleTop = + oldTops.size === 1 && + newTops.size === 1 && + Math.abs([...oldTops][0]! - [...newTops][0]!) <= 20 + if ( + !sameSingleTop && + visibleFloorTopChange(allSlabs, nextSlabs, [...context.wallFootprints.values()]) > 0.05 + ) { + for (const room of rooms) { + const source = sources.get(room.id) + if (!source) continue + const zone = nodes[room.id] as ZoneNode + nodes[room.id] = { ...zone, floor: { ...zone.floor, sourceSlabId: source.id } } + } + reject() + demoteUnmatched('visible-floor-top') + continue + } + const oldFloor = union( + allSlabs.map((slab) => ({ + outer: renderedSlabs.get(slab.id)!, + holes: slab.holes ?? [], + })), + ) + const nextFloor = () => + union([ + ...retained.map((slab) => ({ + outer: renderedSlabs.get(slab.id)!, + holes: slab.holes ?? [], + })), + ...plan.plates.map(slabFootprint), + ]) + // A hidden wall hides no floor: pieces are compared on what is seen. + const seenWalls = adopted + ? union( + walls + .filter((wall) => wall.visible !== false) + .map((wall) => ({ outer: context.wallFootprints.get(wall.id)!, holes: [] })), + ) + : wallArea + const visibleBefore = difference(oldFloor, seenWalls) + let visibleAfter = difference(nextFloor(), seenWalls) + // Hand-drawn pieces: floor the plate would add stays open (a hole) unless + // it is a narrow drawing gap; floor it drops must be a thin strip drawn + // past the walls, outside every room. + let trimmed: MultiPolygon = [] + let voidHoles = 0 + // No measurable old floor (invalid piece geometry): nothing proves the plate matches it. + if (adopted && !oldFloor.length) reject() + if (adopted) { + for (const part of difference(visibleAfter, visibleBefore)) { + if (area([part]) <= 1e-4 || partWidth(part) <= PIECE_GAP_WIDTH + 1e-9) continue + const plate = plan.plates.find( + (candidate) => + candidate.plateRole === 'base' && + area(difference(part, slabFootprint(candidate))) <= 1e-6, + ) + // A hole survives re-derivation; a notch in the plate's outline would not. + if ( + !plate || + part.holes.length || + part.outer.some( + (point) => distanceToBoundary([{ outer: plate.polygon, holes: [] }], point) <= 1e-3, + ) + ) + reject() + plate!.holes = [...plate!.holes, part.outer] + plate!.holeMetadata = [...plate!.holeMetadata, { source: 'manual' }] + voidHoles++ + } + visibleAfter = difference(nextFloor(), seenWalls) + const kept = union([...visibleAfter, ...seenWalls]) + const roomArea = union(zones.map(slabFootprint)) + trimmed = difference(visibleBefore, visibleAfter).filter((part) => area([part]) > 1e-6) + for (const part of trimmed) + if ( + area(intersection(part, roomArea)) > 1e-4 || + partWidth(part) > PIECE_TRIM_DEPTH || + part.outer.some( + (point) => + !containsPoint(kept, point) && + distanceToBoundary(kept, point) > PIECE_TRIM_DEPTH + 1e-6, + ) + ) + reject() + if ( + area(difference(visibleAfter, visibleBefore)) > Math.max(1e-4, area(visibleBefore) * 0.02) + ) + reject() + } else if ( + oldFloor.length && + (area(difference(visibleAfter, visibleBefore)) > 1e-4 || + area(difference(visibleBefore, visibleAfter)) > 1e-4) + ) { + preserveWallSupportedLegacy() + continue + } + for (const [component, plate] of plan.plates.entries()) { + const source = converted.find((source) => source.id === plate.id) + if (!source) continue + let preservesSource = false + try { + const original = difference(slabFootprint(source), [], { throwOnError: true }) + const visibleSource = difference( + { ...legacySurfaces.get(source.id)!, holes: source.holes }, + wallArea, + { throwOnError: true }, + ) + preservesSource = [original, visibleSource].every( + (surface) => + area( + difference(surface, union(plan.plates.map(slabFootprint)), { throwOnError: true }), + ) <= Math.max(1e-6, area(surface) * 0.01), + ) + } catch { + demotionReasons.set(source.id, 'coverage-error') + } + if (!preservesSource) { + const id = floorPlateId( + level.id, + plate.plateRole ?? 'open', + plate.zoneIds ?? [], + component, + ) + plan.remap.set(source.id, id) + plate.id = id as SlabNode['id'] + } + } + const generated = new Map() + for (const plate of plan.plates) { + const id = plate.id + const majority = converted + .map((source) => ({ + source, + area: area(intersection(slabFootprint(source), slabFootprint(plate))), + })) + .sort((a, b) => b.area - a.area || a.source.id.localeCompare(b.source.id))[0]?.source + // An unfinished piece showed the default slab top; its room must not + // inherit another piece's finish through the plate's own surface. + const surface = + adopted && + rooms.some( + (room) => + plate.zoneIds?.includes(room.id as ZoneNode['id']) && + (nodes[room.id] as ZoneNode).floor?.finish === undefined, + ) + ? undefined + : majority + const slots = { ...plate.slots } + delete slots.surface + if (surface?.slots?.surface) slots.surface = surface.slots.surface + nodes[id] = { + ...plate, + id, + // A hand-drawn floor's top was authored, not derived from support. + ...(plate.plateRole === 'base' && + plate.referenceFloorElevation === undefined && + (adopted || Math.abs(plate.elevation - DEFAULT_SLAB_ELEVATION) > 0.02) + ? { referenceFloorElevation: plate.elevation } + : {}), + slots: plate.plateRole === 'base' || plate.support === 'open' ? slots : undefined, + material: surface?.material, + materialPreset: surface?.materialPreset, + } + changed = true + plateIds.push(id) + generated.set(plate.id, id) + } + const partitionContext = { + walls, + zones: rooms.map((room) => nodes[room.id] as ZoneNode), + slabs: plan.plates, + openings: Object.values(nodes).filter( + (node): node is import('../schema').DoorNode | import('../schema').WindowNode => + node.type === 'door' || node.type === 'window', + ), + } + const needsSidePaint = [...sources.values()].some( + (source) => source.slots?.riser || source.slots?.edge, + ) + const migratedSides = needsSidePaint + ? plan.plates.flatMap( + (plate) => computePlateSurfacePartition(plate, partitionContext)?.sides ?? [], + ) + : [] + for (const room of rooms) { + const source = sources.get(room.id) + if (!source) continue + const sides = migratedSides.filter((side) => side.zoneId === room.id) + const zone = nodes[room.id] as ZoneNode + nodes[room.id] = { + ...zone, + ...(zone.floorStepFinish === undefined && + source.slots?.riser && + sides.some((s) => s.role === 'riser') + ? { floorStepFinish: source.slots.riser } + : {}), + ...(zone.floorEdgeFinish === undefined && + source.slots?.edge && + sides.some((s) => s.role === 'edge') + ? { floorEdgeFinish: source.slots.edge } + : {}), + } + } + for (const source of converted) { + if (plan.plates.some((plate) => plate.id === source.id)) continue + const replacements = adopted + ? plan.plates + : plan.plates.filter((plate) => plate.zoneIds?.some((id) => source.zoneIds.includes(id))) + const replacementCoverage = union(replacements.map(slabFootprint)) + // Stale slabs can extend beyond every current room. Keep that authored + // surface until its remaining area can be represented, rather than erase it. + let covered = false + let reason = replacements.length ? 'matched-source-residual' : 'manual-coverage' + try { + const original = difference(slabFootprint(source), [], { throwOnError: true }) + const visibleSource = difference( + { ...legacySurfaces.get(source.id)!, holes: source.holes }, + wallArea, + { throwOnError: true }, + ) + covered = adopted + ? area(difference(difference(visibleSource, replacementCoverage), trimmed)) <= 1e-4 + : [original, visibleSource].every( + (surface) => + area(difference(surface, replacementCoverage, { throwOnError: true })) <= + Math.max(1e-6, area(surface) * 0.01), + ) + } catch { + // A failed coverage calculation cannot justify deleting stored construction. + reason = 'coverage-error' + } + if (!covered) { + demotionReasons.set(source.id, reason) + continue + } + const target = generated.get(source.id) ?? generated.get(plan.remap.get(source.id) ?? '') + remap.set(source.id, target) + delete nodes[source.id] + changed = true + } + if (adopted) { + const cover = union(plan.plates.map(slabFootprint)) + for (const [id, levelId] of adoption.pieces) { + if (levelId !== level.id || !nodes[id] || generated.has(id)) continue + // A piece no room took as its source (a finish laid on another piece). + const surface = difference( + { outer: renderedSlabs.get(id as SlabNode['id'])!, holes: [] }, + wallArea, + ) + if (area(difference(difference(surface, cover), trimmed)) > 1e-4) reject() + const [target] = plan.plates + .map((plate) => ({ plate, overlap: area(intersection(surface, slabFootprint(plate))) })) + .sort((a, b) => b.overlap - a.overlap || a.plate.id.localeCompare(b.plate.id)) + remap.set(id, target?.plate.id) + delete nodes[id] + changed = true + } + const finishOf = (slab: SlabNode) => JSON.stringify(floorPieceFinish(slab) ?? null) + for (const room of rooms) { + const zone = nodes[room.id] as ZoneNode + const own = JSON.stringify(zone.floor?.finish ?? null) + const same = union( + legacy + .filter((slab) => finishOf(slab) === own) + .map((slab) => ({ outer: renderedSlabs.get(slab.id)!, holes: [] })), + ) + const regions = legacy.flatMap((slab) => { + const finish = floorPieceFinish(slab) + if (finish === undefined || finishOf(slab) === own) return [] + const parts = difference( + intersection({ outer: renderedSlabs.get(slab.id)!, holes: [] }, slabFootprint(zone)), + same, + ).filter((part) => area([part]) > 0.01 && partWidth(part) > PIECE_GAP_WIDTH) + return parts.map((part, i) => ({ + id: `${slab.id}_${room.id}${i ? `_${i}` : ''}`, + polygon: part.outer, + finish, + })) + }) + if (regions.length) + nodes[room.id] = { + ...zone, + floor: { ...zone.floor, regions: [...(zone.floor?.regions ?? []), ...regions] }, + } + } + // Every wall-generated slab and piece is consumed, or the level keeps its slabs. + if (legacy.some((slab) => nodes[slab.id] && !(nodes[slab.id] as SlabNode).plateRole)) + reject() + reports.push({ + code: 'floor-pieces-absorbed', + nodeId: level.id, + pieces: [...adoption.pieces].flatMap(([id, levelId]) => + levelId === level.id ? [id] : [], + ), + trimmed: Math.round(area(trimmed) * 1e4) / 1e4, + closed: Math.round(area(difference(visibleAfter, visibleBefore)) * 1e4) / 1e4, + holes: voidHoles, + }) + } + demoteUnmatched() + for (const id of regions) delete nodes[id] + const newSupportNodes = { ...nodes } + for (const wall of walls) { + const old = oldSupports.get(wall.id)! + const next = wallSupportForNodes(wall, newSupportNodes) + const oldTop = + wall.height === undefined + ? getStoredLevelHeight(level) + : (wall.supportSlabId === 'ground' ? old.elevation : Math.max(0, old.elevation)) + + wall.height + const newTop = resolveWallTop(wall, getStoredLevelHeight(level), next.elevation) + if (wall.height !== undefined && Math.abs(oldTop - newTop) > 0.001) + nodes[wall.id] = { ...wall, height: oldTop - next.elevation } + for (const id of wall.children ?? []) { + const opening = nodes[id] + if ( + (opening?.type !== 'door' && opening?.type !== 'window') || + isFloorAnchoredOpening(opening) + ) + continue + const delta = old.elevation - getOpeningFloorDatum(wall, opening, newSupportNodes) + if (Math.abs(delta) > 1e-6) + nodes[id] = { + ...opening, + ...(opening.position[1] + delta - opening.height / 2 <= 0.01 + ? { verticalAnchor: 'wall' as const } + : {}), + position: [ + opening.position[0], + Math.round((opening.position[1] + delta) * 1e6) / 1e6, + opening.position[2], + ], + } + } + const delta = old.elevation - next.elevation + if (wall.faceRegions?.length && Math.abs(delta) > 1e-6) + nodes[wall.id] = { + ...nodes[wall.id], + faceRegions: wall.faceRegions.map((region) => ({ + ...region, + ...(region.v0 === undefined + ? {} + : { v0: Math.round((region.v0 + delta) * 1e6) / 1e6 }), + ...(region.v1 === undefined + ? {} + : { v1: Math.round((region.v1 + delta) * 1e6) / 1e6 }), + })), + } as WallNode + } + if (level.type === 'level') + nodes[level.id] = { + ...level, + children: [ + ...level.children.filter((id) => !!nodes[id]), + ...[...generated.values()].filter((id) => !level.children.includes(id as never)), + ] as typeof level.children, + } + } catch (error) { + const rejected = error instanceof AdoptionRejected + for (const id of Object.keys(nodes)) delete nodes[id] + Object.assign(nodes, beforeNodes) + remap.clear() + for (const [id, target] of beforeRemap) remap.set(id, target) + plateIds.length = beforePlateCount + changed = beforeChanged + if (!rejected) + warnPlateFailure( + level.id, + Object.values(beforeNodes) + .filter((node) => node.parentId === level.id) + .map((node) => node.id), + error, + ) + } + } + for (const node of Object.values(nodes)) { + const data = { ...node } as AnyNode & { supportSlabId?: string; deckSlabId?: string } + let changed = false + for (const field of ['supportSlabId', 'deckSlabId'] as const) { + let host = data[field] + const seen = new Set() + while (host && remap.has(host) && !seen.has(host)) { + seen.add(host) + host = remap.get(host) + } + if (host !== data[field]) { + data[field] = replacementPlateFor( + node, + field, + Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab'), + { ...sourceNodes, ...nodes } as Record, + ) + changed = true + } + } + if (changed) nodes[node.id] = data as AnyNode + } + if ( + Object.values(sourceNodes).some( + (node) => + (node as SlabNode).type === 'slab' && + ((node as SlabNode).autoFromWalls || (node as SlabNode).boundary === 'auto') && + !(node as SlabNode).plateRole, + ) + ) { + const associated = associateLegacyManualFloors(nodes, sourceNodes as Record) + if (associated !== nodes) { + Object.assign(nodes, associated) + changed = true + } + } + if (!Object.values(sourceNodes).some((node) => (node as SlabNode).plateRole)) { + const absorbed = absorbCompleteManualFloors(nodes) + if (absorbed !== nodes) { + Object.assign(nodes, absorbed) + changed = true + } + } + if (clearDanglingFloorSources(nodes)) changed = true + if (changed) + for (const [id, node] of Object.entries(nodes)) + if (node !== sourceNodes[id]) nodes[id] = omitUndefined(node) + const visibleFinishes = new Set( + Object.values(nodes) + .flatMap((node) => { + if (node.type === 'zone') + return [ + node.floor?.finish, + node.floorStepFinish, + node.floorEdgeFinish, + ...(node.floor?.regions ?? []).map((region) => region.finish), + ] + if (node.type === 'slab') + return [node.material, node.materialPreset, ...Object.values(node.slots ?? {})] + return [] + }) + .filter((value) => value !== undefined) + .map((value) => JSON.stringify(value)), + ) + for (const source of Object.values(sourceNodes) as AnyNode[]) + if ( + source.type === 'slab' && + (source.autoFromWalls || source.boundary === 'auto') && + !source.plateRole + ) { + for (const finish of new Set( + [source.material, source.materialPreset, ...Object.values(source.slots ?? {})].filter( + (value) => value !== undefined, + ), + )) + if (!visibleFinishes.has(JSON.stringify(finish))) + reports.push({ code: 'finish-not-visible', nodeId: source.id, finish }) + } + return { nodes: changed ? nodes : sourceNodes, plateIds, reports } +} + +export function migrateSlabSlots(sourceNodes: Record) { + const nodes = { ...sourceNodes } as Record + let changed = false + for (const node of Object.values(nodes)) { + if (node.type !== 'slab' || !node.slots?.side) continue + if (['edge', 'riser', 'underside'].every((key) => node.slots![key] !== undefined)) continue + const slots = { ...node.slots } + for (const key of ['edge', 'riser', 'underside']) + if (slots[key] === undefined) slots[key] = slots.side! + nodes[node.id] = omitUndefined({ ...node, slots }) + changed = true + } + return { nodes: changed ? nodes : sourceNodes, changed } +} diff --git a/packages/core/src/utils/floor-plate-split.test.ts b/packages/core/src/utils/floor-plate-split.test.ts new file mode 100644 index 0000000000..367a986fca --- /dev/null +++ b/packages/core/src/utils/floor-plate-split.test.ts @@ -0,0 +1,88 @@ +import { expect, test } from 'bun:test' +import { type AnyNode, LevelNode, type SlabNode, WallNode, ZoneNode } from '../schema' +import { reconcileStructureOnLoad } from './reconcile-structure-on-load' + +type P = [number, number] +const rect = (x0: number, z0: number, x1: number, z1: number): P[] => [ + [x0, z0], + [x1, z0], + [x1, z1], + [x0, z1], +] +let counter = 0 +const wall = (start: P, end: P) => + WallNode.parse({ + id: `wall_review_${counter++}`, + parentId: 'level_p', + start, + end, + thickness: 0.2, + }) +const ringWalls = (ring: P[]) => ring.map((point, i) => wall(point, ring[(i + 1) % ring.length]!)) +const zone = (id: string, polygon: P[]) => + ZoneNode.parse({ + id, + name: id, + polygon, + parentId: 'level_p', + spaceRole: 'room', + enclosureStatus: 'enclosed', + }) +const slabs = (nodes: Record) => + Object.values(nodes).filter((n): n is SlabNode => n.type === 'slab') +const makeScene = (children: AnyNode[]): Record => + Object.fromEntries( + [LevelNode.parse({ id: 'level_p', children: children.map((n) => n.id) }), ...children].map( + (n) => [n.id, n], + ), + ) + +function run(cx1: number) { + const aw = ringWalls(rect(0, 0, 4, 4)) + const A = zone('zone_A', rect(0, 0, 4, 4)) + let nodes = reconcileStructureOnLoad(makeScene([...aw, A])).nodes + const cw = [wall([4, 0], [cx1, 0]), wall([cx1, 0], [cx1, 4]), wall([cx1, 4], [4, 4])] + const C = zone('zone_C', rect(4, 0, cx1, 4)) + const lvl = nodes.level_p as LevelNode + nodes = { + ...nodes, + level_p: { ...lvl, children: [...lvl.children, ...cw.map((w) => w.id), C.id] }, + } + for (const x of [...cw, C]) nodes[x.id] = x + nodes = reconcileStructureOnLoad(nodes).nodes + const cw2 = ringWalls(rect(6, 0, cx1 + 2, 4)) + const lv = nodes.level_p as LevelNode + const retainedId = slabs(nodes).find((plate) => plate.plateRole === 'base')!.id + const next: Record = { ...nodes } + for (const w of cw) delete next[w.id] + next.level_p = { + ...lv, + children: [ + ...lv.children.filter((id: string) => !cw.some((w) => w.id === id)), + ...cw2.map((w) => w.id), + ], + } + for (const w of cw2) next[w.id] = w + next.zone_C = { + ...(nodes.zone_C as ZoneNode), + polygon: rect(6, 0, cx1 + 2, 4), + boundaryWallIds: [], + } + const r = reconcileStructureOnLoad(next).nodes + expect(r[retainedId]?.type).toBe('slab') + expect(reconcileStructureOnLoad(r).nodes).toEqual(r) + expect(slabs(r).filter((p) => p.plateRole === 'base')).toHaveLength(2) + expect(new Set(slabs(r).map((p) => p.id)).size).toBe(slabs(r).length) + expect( + slabs(r) + .flatMap((p) => p.zoneIds ?? []) + .sort(), + ).toEqual(['zone_A', 'zone_C']) +} + +test('split retains a smaller original footprint without an ID collision', () => { + run(12) +}) +test('split retains a larger original footprint without an ID collision', () => { + run(6) +}) diff --git a/packages/core/src/utils/floor-review-load.test.ts b/packages/core/src/utils/floor-review-load.test.ts new file mode 100644 index 0000000000..466bf6d5a8 --- /dev/null +++ b/packages/core/src/utils/floor-review-load.test.ts @@ -0,0 +1,138 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { automaticFloorHeight } from '../lib/floor-foundation-datum' +import { getOpeningFloorDatum, wallSupportForNodes } from '../lib/opening-floor-datum' +import { type AnyNode, LevelNode, SlabNode, WallNode } from '../schema' +import { getWallPlaneTop } from '../services/storey' +import { resolveWallTop } from '../systems/wall/wall-top' +import { preserveLegacyWallDatums } from './legacy-wall-datums' +import * as migrations from './scene-migrations' + +function load(source: Record) { + const vertical = migrations.migrateVerticalSceneNodes( + migrations.healSceneNodes(migrations.normalizeLegacyStructure(source)).nodes, + ).nodes + const rooms = migrations.migrateRoomZones(vertical).nodes + const plates = migrations.migrateFloorPlates( + migrations.migrateCeilingRoomLinks(rooms).nodes, + ).nodes + const openings = migrations.ensureSceneOpenings(migrations.migrateSlabSlots(plates).nodes).nodes + const walls = migrations.migrateWallFaceBands( + migrations.migrateWallFaceKeys(openings).nodes, + ).nodes + return migrations.reconcileStructureOnLoad(walls, vertical).nodes +} +for (const id of ['scene-26', 'scene-07', 'scene-17', 'scene-24', 'scene-06']) { + test(`${id}: migration is identical on its second load`, () => { + const raw = JSON.parse( + readFileSync( + new URL(`../lib/__fixtures__/plate-corpus/review/${id}.json`, import.meta.url), + 'utf8', + ), + ) + const first = load(raw) + expect(load(first)).toEqual(first) + expect( + Object.values(first).filter((node) => node.type === 'slab' && node.floorHeight !== undefined), + ).toEqual([]) + for (const plate of Object.values(first)) + if (plate.type === 'slab' && plate.plateRole === 'base') + expect(automaticFloorHeight(first, plate)).toBeCloseTo(plate.elevation, 6) + if (id === 'scene-17') { + const wall = first.wall_n1xa0800aqmazoar as WallNode + expect( + resolveWallTop( + wall, + getWallPlaneTop(wall, wall.parentId!, first), + wallSupportForNodes(wall, first).elevation, + ), + ).toBeCloseTo(2.5) + } + if (id === 'scene-24') { + const opening = first.window_drbs0ipvpb9ksir3 + if (opening?.type !== 'window') throw new Error('Missing window') + const wall = first[opening.parentId!] as WallNode + expect( + getOpeningFloorDatum(wall, opening, first) + opening.position[1] - opening.height / 2, + ).toBeCloseTo(0.2) + // The footprint keeps its legacy floor, so the wall does not move and the + // window needs no wall anchoring to keep its sill. + expect(opening.verticalAnchor).toBeUndefined() + } + if (id === 'scene-07') { + const wall = first.wall_1cs12gkft1qbcunm as WallNode + expect( + resolveWallTop( + wall, + getWallPlaneTop(wall, wall.parentId!, first), + wallSupportForNodes(wall, first).elevation, + ), + ).toBeCloseTo(4.49) + } + const rejected = id === 'scene-06' ? ['door_sewdhekqvtodswrn'] : [] + for (const openingId of rejected) { + const opening = first[openingId] + if (opening?.type !== 'door') throw new Error('Missing door') + expect(opening.verticalAnchor).toBe('wall') + for (const height of [undefined, 3, 5]) { + const wall = { ...(first[opening.parentId!] as WallNode), height } + const edited = { ...first, [wall.id]: wall } + expect( + getOpeningFloorDatum(wall, opening, edited) + opening.position[1] - opening.height / 2, + ).toBeCloseTo(0.05, 6) + } + } + }, 20_000) +} + +test('legacy bands and authored paint regions both retain their world heights', () => { + const level = LevelNode.parse({ id: 'level_p', children: ['wall_p', 'slab_p'] }) + const wall = WallNode.parse({ + id: 'wall_p', + parentId: level.id, + start: [0, 0], + end: [4, 0], + height: 2.5, + faceRegions: [{ id: 'paint', face: 'a', v0: 0.2, v1: 0.8, finish: 'library:paint' }], + }) + const slab = SlabNode.parse({ + id: 'slab_p', + parentId: level.id, + polygon: [ + [-1, -1], + [5, -1], + [5, 1], + [-1, 1], + ], + elevation: 0.55, + }) + const before: Record = { [level.id]: level, [wall.id]: wall, [slab.id]: slab } + const converted = migrations.migrateWallFaceBands({ + ...before, + [wall.id]: { + ...wall, + faceBands: { enabled: true, count: 2, lowerHeight: 0.84 }, + slots: { aLower: 'library:band' }, + }, + }).nodes as Record + const nodes = preserveLegacyWallDatums(before, { + ...converted, + [level.id]: { ...level, metadata: { floorOwnershipMigrated: true } }, + [slab.id]: { + ...slab, + elevation: 0.05, + floorHeight: 0.05, + plateRole: 'base', + autoFromWalls: true, + }, + }) + const current = nodes[wall.id] as WallNode + const support = wallSupportForNodes(current, nodes).elevation + expect(support).toBeCloseTo(0.55) + const paint = current.faceRegions!.find((region) => region.id === 'paint')! + const band = current.faceRegions!.find((region) => region.finish === 'library:band')! + expect(paint.v0! + support).toBeCloseTo(0.75, 6) + expect(paint.v1! + support).toBeCloseTo(1.35, 6) + expect(band.v1! + support).toBeCloseTo(1.39, 6) + expect(preserveLegacyWallDatums(nodes, nodes)).toEqual(nodes) +}) diff --git a/packages/core/src/utils/frozen-floor-gate.test.ts b/packages/core/src/utils/frozen-floor-gate.test.ts new file mode 100644 index 0000000000..447072cf0e --- /dev/null +++ b/packages/core/src/utils/frozen-floor-gate.test.ts @@ -0,0 +1,175 @@ +import { expect, test } from 'bun:test' +import { readdirSync, readFileSync } from 'node:fs' +import { slabFootprint } from '../lib/floor-plates' +import { area, containsPoint, difference, distanceToBoundary, union } from '../lib/polygon-boolean' +import { getRenderableSlabPolygon } from '../lib/slab-polygon' +import type { AnyNode, AnyNodeId, ElevatorNode, SlabNode, WallNode } from '../schema' +import { getWallSurfacePolygon, isCurvedWall } from '../systems/wall/wall-curve' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { getWallMiterBoundaryPoints } from '../systems/wall/wall-mitering' +import { materializeLegacyAutoOpenings } from './owned-floor-opening-migration' +import { + healSceneNodes, + migrateCeilingRoomLinks, + migrateFloorPlates, + migrateRoomZones, + migrateSlabSlots, + migrateVerticalSceneNodes, + normalizeLegacyStructure, +} from './scene-migrations' + +type Fixture = { + sceneId: string + rootNodeIds: AnyNodeId[] + nodes: Record + areas: { levelId: string; beforeVisible: number; afterVisible: number }[] + gaps: { + levelId: string + wallId: string + plateIds: string[] + sampleStations: number[] + faces: { face: 'a' | 'b'; uncoveredSamples: number[] }[] + }[] +} +const directory = new URL('../lib/__fixtures__/plate-corpus/frozen-gate/', import.meta.url) +const fixtures: Fixture[] = readdirSync(directory) + .filter((file) => file.endsWith('.json')) + .map((file) => JSON.parse(readFileSync(new URL(file, directory), 'utf8'))) +function prefix(nodes: Record) { + return migrateCeilingRoomLinks( + migrateRoomZones( + migrateVerticalSceneNodes(healSceneNodes(normalizeLegacyStructure(nodes)).nodes).nodes, + ).nodes, + ).nodes as Record +} +function visible(nodes: Record, levelId: string) { + const children = Object.values(nodes).filter((node) => node.parentId === levelId) + const walls = children.filter((node): node is WallNode => node.type === 'wall') + const slabs = children.filter((node): node is SlabNode => node.type === 'slab') + const miters = calculateLevelMiters(walls) + return difference( + union( + slabs.map((slab) => ({ + outer: getRenderableSlabPolygon(slab, { walls, siblingSlabs: slabs }), + holes: slab.holes ?? [], + })), + ), + union( + walls.map((wall) => + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ), + ), + ) +} + +test.each( + fixtures.filter((fixture) => fixture.areas.length), +)('$sceneId M4 preserves visible area; subsequent loss is exactly legacy stair openings', (fixture) => { + const before = prefix(fixture.nodes) + const plates = migrateFloorPlates(before).nodes as Record + const ensured = { nodes: materializeLegacyAutoOpenings(plates) as Record } + for (const row of fixture.areas) { + const original = visible(before, row.levelId) + const migrated = visible(plates, row.levelId) + const opened = visible(ensured.nodes, row.levelId) + expect(Math.abs(area(migrated) - area(original))).toBeLessThanOrEqual(area(original) * 0.01) + expect(area(original)).toBeCloseTo(row.beforeVisible, 2) + expect(area(opened)).toBeCloseTo(row.afterVisible, 2) + const newHoles = Object.values(ensured.nodes).flatMap((node) => { + if (node.type !== 'slab' || node.parentId !== row.levelId) return [] + const previous = plates[node.id] as SlabNode + return node.holes.slice(previous.holes?.length ?? 0) + }) + expect(area(difference(difference(migrated, opened), union(newHoles)))).toBeLessThan(0.001) + } + expect(materializeLegacyAutoOpenings(ensured.nodes)).toBe(ensured.nodes) +}) + +test.each( + fixtures.filter((fixture) => fixture.gaps.length), +)('$sceneId frozen gap samples are covered by stored plates before missing openings are ensured', (fixture) => { + const plates = migrateFloorPlates(prefix(fixture.nodes)).nodes as Record + const ensured = materializeLegacyAutoOpenings(plates) as Record + for (const gap of fixture.gaps) { + const wall = plates[gap.wallId] as WallNode + const walls = Object.values(plates).filter( + (node): node is WallNode => node.type === 'wall' && node.parentId === gap.levelId, + ) + const ends = getWallMiterBoundaryPoints(wall, calculateLevelMiters(walls))! + const count = isCurvedWall(wall) ? 24 : 1 + const polygon = getWallSurfacePolygon(wall, count, ends) + const lines = { a: polygon.slice(count + 1).reverse(), b: polygon.slice(0, count + 1) } + const owners = Object.values(plates).filter( + (node): node is SlabNode => node.type === 'slab' && node.parentId === gap.levelId, + ) + const geometry = owners.map(slabFootprint) + const additions = owners + .map((plate) => plate.id) + .flatMap((id) => (ensured[id] as SlabNode).holes.slice((plates[id] as SlabNode).holes.length)) + for (const face of gap.faces) + for (const index of face.uncoveredSamples) { + const t = gap.sampleStations[index]! + const segment = Math.min(Math.floor(t * count), count - 1) + const fraction = t * count - segment + const a = lines[face.face][segment]!, + b = lines[face.face][segment + 1]! + const point: [number, number] = [a.x + (b.x - a.x) * fraction, a.y + (b.y - a.y) * fraction] + expect(containsPoint(geometry, point) || distanceToBoundary(geometry, point) <= 0.005).toBe( + true, + ) + expect( + containsPoint( + additions.map((outer) => ({ outer, holes: [] })), + point, + ), + ).toBe(true) + } + } +}) + +test.each( + fixtures.filter(({ sceneId }) => ['scene-19', 'scene-10'].includes(sceneId)), +)('$sceneId level-parented elevator openings agree with client building reparenting and preserve saved holes', (fixture) => { + const before = migrateSlabSlots(migrateFloorPlates(prefix(fixture.nodes)).nodes).nodes as Record< + string, + AnyNode + > + const bytes = JSON.stringify(before) + const clientParents = { ...before } + const legacy = Object.values(before).filter( + (node): node is ElevatorNode => + node.type === 'elevator' && before[node.parentId!]?.type === 'level', + ) + expect(legacy.length).toBeGreaterThan(0) + for (const elevator of legacy) { + const building = Object.values(before).find( + (node) => node.type === 'building' && node.children.includes(elevator.parentId as AnyNodeId), + )! + clientParents[elevator.id] = { ...elevator, parentId: building.id } + } + const server = materializeLegacyAutoOpenings(before) as Record, + client = materializeLegacyAutoOpenings(clientParents) as Record + expect(JSON.stringify(before)).toBe(bytes) + expect( + Object.values(server) + .filter((node) => node.type === 'slab') + .map((node) => node.holeMetadata), + ).toEqual( + Object.values(client) + .filter((node) => node.type === 'slab') + .map((node) => node.holeMetadata), + ) + for (const elevator of legacy) { + expect( + Object.values(server).some( + (node) => + node.type === 'slab' && node.holeMetadata?.some((m) => m.elevatorId === elevator.id), + ), + ).toBe(fixture.sceneId !== 'scene-19') + } + for (const node of Object.values(before)) { + if (node.type !== 'slab') continue + expect((server[node.id] as SlabNode).holes.slice(0, node.holes.length)).toEqual(node.holes) + } + expect(materializeLegacyAutoOpenings(server)).toBe(server) +}) diff --git a/packages/core/src/utils/heal-plan-coordinates.test.ts b/packages/core/src/utils/heal-plan-coordinates.test.ts new file mode 100644 index 0000000000..7385c35feb --- /dev/null +++ b/packages/core/src/utils/heal-plan-coordinates.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, test } from 'bun:test' +import { healSceneNodes, healScenePlanCoordinates } from './scene-migrations' + +const ring = [ + [1, 2], + [4, 2], + [4, 6], +] +const wallCases = [ + { start: { x: 1, z: 2 }, end: { x: 4, z: 6 } }, + { start: { x: 1, y: 9, z: 2 }, end: { x: 4, y: 9, z: 6 } }, + { start: { x: 1, y: 2 }, end: { x: 4, y: 6 }, height: 3 }, + { start: [1, 9, 2], end: [4, 9, 6] }, + { + points: [ + [1, 2], + [4, 6], + ], + }, +] + +describe('healScenePlanCoordinates', () => { + test.each(wallCases)('normalizes wall endpoints: %j', (geometry) => { + const node = { type: 'wall', ...geometry, children: ['door_a'], metadata: { retained: true } } + const input = { wall_a: node } + const snapshot = structuredClone(input) + const healed = healScenePlanCoordinates(input) + expect(healed.wall_a).toEqual({ ...node, start: [1, 2], end: [4, 6] }) + expect(input).toEqual(snapshot) + expect(healScenePlanCoordinates(healed)).toBe(healed) + }) + + test.each([ + { polygon: { points: ring } }, + { polygon: { type: 'polygon', points: ring } }, + { polygon: [ring] }, + { polygon: { points: [ring] } }, + { points: ring }, + { vertices: ring }, + { polygon: ring.map(([x, z]) => ({ x, z })) }, + { points: ring.map(([x, y]) => ({ x, y })), thickness: 0.25 }, + { polygon: ring.map(([x, z]) => [x, 9, z]) }, + ])('recovers a slab ring: %j', (geometry) => { + const node = { type: 'slab', ...geometry, holes: [], parentId: 'level_a' } + const input = { slab_a: node } + const snapshot = structuredClone(input) + const healed = healScenePlanCoordinates(input) + expect(healed.slab_a).toEqual({ ...node, polygon: ring }) + expect(input).toEqual(snapshot) + expect(healScenePlanCoordinates(healed)).toBe(healed) + }) + + test.each([ + { type: 'wall', start: { x: 1, y: 2 }, end: { x: 4, y: 6 } }, + { type: 'wall', start: { x: 1, z: '2' }, end: [4, 6], height: 3 }, + { type: 'wall', start: { x: 1, y: 2, z: null }, end: [4, 6], height: 3 }, + { type: 'wall', start: [1, Number.NaN, 2], end: [4, 9, 6] }, + { type: 'wall', start: [1, 2], end: [4, Number.POSITIVE_INFINITY] }, + { type: 'wall', points: ring }, + { + type: 'wall', + start: null, + points: [ + [1, 2], + [4, 6], + ], + }, + { type: 'slab', polygon: { coordinates: ring } }, + { type: 'slab', polygon: [ring, ring] }, + { type: 'slab', polygon: [[ring]] }, + { type: 'slab', polygon: ring.map(([x, y]) => ({ x, y })) }, + { + type: 'slab', + polygon: [ + [1, 2], + [4, 6], + ], + }, + { type: 'slab', polygon: null, points: ring }, + { + type: 'slab', + polygon: [ + [1, 2], + [4, 6], + [7, '8'], + ], + }, + { type: 'item', start: { x: 1, z: 2 }, end: { x: 4, z: 6 } }, + ])('leaves unknown or ambiguous shapes untouched: %j', (node) => { + const input = { node } + expect(healScenePlanCoordinates(input)).toBe(input) + }) + + test('preserves canonical nodes and unrelated fields by reference', () => { + const input = { + wall_a: { type: 'wall', start: [1, 2], end: [4, 6] }, + slab_a: { type: 'slab', polygon: ring, elevation: 0.1 }, + unknown: null, + } + expect(healScenePlanCoordinates(input)).toBe(input) + }) + + test('the loader heal normalizes 3D endpoints before checking zero length', () => { + const input = { wall_a: { type: 'wall', start: [1, 0, 2], end: [1, 0, 6] } } + const healed = healSceneNodes(input) + expect(healed.nodes.wall_a).toEqual({ type: 'wall', start: [1, 2], end: [1, 6] }) + expect(healed.droppedWallIds).toEqual([]) + expect(healed.repairedCoordinates).toBe(1) + expect(healSceneNodes(healed.nodes)).toEqual({ ...healed, repairedCoordinates: 0 }) + }) + + test('reports repaired nodes once each for coordinate-only changes', () => { + const input = { + wall_a: { type: 'wall', start: { x: 1, z: 2 }, end: { x: 4, z: 6 } }, + slab_a: { type: 'slab', polygon: { points: ring } }, + wall_b: { type: 'wall', start: [0, 0], end: [1, 0] }, + } + const healed = healSceneNodes(input) + expect(healed).toMatchObject({ + repairedCoordinates: 2, + droppedWallIds: [], + strippedChildRefs: 0, + strippedStaleChildRefs: 0, + repairedParentLinkNodeIds: [], + }) + expect(healSceneNodes(healed.nodes)).toEqual({ ...healed, repairedCoordinates: 0 }) + }) + + test('does not report coordinate repairs for unknown representations', () => { + const input = { wall_a: { type: 'wall', start: { u: 1, v: 2 }, end: { u: 4, v: 6 } } } + expect(healSceneNodes(input).repairedCoordinates).toBe(0) + }) +}) diff --git a/packages/core/src/utils/heal-plan-coordinates.ts b/packages/core/src/utils/heal-plan-coordinates.ts new file mode 100644 index 0000000000..9b216c8b86 --- /dev/null +++ b/packages/core/src/utils/heal-plan-coordinates.ts @@ -0,0 +1,64 @@ +type PlanPoint = [number, number] +type NodeData = Record + +function record(value: unknown): value is NodeData { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +function finite(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) +} + +function planPoint(value: unknown, allowXY: boolean): PlanPoint | undefined { + if (Array.isArray(value)) { + if (!value.every(finite)) return + if (value.length === 2) return value as PlanPoint + if (value.length === 3) return [value[0]!, value[2]!] + return + } + if (!(record(value) && finite(value.x))) return + if (finite(value.z)) return [value.x, value.z] + if (allowXY && !('z' in value) && finite(value.y)) return [value.x, value.y] +} + +function planRing(value: unknown, allowXY: boolean): PlanPoint[] | undefined { + let points = record(value) ? value.points : value + if (Array.isArray(points) && points.length === 1) points = points[0] + if (!Array.isArray(points) || points.length < 3) return + const ring = points.map((point) => planPoint(point, allowXY)) + if (!ring.every((point): point is PlanPoint => point !== undefined)) return + return ring.every((point, i) => point === points[i]) ? (points as PlanPoint[]) : ring +} + +function healNode(node: NodeData): NodeData { + // A separately authored vertical dimension identifies legacy XY plan data; + // otherwise a missing Z is ambiguous and must not be guessed. + const allowXY = [node.height, node.thickness, node.elevation].some(finite) + if (node.type === 'wall') { + const points = + node.start === undefined && node.end === undefined && Array.isArray(node.points) + ? node.points + : undefined + const start = planPoint(points?.length === 2 ? points[0] : node.start, allowXY) + const end = planPoint(points?.length === 2 ? points[1] : node.end, allowXY) + if (start && end && (start !== node.start || end !== node.end)) return { ...node, start, end } + } + if (node.type === 'slab') { + const source = node.polygon === undefined ? (node.points ?? node.vertices) : node.polygon + const polygon = planRing(source, allowXY) + if (polygon && polygon !== node.polygon) return { ...node, polygon } + } + return node +} + +export function healScenePlanCoordinates(input: Record): Record { + let nodes = input + for (const [id, node] of Object.entries(input)) { + if (!record(node)) continue + const healed = healNode(node) + if (healed === node) continue + if (nodes === input) nodes = { ...input } + nodes[id] = healed + } + return nodes +} diff --git a/packages/core/src/utils/heal-scene-graph.test.ts b/packages/core/src/utils/heal-scene-graph.test.ts index d3a671fc01..8d71bbb0b6 100644 --- a/packages/core/src/utils/heal-scene-graph.test.ts +++ b/packages/core/src/utils/heal-scene-graph.test.ts @@ -2,6 +2,28 @@ import { describe, expect, test } from 'bun:test' import { healSceneNodes } from './heal-scene-graph' describe('healSceneNodes', () => { + test('repairs missing reverse child links on saved hosts without mutating source nodes', () => { + const input = { + site_a: { id: 'site_a', type: 'site', parentId: null }, + building_a: { id: 'building_a', type: 'building', parentId: 'site_a' }, + level_a: { id: 'level_a', type: 'level', parentId: 'building_a', children: ['item_a'] }, + item_a: { id: 'item_a', type: 'item', parentId: 'level_a', children: [] }, + item_b: { id: 'item_b', type: 'item', parentId: 'item_a' }, + } + const snapshot = structuredClone(input) + const healed = healSceneNodes(input) + expect(healed.nodes.site_a).toMatchObject({ children: ['building_a'] }) + expect(healed.nodes.building_a).toMatchObject({ children: ['level_a'] }) + expect(healed.nodes.item_a).toMatchObject({ children: ['item_b'] }) + expect(healed.nodes.level_a).toBe(input.level_a) + expect(input).toEqual(snapshot) + expect(healSceneNodes(healed.nodes).repairedChildLinkNodeIds).toEqual([]) + expect(healSceneNodes(healed.nodes).nodes).toEqual(healed.nodes) + expect(healSceneNodes(Object.fromEntries(Object.entries(input).reverse())).nodes).toEqual( + healed.nodes, + ) + }) + test('strips non-string (null) children entries', () => { const { nodes, strippedChildRefs } = healSceneNodes({ wall_a: { diff --git a/packages/core/src/utils/heal-scene-graph.ts b/packages/core/src/utils/heal-scene-graph.ts index 88e739ed3d..2d7674b7c6 100644 --- a/packages/core/src/utils/heal-scene-graph.ts +++ b/packages/core/src/utils/heal-scene-graph.ts @@ -22,12 +22,25 @@ // All are also prevented at the source now; this is the load-time safety net // for already-saved scenes. +import { AnyNode, nodeKindOf } from '../schema/types' +import { healScenePlanCoordinates } from './heal-plan-coordinates' + const ZERO_LENGTH_EPS = 1e-6 +const hostKinds = new Set( + AnyNode.options.filter((schema) => 'children' in schema.shape).map(nodeKindOf), +) export interface HealSceneResult { - nodes: Record /** Ids of zero-length walls that were dropped. */ droppedWallIds: string[] + nodes: Record + repairedCoordinates: number + /** + * Ids of nodes whose null `parentId` was repaired to the one parent that + * still claims them via `children`. + */ + repairedParentLinkNodeIds: string[] + repairedChildLinkNodeIds: string[] /** Count of invalid non-string (e.g. null) entries removed from `children` arrays. */ strippedChildRefs: number /** @@ -35,11 +48,6 @@ export interface HealSceneResult { * a different node (stale reparent leftovers), plus same-array duplicates. */ strippedStaleChildRefs: number - /** - * Ids of nodes whose null `parentId` was repaired to the one parent that - * still claims them via `children`. - */ - repairedParentLinkNodeIds: string[] } function isWallLike(node: unknown): node is { start: [number, number]; end: [number, number] } { @@ -62,11 +70,14 @@ function isWallLike(node: unknown): node is { start: [number, number]; end: [num */ export function healSceneNodes(input: Record): HealSceneResult { const droppedWallIds: string[] = [] + const repairedChildLinkNodeIds: string[] = [] + let repairedCoordinates = 0 // Pass 1: drop childless zero-length walls. (Only childless ones — a wall // carrying a door/window must keep its hosts, degenerate or not.) const kept: Record = {} - for (const [id, node] of Object.entries(input)) { + for (const [id, node] of Object.entries(healScenePlanCoordinates(input))) { + if (node !== input[id]) repairedCoordinates += 1 if (isWallLike(node)) { const children = (node as { children?: unknown }).children const childless = !Array.isArray(children) || children.length === 0 @@ -92,6 +103,16 @@ export function healSceneNodes(input: Record): HealSceneResult const nodes: Record = {} for (const [id, node] of Object.entries(kept)) { const children = (node as { children?: unknown })?.children + if ((node as { type?: unknown })?.type === 'level' && !Array.isArray(children)) { + nodes[id] = { + ...(node as Record), + children: Object.entries(kept) + .filter(([, child]) => (child as { parentId?: unknown })?.parentId === id) + .map(([childId]) => childId), + } + repairedChildLinkNodeIds.push(id) + continue + } if (Array.isArray(children)) { const seen = new Set() const cleaned = children.filter((child) => { @@ -149,7 +170,7 @@ export function healSceneNodes(input: Record): HealSceneResult : child && typeof child === 'object' && typeof (child as { id?: unknown }).id === 'string' ? (child as { id: string }).id : null - if (!childId || !(childId in nodes)) continue + if (!(childId && childId in nodes)) continue const claimants = claimantsByChildId.get(childId) ?? [] claimants.push(id) claimantsByChildId.set(childId, claimants) @@ -166,11 +187,31 @@ export function healSceneNodes(input: Record): HealSceneResult repairedParentLinkNodeIds.push(id) } + // Reachability follows children, so retaining a node via parentId also + // requires repairing its host's reverse link before authority validation. + for (const [id, node] of Object.entries(nodes).sort(([a], [b]) => a.localeCompare(b))) { + const parentId = (node as { parentId?: unknown })?.parentId + if (typeof parentId !== 'string' || parentId === id) continue + const parent = nodes[parentId] as { type?: string; children?: unknown } | undefined + if (!parent || !(hostKinds.has(parent.type ?? '') || Array.isArray(parent.children))) continue + const children = Array.isArray(parent.children) ? parent.children : [] + if ( + children.some( + (child) => child === id || (child && typeof child === 'object' && child.id === id), + ) + ) + continue + nodes[parentId] = { ...parent, children: [...children, id] } + if (!repairedChildLinkNodeIds.includes(parentId)) repairedChildLinkNodeIds.push(parentId) + } + return { nodes, + repairedCoordinates, droppedWallIds, strippedChildRefs, strippedStaleChildRefs, repairedParentLinkNodeIds, + repairedChildLinkNodeIds, } } diff --git a/packages/core/src/utils/legacy-floor-datum.test.ts b/packages/core/src/utils/legacy-floor-datum.test.ts new file mode 100644 index 0000000000..bb5bce127f --- /dev/null +++ b/packages/core/src/utils/legacy-floor-datum.test.ts @@ -0,0 +1,269 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { setRoomFloorConstruction } from '../commands/structure/set-room-floor-construction' +import { automaticFloorHeight, footprintLift } from '../lib/floor-foundation-datum' +import { area, intersection } from '../lib/polygon-boolean' +import { levelBaseElevationAt } from '../lib/terrain-support-query' +import { type AnyNode, LevelNode, SlabNode, WallNode } from '../schema' +import { computeWallSlabSupport } from '../systems/slab/slab-support' +import { legacyWallElevations } from './legacy-wall-datums' +import * as migrations from './scene-migrations' +import { reconcileStructureWithStableIds } from './structure-id' + +function load(source: Record) { + const vertical = migrations.migrateVerticalSceneNodes( + migrations.healSceneNodes(migrations.normalizeLegacyStructure(source)).nodes, + ).nodes + const rooms = migrations.migrateRoomZones(vertical).nodes + const plates = migrations.migrateFloorPlates( + migrations.migrateCeilingRoomLinks(rooms).nodes, + ).nodes + const openings = migrations.ensureSceneOpenings(migrations.migrateSlabSlots(plates).nodes).nodes + const walls = migrations.migrateWallFaceBands( + migrations.migrateWallFaceKeys(openings).nodes, + ).nodes + return { + legacy: vertical as Record, + nodes: migrations.reconcileStructureOnLoad(walls, vertical).nodes as Record, + } +} + +const slabsOn = (nodes: Record, levelId: string) => + Object.values(nodes).filter( + (node): node is SlabNode => node.type === 'slab' && node.parentId === levelId, + ) +const wallsOn = (nodes: Record, levelId: string) => + Object.values(nodes).filter( + (node): node is WallNode => node.type === 'wall' && node.parentId === levelId, + ) +const support = (nodes: Record, wall: WallNode) => + computeWallSlabSupport( + wall, + slabsOn(nodes, wall.parentId!), + wallsOn(nodes, wall.parentId!), + wall.supportSlabId, + undefined, + levelBaseElevationAt(nodes, wall.parentId!, ...wall.start), + nodes, + ) + +test('a terrace pad under a few walls keeps the house floor at its rooms, with walls where they stood', () => { + // Trimmed production house: every room floor at 0.05, a 0.15 manual terrace + // pad outside the ground floor and a 0.15 manual landing upstairs, each under + // a few boundary walls. They used to lift the whole footprint to 0.20 and + // turn every room into a sunken one. + const fixture = JSON.parse( + readFileSync( + new URL('../lib/__fixtures__/plate-corpus/review/legacy-terrace-pad.json', import.meta.url), + 'utf8', + ), + ) + const { legacy, nodes } = load(fixture.nodes) + const levels = Object.values(nodes).filter((node) => node.type === 'level') + expect(levels).toHaveLength(2) + for (const level of levels) { + const slabs = slabsOn(nodes, level.id) + const bases = slabs.filter((slab) => slab.plateRole === 'base') + expect(slabs.some((slab) => slab.plateRole === 'base' || slab.associatedZoneIds?.length)).toBe( + true, + ) + for (const base of bases) { + expect(base.elevation).toBeCloseTo(0.05, 6) + expect(base.referenceFloorElevation).toBeUndefined() + } + expect(slabs.filter((slab) => slab.plateRole && slab.plateRole !== 'base')).toEqual([]) + const manual = slabs.filter((slab) => !slab.plateRole) + for (const source of slabsOn(legacy, level.id).filter((slab) => !slab.autoFromWalls)) + expect(manual.find((slab) => slab.id === source.id)).toMatchObject({ + elevation: source.elevation, + polygon: source.polygon, + }) + for (const pad of manual.filter( + (slab) => !slabsOn(legacy, level.id).find((s) => s.id === slab.id)?.autoFromWalls, + )) + for (const base of bases) + expect( + area( + intersection( + { outer: base.polygon, holes: base.holes }, + { outer: pad.polygon, holes: pad.holes }, + ), + ) > 0.05 && base.elevation - base.thickness >= pad.elevation - 1e-6, + ).toBe(false) + const old = legacyWallElevations( + wallsOn(legacy, level.id), + slabsOn(legacy, level.id), + legacy, + level.id, + ) + for (const wall of wallsOn(nodes, level.id)) { + const before = old.get(wall.id)!.elevation + const after = support(nodes, wall).elevation + // Walls that stood on the ground now stand on the floor band above it. + if (Math.abs(after - before) > 1e-6) + expect([before, after]).toEqual([ + levelBaseElevationAt(nodes, level.id, ...wall.start), + 0.05, + ]) + } + } + expect(load(nodes).nodes).toEqual(nodes) + expect(reconcileStructureWithStableIds({ nodes }).patches).toEqual([]) +}) + +function legacyRoom(floor: number, inset = 0) { + const level = LevelNode.parse({ id: 'level_legacy', height: 2.7 }) + const ring: [number, number][] = [ + [0, 0], + [6, 0], + [6, 6], + [0, 6], + ] + const walls = ring.map((start, i) => + WallNode.parse({ + id: `wall_legacy_${i}`, + parentId: level.id, + start, + end: ring[(i + 1) % 4], + thickness: 0.2, + }), + ) + const slab = SlabNode.parse({ + id: 'slab_legacy_room', + parentId: level.id, + autoFromWalls: true, + elevation: floor, + polygon: [ + [inset, inset], + [6 - inset, inset], + [6 - inset, 6 - inset], + [inset, 6 - inset], + ], + }) + level.children = [...walls.map((wall) => wall.id), slab.id] + return Object.fromEntries([level, ...walls, slab].map((node) => [node.id, node])) as Record< + string, + AnyNode + > +} + +test('a raised legacy floor keeps its top and authored depth without invented ground fill', () => { + const { legacy, nodes } = load(legacyRoom(0.2)) + const [base, ...others] = slabsOn(nodes, 'level_legacy') + expect(others).toEqual([]) + expect(base).toMatchObject({ + plateRole: 'base', + elevation: 0.2, + referenceFloorElevation: 0.2, + foundation: { type: 'none' }, + }) + expect(base!.thickness).toBeCloseTo(0.05, 6) + expect(automaticFloorHeight(nodes, base!)).toBeCloseTo(0.2, 6) + expect(footprintLift(nodes, base!)).toBe(0) + const old = legacyWallElevations( + wallsOn(legacy, 'level_legacy'), + slabsOn(legacy, 'level_legacy'), + legacy, + 'level_legacy', + ) + for (const wall of wallsOn(nodes, 'level_legacy')) + expect(support(nodes, wall).elevation).toBeCloseTo(old.get(wall.id)!.elevation, 6) + expect(load(nodes).nodes).toEqual(nodes) + expect(reconcileStructureWithStableIds({ nodes }).patches).toEqual([]) +}) + +test('walls that stood on the ground under a storey-high legacy floor keep standing there', () => { + // The legacy floor stops at the walls' inner faces, so the walls stood on the ground. + const { nodes } = load(legacyRoom(2.55, 0.101)) + const floor = slabsOn(nodes, 'level_legacy')[0]! + expect(floor).toMatchObject({ + elevation: 2.55, + thickness: 0.05, + }) + expect(floor.plateRole === 'base' || floor.associatedZoneIds?.length).toBeTruthy() + for (const wall of wallsOn(nodes, 'level_legacy')) { + expect(wall.supportSlabId).toBeUndefined() + expect(support(nodes, wall).elevation).toBeCloseTo(0, 6) + } + expect(load(nodes).nodes).toEqual(nodes) + expect(reconcileStructureWithStableIds({ nodes }).patches).toEqual([]) +}) + +test('a manual terrace under one wall does not lift the automatic floor of a new room', () => { + const nodes = legacyRoom(0.05) + delete nodes.slab_legacy_room + const level = nodes.level_legacy as LevelNode + const terrace = SlabNode.parse({ + id: 'slab_terrace', + parentId: level.id, + elevation: 0.3, + thickness: 0.3, + polygon: [ + [-3, 1], + [0.1, 1], + [0.1, 5], + [-3, 5], + ], + }) + nodes[terrace.id] = terrace + nodes[level.id] = { ...level, children: [...level.children.slice(0, 4), terrace.id] } + const loaded = migrations.reconcileStructureOnLoad(nodes).nodes as Record + const base = slabsOn(loaded, level.id).find((slab) => slab.plateRole === 'base')! + expect(base.elevation).toBeCloseTo(0.05, 6) + expect(automaticFloorHeight(loaded, base)).toBeCloseTo(0.05, 6) + expect(loaded[terrace.id]).toBe(terrace) +}) + +test('a complete manual room floor becomes one editable plate with its identity', () => { + const source = legacyRoom(0.05) + const slab = source.slab_legacy_room as SlabNode + source[slab.id] = { ...slab, autoFromWalls: false, slots: { surface: 'library:oak' } } + const { nodes } = load(source) + const floor = nodes[slab.id] as SlabNode + expect(floor).toMatchObject({ + plateRole: 'base', + boundary: 'auto', + thickness: 0.05, + referenceFloorElevation: 0.05, + }) + const room = Object.values(nodes).find((node) => node.type === 'zone')! + if (room.type !== 'zone') throw new Error('room missing') + expect(floor.zoneIds).toContain(room.id) + expect(room.floor?.sourceSlabId).toBeUndefined() + expect(room.floor?.finish).toBe('library:oak') + expect( + setRoomFloorConstruction(nodes, { zoneId: room.id, patch: { thickness: 0.12 } }).changes, + ).toContainEqual({ + op: 'update', + id: floor.id, + data: expect.objectContaining({ thickness: 0.12 }), + }) + expect(load(nodes).nodes).toEqual(nodes) + expect(reconcileStructureWithStableIds({ nodes }).patches).toEqual([]) +}) + +test('an absorbed manual floor carries its cutout into a floor-opening node', () => { + const source = legacyRoom(0.05) + const slab = source.slab_legacy_room as SlabNode + const hole: [number, number][] = [ + [2, 2], + [3, 2], + [3, 3], + [2, 3], + ] + source[slab.id] = { + ...slab, + autoFromWalls: false, + holes: [hole], + holeMetadata: [{ source: 'manual' }], + } + const { nodes } = load(source) + const floor = nodes[slab.id] as SlabNode + const opening = Object.values(nodes).find((node) => node.type === 'floor-opening') + expect(floor.plateRole).toBe('base') + expect(opening).toMatchObject({ source: 'manual', polygon: hole }) + expect(floor.holes).toEqual([hole]) + expect(floor.holeMetadata).toEqual([{ source: 'floor-opening', openingId: opening!.id }]) + expect(load(nodes).nodes).toEqual(nodes) + expect(reconcileStructureWithStableIds({ nodes }).patches).toEqual([]) +}) diff --git a/packages/core/src/utils/legacy-material-slots.test.ts b/packages/core/src/utils/legacy-material-slots.test.ts new file mode 100644 index 0000000000..abf173e688 --- /dev/null +++ b/packages/core/src/utils/legacy-material-slots.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from 'bun:test' +import { legacySpecToMaterialRef, migrateStructuralMaterialSlots } from './legacy-material-slots' + +describe('legacy material slots', () => { + test('an inline finish mints one content-derived scene material, the same on every load', () => { + const first = {} + const again = {} + const ref = legacySpecToMaterialRef({ material: { preset: 'white' } }, first) + expect(ref).toMatch(/^scene:mat_[0-9a-z]{16}$/) + expect(legacySpecToMaterialRef({ material: { preset: 'white' } }, first)).toBe(ref) + expect(Object.keys(first)).toHaveLength(1) + expect(legacySpecToMaterialRef({ material: { preset: 'white' } }, again)).toBe(ref) + expect(legacySpecToMaterialRef({ material: { preset: 'wood' } }, again)).not.toBe(ref) + expect(legacySpecToMaterialRef({ materialPreset: 'library:preset-sage' }, again)).toBe( + 'library:preset-sage', + ) + }) + + test('walls, slabs and ceilings move their legacy finish onto slots; other kinds are untouched', () => { + const nodes = { + wall_a: { id: 'wall_a', type: 'wall', interiorMaterialPreset: 'library:preset-sage' }, + slab_a: { id: 'slab_a', type: 'slab', material: { preset: 'wood' } }, + fence_a: { id: 'fence_a', type: 'fence', material: { preset: 'wood' } }, + wall_b: { id: 'wall_b', type: 'wall', slots: { a: 'library:preset-navy' } }, + } + const result = migrateStructuralMaterialSlots(nodes) + expect(result.changed).toBe(true) + expect(result.nodes.wall_a).toMatchObject({ slots: { interior: 'library:preset-sage' } }) + const wood = (result.nodes.slab_a as { slots: { surface: string } }).slots.surface + expect(Object.keys(result.materials)).toEqual([wood.slice('scene:'.length)]) + expect(result.nodes.fence_a).toBe(nodes.fence_a) + expect(result.nodes.wall_b).toBe(nodes.wall_b) + expect(migrateStructuralMaterialSlots({ wall_b: nodes.wall_b }).changed).toBe(false) + }) +}) diff --git a/packages/core/src/utils/legacy-material-slots.ts b/packages/core/src/utils/legacy-material-slots.ts new file mode 100644 index 0000000000..d323dbfb3f --- /dev/null +++ b/packages/core/src/utils/legacy-material-slots.ts @@ -0,0 +1,150 @@ +import { parseMaterialRef, toSceneMaterialRef } from '../material-library' +import { getEffectiveWallSurfaceMaterial, type WallSurfaceSide } from '../schema/nodes/wall' +import type { SceneMaterial, SceneMaterialId } from '../schema/scene-material' + +// Legacy inline finishes (`material*` / `materialPreset*`) → `node.slots`, +// shared by the client loader and the hosted authority. Both must run it +// before the structural migrations that read slots (M1 re-keys wall slots by +// face, the floor-plate migration copies a slab's surface onto its room), or +// the two paths store different graphs for the same scene. + +export type MintedMaterials = Record + +function hash53(text: string, seed: number) { + let h1 = 0xdeadbeef ^ seed + let h2 = 0x41c6ce57 ^ seed + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i) + h1 = Math.imul(h1 ^ code, 2654435761) + h2 = Math.imul(h2 ^ code, 1597334677) + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909) + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909) + return 4294967296 * (2097151 & h2) + (h1 >>> 0) +} + +// Content-derived, so every load of the same legacy scene — the authority +// normalises the stored graph on each read — mints the same id. +function legacySceneMaterialId(materialJson: string): SceneMaterialId { + const digest = hash53(materialJson, 0).toString(36).padStart(11, '0') + return `mat_${(digest + hash53(materialJson, 1).toString(36).padStart(11, '0')).slice(0, 16)}` +} + +/** + * A legacy surface spec as a `MaterialRef`: a preset that is already a + * `library:`/`scene:` ref is used as-is; an inline material mints (or reuses) + * a scene material in `minted`. Undefined when the spec carries no material. + */ +export function legacySpecToMaterialRef( + spec: { material?: unknown; materialPreset?: unknown }, + minted: MintedMaterials, +): string | undefined { + if (typeof spec.materialPreset === 'string' && parseMaterialRef(spec.materialPreset)) { + return spec.materialPreset + } + if (spec.material === undefined) return + const json = JSON.stringify(spec.material) + const id = legacySceneMaterialId(json) + // One shared datablock per custom colour (mirrors `commitSlotPaint`'s dedupe-on-match). + minted[id] ??= { + id, + name: `Material ${Object.keys(minted).length + 1}`, + material: spec.material as SceneMaterial['material'], + } + return toSceneMaterialRef(id) +} + +// Move the retired inline `material*` / `interiorMaterial*` / `exteriorMaterial*` +// fields onto `node.slots` (interior / exterior → a ref). Already slot-modelled +// walls and walls with no legacy material are left untouched. +export function migrateWallSurfaceMaterials(node: Record, minted: MintedMaterials) { + if (node.slots && (node.slots.interior !== undefined || node.slots.exterior !== undefined)) { + return node + } + // Already on geometric faces (M1 ran on an earlier load): its legacy fallback + // is per face now, and re-keying it by side would undo that. + if ( + node.legacyFaceMaterials || + (node.slots && (node.slots.a !== undefined || node.slots.b !== undefined)) + ) { + return node + } + + const slots: Record = { ...(node.slots ?? {}) } + for (const side of ['interior', 'exterior'] as WallSurfaceSide[]) { + const spec = getEffectiveWallSurfaceMaterial( + node as Parameters[0], + side, + ) + const ref = legacySpecToMaterialRef(spec, minted) + if (ref) slots[side] = ref + } + + if (Object.keys(slots).length === 0) { + return node + } + + return { + ...node, + slots, + material: undefined, + materialPreset: undefined, + interiorMaterial: undefined, + interiorMaterialPreset: undefined, + exteriorMaterial: undefined, + exteriorMaterialPreset: undefined, + } +} + +// Move a kind's single legacy `material` / `materialPreset` onto its declared +// slots. A pre-slot-model node painted one material rendered that material on +// every part (each slot resolves `node.slots[slot]` → legacy → default), so the +// migration writes the same ref to every slot id the kind can expose — unused +// conditional slots are harmless. Already slot-modelled or unpainted nodes are +// left untouched. +export function migrateSingleMaterialSlots( + node: Record, + slotIds: readonly string[], + minted: MintedMaterials, +) { + if (node.slots && Object.keys(node.slots).length > 0) { + return node + } + + const ref = legacySpecToMaterialRef( + { material: node.material, materialPreset: node.materialPreset }, + minted, + ) + if (!ref) { + return node + } + + const slots: Record = {} + for (const slotId of slotIds) slots[slotId] = ref + + return { ...node, slots, material: undefined, materialPreset: undefined } +} + +/** + * The legacy-finish migrations of the kinds the structural load migrations + * read (walls, slabs, ceilings), for the hosted authority: the client loader + * runs the same per-node functions in `migrateNodes`. + */ +export function migrateStructuralMaterialSlots(sourceNodes: Record) { + const materials: MintedMaterials = {} + let nodes: Record | null = null + for (const [id, value] of Object.entries(sourceNodes)) { + const node = value as Record | null + if (!node || typeof node !== 'object') continue + const next = + node.type === 'wall' + ? migrateWallSurfaceMaterials(node, materials) + : node.type === 'slab' || node.type === 'ceiling' + ? migrateSingleMaterialSlots(node, ['surface'], materials) + : node + if (next === node) continue + nodes ??= { ...sourceNodes } + nodes[id] = next + } + return { nodes: nodes ?? sourceNodes, materials, changed: nodes !== null } +} diff --git a/packages/core/src/utils/legacy-opening-datums.test.ts b/packages/core/src/utils/legacy-opening-datums.test.ts new file mode 100644 index 0000000000..c4129334ac --- /dev/null +++ b/packages/core/src/utils/legacy-opening-datums.test.ts @@ -0,0 +1,135 @@ +import { expect, test } from 'bun:test' +import { getOpeningFloorDatum, getOpeningFloorTarget } from '../lib/opening-floor-datum' +import { checkRoomFloor } from '../lib/room-floor-feasibility' +import { + type AnyNode, + DoorNode, + LevelNode, + SlabNode, + WallNode, + WindowNode, + ZoneNode, +} from '../schema' +import { legacyOpeningFloorChange } from './legacy-opening-datums' + +function fixture(raised: boolean) { + const polygon: [number, number][] = [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ] + const level = LevelNode.parse({ id: 'level_test' }) + const walls = polygon.map((start, i) => + WallNode.parse({ + id: `wall_${i}`, + parentId: level.id, + start, + end: polygon[(i + 1) % 4], + thickness: 0.2, + }), + ) + const wall = WallNode.parse({ + id: 'wall_shared', + parentId: level.id, + start: [2, 0], + end: [2, 4], + thickness: 0.2, + }) + const door = DoorNode.parse({ parentId: wall.id, position: [2, 1, 0], height: 2, width: 0.8 }) + wall.children = [door.id] + const left = ZoneNode.parse({ + id: 'zone_left', + name: 'Left', + parentId: level.id, + spaceRole: 'room', + polygon: [ + [0, 0], + [2, 0], + [2, 4], + [0, 4], + ], + floor: { elevation: 0.05 }, + }) + const right = ZoneNode.parse({ + id: 'zone_right', + name: 'Right', + parentId: level.id, + spaceRole: 'room', + polygon: [ + [2, 0], + [4, 0], + [4, 4], + [2, 4], + ], + floor: { elevation: raised ? 0.35 : 0.05 }, + }) + const base = SlabNode.parse({ + id: 'slab_base', + parentId: level.id, + polygon: [ + [-0.1, -0.1], + [4.1, -0.1], + [4.1, 4.1], + [-0.1, 4.1], + ], + boundary: 'auto', + plateRole: 'base', + elevation: 0.05, + zoneIds: [left.id, right.id], + }) + const platform = SlabNode.parse({ + id: 'slab_platform', + parentId: level.id, + polygon: right.polygon, + boundary: 'auto', + plateRole: 'platform', + elevation: 0.35, + thickness: 0.3, + zoneIds: [right.id], + }) + const nodes: Record = Object.fromEntries( + [level, ...walls, wall, door, left, right, base, ...(raised ? [platform] : [])].map((node) => [ + node.id, + node, + ]), + ) + return { nodes, wall, door } +} + +test('a legacy opening may follow a real step but not a support shift larger than that step', () => { + const { nodes, wall, door } = fixture(true) + expect(legacyOpeningFloorChange(wall, door, nodes, 0.05)).toMatchObject({ + reason: 'between-heights', + }) + expect(legacyOpeningFloorChange(wall, door, nodes, -0.05).reason).toBeUndefined() +}) + +test('an equal-floor correction requires a finish that already covered the legacy opening', () => { + const { nodes, wall, door } = fixture(false) + expect(legacyOpeningFloorChange(wall, door, nodes, 0).reason).toBeUndefined() + expect(legacyOpeningFloorChange(wall, door, nodes, 0, 1e-6, 0.05).reason).toBe('finished-floor') +}) + +test('a higher-floor opening must fit in both migration and live placement, including exact clearance', () => { + const source = fixture(true) + for (const opening of [ + source.door, + WindowNode.parse({ ...source.door, id: 'window_fit', type: 'window', openingKind: 'window' }), + ]) { + for (const height of [undefined, 2.3, 2.299]) { + const wall = { ...source.wall, height, children: [opening.id] } + const nodes = { ...source.nodes, [wall.id]: wall, [opening.id]: opening } + const fits = height !== 2.299 + expect(getOpeningFloorTarget(wall, opening, nodes)).toBeCloseTo(0.35) + expect(getOpeningFloorDatum(wall, opening, nodes)).toBeCloseTo(fits ? 0.35 : 0.05) + const migration = legacyOpeningFloorChange(wall, opening, nodes, 0.05) + expect(migration.fits).toBe(fits) + expect(migration.reason).toBe(fits ? 'between-heights' : undefined) + if (!fits) + expect(checkRoomFloor(nodes, 'zone_right', 0.35).conflicts).toContainEqual( + expect.objectContaining({ code: 'floor-opening-fit' }), + ) + } + } +}) diff --git a/packages/core/src/utils/legacy-opening-datums.ts b/packages/core/src/utils/legacy-opening-datums.ts new file mode 100644 index 0000000000..377006df00 --- /dev/null +++ b/packages/core/src/utils/legacy-opening-datums.ts @@ -0,0 +1,118 @@ +import { roomFace } from '../commands/structure/shared' +import { floorRoomFaces } from '../lib/floor-room-faces' +import { + openingDatumFromSupport, + openingFitsAtDatum, + supportSegmentAt, + wallSupportForNodes, +} from '../lib/opening-floor-datum' +import { roomFloorPlate } from '../lib/room-floor-plate' +import type { AnyNode, DoorNode, SlabNode, WallNode, WindowNode } from '../schema' +import { getWallCurveFrameAt, getWallCurveLength } from '../systems/wall/wall-curve' + +type Facing = { face: 'a' | 'b'; from: number; to: number; zoneId: string; raised: boolean } +const contexts = new WeakMap>>() + +function roomSpans(nodes: Readonly>, levelId: string) { + let levels = contexts.get(nodes) + if (!levels) { + levels = new Map() + contexts.set(nodes, levels) + } + const cached = levels.get(levelId) + if (cached) return cached + const children = Object.values(nodes).filter((node) => node.parentId === levelId) + const faces = floorRoomFaces( + children.filter((node) => node.type === 'wall' || node.type === 'separator'), + ) + const slabs = children.filter((node): node is SlabNode => node.type === 'slab') + const result = new Map() + for (const zone of children) { + if ( + zone.type !== 'zone' || + zone.spaceRole !== 'room' || + zone.hasFloor === false || + zone.floor?.support === 'open' + ) + continue + const room = roomFace(nodes, zone, faces) + const plate = roomFloorPlate(slabs, zone.id) + for (const span of room?.spans ?? []) { + const spans = result.get(span.boundaryId) ?? [] + spans.push({ + face: span.face, + from: span.t0, + to: span.t1, + zoneId: zone.id, + raised: plate?.plateRole === 'platform', + }) + result.set(span.boundaryId, spans) + } + } + levels.set(levelId, result) + return result +} + +/** A legacy wall election changing is not evidence of an authored floor step. */ +export function legacyOpeningFloorChange( + wall: WallNode, + opening: DoorNode | WindowNode, + nodes: Readonly>, + oldSupport: number, + tolerance = 1e-6, + legacyFloor = oldSupport, +) { + const support = wallSupportForNodes(wall, nodes) + const datum = openingDatumFromSupport(wall, opening, support) + const fits = openingFitsAtDatum(wall, opening, datum, nodes, support) + const delta = datum - oldSupport + const length = getWallCurveLength(wall) + const from = Math.max(0, (opening.position[0] - opening.width / 2) / length) + const to = Math.min(1, (opening.position[0] + opening.width / 2) / length) + const heights = [...support.faceDatum.a, ...support.faceDatum.b].flatMap((segment) => { + const a = Math.max(from, segment.start), + b = Math.min(to, segment.end) + return b > a ? [supportSegmentAt(segment, a), supportSegmentAt(segment, b)] : [] + }) + const difference = heights.length ? Math.max(...heights) - Math.min(...heights) : 0 + const chord = (t: number) => { + const { point } = getWallCurveFrameAt(wall, t) + const dx = wall.end[0] - wall.start[0], + dz = wall.end[1] - wall.start[1] + return ((point.x - wall.start[0]) * dx + (point.y - wall.start[1]) * dz) / (dx * dx + dz * dz) + } + const start = chord(from), + end = chord(to) + const spans = (roomSpans(nodes, wall.parentId!).get(wall.id) ?? []).filter( + (span) => span.to > start && span.from < end, + ) + const covered = (face: 'a' | 'b') => { + let cursor = start + for (const span of spans.filter((span) => span.face === face).sort((a, b) => a.from - b.from)) { + if (span.from > cursor + 1e-6) return false + cursor = Math.max(cursor, span.to) + } + return end > start && cursor >= end - 1e-6 + } + const a = covered('a'), + b = covered('b') + const step = difference >= 0.001 - 1e-6 && Math.abs(delta) <= difference + tolerance + const reason = + step && a && b + ? 'between-heights' + : step && spans.some((span) => span.raised && covered(span.face)) + ? 'raised-room' + : delta >= -tolerance && + delta <= Math.min(0.05, legacyFloor - oldSupport) + tolerance && + (a || b) + ? 'finished-floor' + : undefined + return { + datum, + delta, + difference, + reason: fits ? reason : undefined, + fits, + zoneIds: [...new Set(spans.map((span) => span.zoneId))], + } +} diff --git a/packages/core/src/utils/legacy-wall-datums.ts b/packages/core/src/utils/legacy-wall-datums.ts new file mode 100644 index 0000000000..d8f1b3509a --- /dev/null +++ b/packages/core/src/utils/legacy-wall-datums.ts @@ -0,0 +1,263 @@ +import { floorConstructionLift } from '../lib/floor-construction-lift' +import { isFloorAnchoredOpening } from '../lib/floor-opening-footprints' +import { + getOpeningFloorDatum, + getOpeningFloorTarget, + wallSupportForNodes, +} from '../lib/opening-floor-datum' +import { levelBaseElevationAt } from '../lib/terrain-support-query' +import type { AnyNode, SlabNode, WallNode } from '../schema' +import { findLevelBelowId, getAuthoredLevelElevations, getWallPlaneTops } from '../services/storey' +import { computeWallSlabSupport, type WallSlabSupport } from '../systems/slab/slab-support' +import { resolveWallTop } from '../systems/wall/wall-top' + +const legacySupports = new Map>() + +export function legacyWallElevations( + walls: WallNode[], + slabs: SlabNode[], + nodes: Readonly>, + levelId: string, +) { + const orderedWalls = [...walls].sort((a, b) => a.id.localeCompare(b.id)) + const orderedSlabs = [...slabs].sort((a, b) => a.id.localeCompare(b.id)) + const signature = JSON.stringify([ + orderedWalls.map((wall) => [ + wall.id, + wall.start, + wall.end, + wall.thickness, + wall.justification, + wall.curveOffset, + wall.supportOffset, + wall.supportSlabId, + levelBaseElevationAt(nodes, levelId, ...wall.start), + ]), + orderedSlabs.map((slab) => [ + slab.id, + slab.polygon, + slab.holes, + slab.elevation, + slab.thickness, + slab.autoFromWalls, + slab.recessed, + ]), + ]) + const cached = legacySupports.get(signature) + if (cached) return cached + const legacySlabs = orderedSlabs.map((slab) => ({ + ...slab, + boundary: undefined, + plateRole: undefined, + support: undefined, + })) + const supports = new Map( + orderedWalls.map((wall) => [ + wall.id as string, + computeWallSlabSupport( + wall, + legacySlabs, + orderedWalls, + wall.supportSlabId, + undefined, + levelBaseElevationAt(nodes, levelId, ...wall.start), + ), + ]), + ) + legacySupports.set(signature, supports) + if (legacySupports.size > 32) legacySupports.delete(legacySupports.keys().next().value!) + return supports +} + +/** Preserve production datums once, before a level first acquires derived plates. */ +export function preserveLegacyWallDatums( + before: Readonly>, + after: Record, +): Record { + const values = Object.values(before) + const migrated = Object.values(after).some( + (node) => + node.type === 'level' && + node.metadata?.floorOwnershipMigrated === true && + (before[node.id] as typeof node | undefined)?.metadata?.floorOwnershipMigrated !== true, + ) + const newBaseLevels = new Set( + Object.values(after).flatMap((node) => + node.type === 'slab' && node.plateRole === 'base' && node.parentId && !before[node.id] + ? [node.parentId] + : [], + ), + ) + const legacyRoomPlate = + !migrated && + Object.values(after).some( + (node) => + node.type === 'zone' && + node.autoFromWalls && + !before[node.id] && + node.parentId && + newBaseLevels.has(node.parentId), + ) + const pendingLegacyRoomPlate = + !migrated && + [...newBaseLevels].some( + (id) => before[id]?.type === 'level' && before[id].metadata?.legacyRoomMigrationPending, + ) + if ( + !migrated && + !legacyRoomPlate && + !pendingLegacyRoomPlate && + !values.some((node) => node.type === 'slab' && node.autoFromWalls && !node.plateRole) + ) + return after + const existing = new Set( + values.flatMap((node) => (node.type === 'slab' && node.plateRole ? [node.parentId] : [])), + ) + const legacyLevels = [ + ...new Set( + values.flatMap((node) => + node.type === 'wall' && node.parentId && !existing.has(node.parentId) + ? [node.parentId] + : [], + ), + ), + ] + for (const slab of values) { + if ( + slab.type === 'slab' && + slab.autoFromWalls && + !slab.plateRole && + slab.parentId && + !legacyLevels.includes(slab.parentId) + ) + legacyLevels.push(slab.parentId) + } + + const elevations = getAuthoredLevelElevations(before) + for (const levelId of [...legacyLevels]) { + const below = findLevelBelowId(levelId, elevations) + if (below && !existing.has(below) && !legacyLevels.includes(below)) legacyLevels.push(below) + } + + let nodes = after + const write = (node: AnyNode) => { + if (nodes === after) nodes = { ...after } + nodes[node.id] = node + } + for (const levelId of legacyLevels) { + const walls = values.filter((n): n is WallNode => n.type === 'wall' && n.parentId === levelId) + const slabs = values + .filter((n): n is SlabNode => n.type === 'slab' && n.parentId === levelId) + .map((slab) => ({ ...slab, boundary: undefined, support: undefined })) + const oldSupports = legacyWallElevations(walls, slabs, before, levelId) + const oldPlanes = getWallPlaneTops( + walls.filter((wall) => wall.height === undefined), + levelId, + before, + ) + const currentWalls = walls + .map((wall) => after[wall.id]) + .filter((wall): wall is WallNode => wall?.type === 'wall' && wall.height === undefined) + const newPlanes = getWallPlaneTops(currentWalls, levelId, after) + for (const wall of walls) { + let current = after[wall.id] + if (current?.type !== 'wall') continue + const old = oldSupports.get(wall.id)! + let next = wallSupportForNodes(current, after) + if (Math.abs(next.elevation - old.elevation) > 1e-3) { + const oldSupport = old.electedSlabId ? after[old.electedSlabId] : undefined + const keepSlab = + oldSupport?.type === 'slab' && + Math.abs(oldSupport.elevation - old.elevation) <= 1e-3 && + Math.abs( + wallSupportForNodes( + { + ...current, + supportSlabId: oldSupport.id, + supportOffset: old.elevation - oldSupport.elevation, + }, + after, + ).elevation - old.elevation, + ) <= 1e-3 + const ground = levelBaseElevationAt(after, levelId, ...current.start) + current = { + ...current, + supportSlabId: keepSlab ? oldSupport.id : 'ground', + supportOffset: keepSlab + ? old.elevation - oldSupport.elevation + : old.elevation - ground - floorConstructionLift(after, current), + } + write(current) + next = wallSupportForNodes(current, nodes) + } + // Datums read the wall as it now stands (a kept legacy support included). + const datumWall = current + const oldTop = + wall.height === undefined + ? oldPlanes.get(wall.id)! + : (wall.supportSlabId === 'ground' ? old.elevation : Math.max(0, old.elevation)) + + wall.height + const newTop = resolveWallTop(current, newPlanes.get(current.id) ?? 0, next.elevation) + const patch: Partial = {} + if (Math.abs(oldTop - newTop) > 1e-6) patch.height = oldTop - next.elevation + const delta = old.elevation - next.elevation + if (current.faceRegions?.length && Math.abs(delta) > 1e-6) + patch.faceRegions = current.faceRegions.map((region) => { + // Existing regions may already have moved in M4; converted bands have not. + const source = wall.faceRegions?.find((old) => old.id === region.id) ?? region + const { v0: _v0, v1: _v1, ...rest } = region + return { + ...rest, + ...(source.v0 === undefined ? {} : { v0: Math.round((source.v0 + delta) * 1e6) / 1e6 }), + ...(source.v1 === undefined ? {} : { v1: Math.round((source.v1 + delta) * 1e6) / 1e6 }), + } + }) + if (Object.keys(patch).length) write({ ...current, ...patch }) + for (const id of wall.children ?? []) { + const opening = before[id], + current = after[id] + if ( + (opening?.type !== 'door' && opening?.type !== 'window') || + (current?.type !== 'door' && current?.type !== 'window') || + !opening.position || + !current.position + ) + continue + const legacyOpening = { + ...current, + ...opening, + position: opening.position ?? current.position, + height: opening.height ?? current.height, + } + const floorAnchored = isFloorAnchoredOpening(legacyOpening) + const datum = getOpeningFloorDatum(datumWall, legacyOpening, nodes) + let y = legacyOpening.position[1] + old.elevation - datum + let anchor: 'floor' | 'wall' = floorAnchored ? 'floor' : 'wall' + const movedOpening = { + ...legacyOpening, + verticalAnchor: 'floor' as const, + position: [legacyOpening.position[0], y, legacyOpening.position[2]] as [ + number, + number, + number, + ], + } + if ( + floorAnchored && + (Math.abs(getOpeningFloorTarget(datumWall, legacyOpening, nodes) - datum) > 1e-6 || + Math.abs(getOpeningFloorDatum(datumWall, movedOpening, nodes) - datum) > 1e-6) + ) { + anchor = 'wall' + y = legacyOpening.position[1] + old.elevation - next.elevation + } + if (Math.abs(y - current.position[1]) > 1e-6 || (anchor === 'wall' && floorAnchored)) + write({ + ...current, + verticalAnchor: anchor, + position: [current.position[0], Math.round(y * 1e6) / 1e6, current.position[2]], + }) + } + } + } + return nodes +} diff --git a/packages/core/src/utils/node-defaults.ts b/packages/core/src/utils/node-defaults.ts new file mode 100644 index 0000000000..661df110a9 --- /dev/null +++ b/packages/core/src/utils/node-defaults.ts @@ -0,0 +1,82 @@ +import type { z } from 'zod' +import { AnyNode, nodeKindOf } from '../schema/types' + +type DefaultField = { key: string; schema: z.ZodType } + +let defaultsByKind: Map | undefined + +/** + * Kinds whose load migrations all live in the shared server-safe pipeline, so a + * caller that runs only that pipeline (the hosted authority) may fill their + * defaults. Roofs, dormers, items and the rest still migrate in the client + * loader, which reads fields those defaults would supply. + */ +export const STRUCTURE_NODE_KINDS: ReadonlySet = new Set([ + 'slab', + 'ceiling', + 'zone', + 'wall', + 'separator', + 'floor-opening', +]) + +// Only deterministic defaults: a generated id (`objectId`) is not a default a +// load may invent. +function fieldsWithDefaults(shape: Record): DefaultField[] { + const fields: DefaultField[] = [] + for (const [key, schema] of Object.entries(shape)) { + const first = schema.safeParse(undefined) + if (!first.success || first.data === undefined) continue + const second = schema.safeParse(undefined) + if (JSON.stringify(first.data) !== JSON.stringify(second.data)) continue + fields.push({ key, schema }) + } + return fields +} + +function defaultFields(kind: string): DefaultField[] | undefined { + defaultsByKind ??= new Map( + AnyNode.options.map((option) => [ + nodeKindOf(option), + fieldsWithDefaults(option.shape as Record), + ]), + ) + return defaultsByKind.get(kind) +} + +/** + * Fills the schema defaults a stored built-in node leaves out, as the last + * step of every load (client `setScene`, hosted authority). The migrations run + * first on the stored nodes because they read what a node omits (a legacy slab + * without `thickness` is solid down to its level); after them, renderers and + * tools may rely on every defaulted field (`zone.holes`, `slab.holes`, …). + * Only missing top-level fields are added: present values are never parsed, + * coerced or stripped. `kinds` limits it to the kinds whose absence-reading + * migrations the caller has all run ({@link STRUCTURE_NODE_KINDS} for the + * hosted authority). + */ +export function materializeNodeDefaults>( + nodes: T, + kinds?: ReadonlySet, +): { nodes: T; changed: boolean } { + let out: Record | null = null + for (const [id, value] of Object.entries(nodes)) { + if (!value || typeof value !== 'object' || Array.isArray(value)) continue + const node = value as Record + const fields = + typeof node.type === 'string' && (!kinds || kinds.has(node.type)) + ? defaultFields(node.type) + : undefined + if (!fields) continue + let next: Record | null = null + for (const { key, schema } of fields) { + if (node[key] !== undefined) continue + next ??= { ...node } + next[key] = schema.parse(undefined) + } + if (!next) continue + out ??= { ...nodes } + out[id] = next + } + return out ? { nodes: out as T, changed: true } : { nodes, changed: false } +} diff --git a/packages/core/src/utils/normalize-legacy-structure.test.ts b/packages/core/src/utils/normalize-legacy-structure.test.ts new file mode 100644 index 0000000000..0527a3a9c6 --- /dev/null +++ b/packages/core/src/utils/normalize-legacy-structure.test.ts @@ -0,0 +1,146 @@ +import { afterEach, expect, test } from 'bun:test' +import { area } from '../lib/polygon-boolean' +import { detectRoomFaces, extractRooms } from '../lib/room-graph' +import { + type AnyNode, + type AnyNodeId, + BuildingNode, + LevelNode, + SiteNode, + WallNode, +} from '../schema' +import useScene from '../store/use-scene' +import { + ensureSceneOpenings, + healSceneNodes, + migrateCeilingRoomLinks, + migrateFloorPlates, + migrateRoomZones, + migrateSlabSlots, + migrateVerticalSceneNodes, + migrateWallFaceBands, + migrateWallFaceKeys, + normalizeLegacyStructure, + reconcileStructureOnLoad, + removeRetiredDrawingSheetNodes, +} from './scene-migrations' + +const previous = useScene.getState() +afterEach(() => useScene.setState(previous, true)) + +test('legacy documentation-only zones retain metadata without inventing a room boundary', () => { + const source = { + zone_docs: { id: 'zone_docs', type: 'zone', name: 'Ward', metadata: { capacity: 2 } }, + zone_room: { id: 'zone_room', type: 'zone', spaceRole: 'room' }, + } + const normalized = normalizeLegacyStructure(source) + expect(normalized.zone_docs).toEqual({ ...source.zone_docs, polygon: [] }) + expect(normalized.zone_room).toEqual({ ...source.zone_room, name: 'Room' }) + expect(source.zone_docs).not.toHaveProperty('polygon') + expect(normalizeLegacyStructure(normalized)).toBe(normalized) +}) + +function source(embedded: boolean) { + const polygon: [number, number][] = [ + [0, 0], + [0.9, 0], + [0.9, 0.9], + [0, 0.9], + ] + const walls = polygon.map((start, i) => ({ + ...WallNode.parse({ + id: `wall_${i}`, + parentId: 'level_legacy', + start, + end: polygon[(i + 1) % 4], + thickness: 0.1, + justification: 'a', + }), + assemblyLayers: [{ thickness: 0.5 }], + })) + const level = LevelNode.parse({ + id: 'level_legacy', + parentId: 'building_legacy', + children: walls.map((w) => w.id), + }) + const building = BuildingNode.parse({ + id: 'building_legacy', + parentId: 'site_legacy', + children: [level.id], + }) + const site = { + ...SiteNode.parse({ id: 'site_legacy' }), + children: embedded ? [building] : [building.id], + } + return Object.fromEntries( + [site, level, ...walls, ...(embedded ? [] : [building])].map((n) => [n.id, n]), + ) +} + +// The authority prunes to root reachability after the shared migrations. +function authorityLoad(sourceNodes: Record, roots: string[]) { + const normalized = normalizeLegacyStructure(sourceNodes) + const healed = healSceneNodes(normalized) + const retired = removeRetiredDrawingSheetNodes(healed.nodes) + const vertical = migrateVerticalSceneNodes(retired.nodes) + const rooms = migrateRoomZones(vertical.nodes) + const ceilings = migrateCeilingRoomLinks(rooms.nodes) + const plates = migrateFloorPlates(ceilings.nodes) + const slots = migrateSlabSlots(plates.nodes) + const openings = ensureSceneOpenings(slots.nodes) + const walls = migrateWallFaceBands(migrateWallFaceKeys(openings.nodes).nodes) + const nodes = reconcileStructureOnLoad(walls.nodes, vertical.nodes).nodes + const reachable = new Set() + const pending = [...roots] + while (pending.length) { + const id = pending.pop()! + const node = nodes[id] + if (!node || reachable.has(id)) continue + reachable.add(id) + if ('children' in node && Array.isArray(node.children)) pending.push(...node.children) + } + return Object.fromEntries(Object.entries(nodes).filter(([id]) => reachable.has(id))) +} + +for (const embedded of [false, true]) { + test(`complete client and authority load paths agree with legacy layers and embedded building=${embedded}`, () => { + const original = source(embedded) + const saved = JSON.stringify(original) + const server = authorityLoad(original, ['site_legacy']) + useScene.getState().setScene(original as Record, ['site_legacy']) + const client = useScene.getState().nodes + const rooms = (nodes: Record) => + Object.values(nodes) + .filter((n) => n.type === 'zone') + .sort((a, b) => a.id.localeCompare(b.id)) + expect(rooms(client)).toHaveLength(1) + expect(rooms(server)).toEqual(rooms(client)) + expect(server.building_legacy).toMatchObject({ + parentId: 'site_legacy', + children: ['level_legacy'], + }) + expect(server.level_legacy).toMatchObject({ + children: expect.arrayContaining([rooms(server)[0]!.id]), + }) + expect(JSON.stringify(original)).toBe(saved) + const normalized = normalizeLegacyStructure(original) + expect(normalizeLegacyStructure(normalized)).toBe(normalized) + expect(normalized.wall_0).toMatchObject({ thickness: 0.5 }) + expect(normalized.wall_0).not.toHaveProperty('assemblyLayers') + }) +} + +test('reference-area eligibility does not depend on wall thickness', () => { + const nodes = source(false) + const walls = Object.values(nodes).filter((n) => n.type === 'wall') as WallNode[] + const reference = detectRoomFaces(walls) + expect(reference).toHaveLength(1) + const thickRoom = extractRooms(walls.map((wall) => ({ ...wall, thickness: 0.5 })))[0]! + expect(area([{ outer: thickRoom.polygon.map(({ x, y }) => [x, y]), holes: [] }])).toBeLessThan( + 0.5, + ) + expect(area([{ outer: reference[0]!.polygon, holes: [] }])).toBeGreaterThan(0.5) + for (const thickness of [0.01, 0.5, 0.8]) { + expect(detectRoomFaces(walls.map((wall) => ({ ...wall, thickness })))).toEqual(reference) + } +}) diff --git a/packages/core/src/utils/normalize-legacy-structure.ts b/packages/core/src/utils/normalize-legacy-structure.ts new file mode 100644 index 0000000000..2f0068c9bc --- /dev/null +++ b/packages/core/src/utils/normalize-legacy-structure.ts @@ -0,0 +1,65 @@ +export function normalizeLegacyStructure(source: Record): Record { + const nodes: Record = { ...source } + let changed = false + for (const [id, node] of Object.entries(nodes)) { + if (node?.type !== 'site' || !Array.isArray(node.children)) continue + const children = node.children.map((child: any) => { + if (!child || typeof child !== 'object' || typeof child.id !== 'string') return child + if (!nodes[child.id]) nodes[child.id] = { ...child, parentId: id } + changed = true + return child.id + }) + if (children.some((child: unknown, index: number) => child !== node.children[index])) { + nodes[id] = { ...node, children } + } + } + for (const [id, node] of Object.entries(nodes)) { + // Door/window normalization parses defaults before structural migration. + // Retain absence here so old openings cannot look like newly created ones. + if ( + (node?.type === 'door' || node?.type === 'window') && + node.floorThresholdVersion === undefined + ) { + nodes[id] = { ...node, floorThresholdVersion: 0 } + changed = true + continue + } + // Legacy documentation-only zones have no boundary. Preserve their metadata + // as an empty generic zone instead of feeding an absent ring to topology. + if ( + node?.type === 'zone' && + node.polygon === undefined && + (node.spaceRole === undefined || node.spaceRole === 'generic') && + node.autoFromWalls !== true + ) { + nodes[id] = { + ...node, + name: typeof node.name === 'string' ? node.name : 'Zone', + polygon: [], + } + changed = true + continue + } + if (node?.type === 'zone' && typeof node.name !== 'string') { + nodes[id] = { ...node, name: node.spaceRole === 'room' ? 'Room' : 'Zone' } + changed = true + continue + } + if (node?.type !== 'wall' || !Object.hasOwn(node, 'assemblyLayers')) continue + const thickness = Array.isArray(node.assemblyLayers) + ? node.assemblyLayers.reduce( + (total: number, layer: any) => + typeof layer?.thickness === 'number' && + Number.isFinite(layer.thickness) && + layer.thickness > 0 + ? total + layer.thickness + : total, + 0, + ) + : 0 + const { assemblyLayers: _layers, ...wall } = node + nodes[id] = thickness > 0 ? { ...wall, thickness } : wall + changed = true + } + return changed ? nodes : source +} diff --git a/packages/core/src/utils/omit-undefined.ts b/packages/core/src/utils/omit-undefined.ts new file mode 100644 index 0000000000..2b2aee42dc --- /dev/null +++ b/packages/core/src/utils/omit-undefined.ts @@ -0,0 +1,16 @@ +// Scene JSON omits undefined object properties, including nested material and intent fields. +export function omitUndefined(value: T): T { + if (Array.isArray(value)) { + const entries = value.map((entry) => omitUndefined(entry)) + return entries.some((entry, index) => entry !== value[index]) ? (entries as T) : value + } + if (value === null || typeof value !== 'object') return value + const entries = Object.entries(value) + const cleaned = entries + .filter(([, entry]) => entry !== undefined) + .map(([key, entry]) => [key, omitUndefined(entry)] as const) + return cleaned.length !== entries.length || + cleaned.some(([, entry], index) => entry !== entries[index]![1]) + ? (Object.fromEntries(cleaned) as T) + : value +} diff --git a/packages/core/src/utils/owned-floor-opening-migration.test.ts b/packages/core/src/utils/owned-floor-opening-migration.test.ts new file mode 100644 index 0000000000..b1b673fcce --- /dev/null +++ b/packages/core/src/utils/owned-floor-opening-migration.test.ts @@ -0,0 +1,76 @@ +import { expect, test } from 'bun:test' +import { CeilingNode, LevelNode, SlabNode, StairNode, StairSegmentNode } from '../schema' +import { + materializeLegacyAutoOpenings, + migrateOwnedFloorOpenings, +} from './owned-floor-opening-migration' + +const polygon: [number, number][] = [ + [0, 0], + [5, 0], + [5, 5], + [0, 5], +] +const hole: [number, number][] = [ + [1, 1], + [2, 1], + [2, 2], + [1, 2], +] + +test('load drops orphaned stair cuts on slabs and ceilings instead of adopting manual openings', () => { + const level = LevelNode.parse({ id: 'level_legacy', level: 0 }) + const slab = SlabNode.parse({ + id: 'slab_legacy', + parentId: level.id, + polygon, + holes: [hole], + holeMetadata: [{ source: 'stair', stairId: 'stair_deleted' }], + }) + const ceiling = CeilingNode.parse({ + id: 'ceiling_legacy', + parentId: level.id, + polygon, + holes: [hole], + holeMetadata: [{ source: 'stair', stairId: 'stair_deleted' }], + }) + const source = { [level.id]: level, [slab.id]: slab, [ceiling.id]: ceiling } + const cleaned = materializeLegacyAutoOpenings(source, true) + expect((cleaned[slab.id] as typeof slab).holes).toEqual([]) + expect((cleaned[ceiling.id] as typeof ceiling).holes).toEqual([]) + expect(migrateOwnedFloorOpenings(cleaned).changed).toBe(false) + expect(materializeLegacyAutoOpenings(cleaned, true)).toBe(cleaned) +}) + +test('load syncs a legacy stair to its saved level rise when its old level links are stale', () => { + const lower = LevelNode.parse({ id: 'level_lower', level: 0, height: 4.3 }) + const upper = LevelNode.parse({ id: 'level_upper', level: 1, height: 3 }) + const stair = StairNode.parse({ + id: 'stair_legacy', + parentId: lower.id, + position: [10, 0, 10], + fromLevelId: 'level_removed', + toLevelId: 'level_removed', + }) + const flight = StairSegmentNode.parse({ + id: 'sseg_legacy', + parentId: stair.id, + height: 3.65, + length: 4, + }) + const slab = SlabNode.parse({ + id: 'slab_upper', + parentId: upper.id, + autoFromWalls: true, + polygon, + }) + lower.children = [stair.id] + upper.children = [slab.id] + stair.children = [flight.id] + const source = Object.fromEntries( + [lower, upper, stair, flight, slab].map((node) => [node.id, node]), + ) + const loaded = materializeLegacyAutoOpenings(source, true) + expect((loaded[flight.id] as typeof flight).height).toBeCloseTo(4.3) + expect(materializeLegacyAutoOpenings(loaded, true)).toBe(loaded) +}) diff --git a/packages/core/src/utils/owned-floor-opening-migration.ts b/packages/core/src/utils/owned-floor-opening-migration.ts new file mode 100644 index 0000000000..b008444f8c --- /dev/null +++ b/packages/core/src/utils/owned-floor-opening-migration.ts @@ -0,0 +1,314 @@ +import { canonicalOpeningRing } from '../lib/canonical-opening-ring' +import { area, type Ring } from '../lib/polygon-boolean' +import type { AnyNode, CeilingNode, SlabNode, StairNode } from '../schema' +import { FloorOpeningNode } from '../schema/nodes/floor-opening' +import { syncAutoElevatorOpenings } from '../systems/elevator/elevator-opening-sync' +import { ensureMissingSlabOpenings } from '../systems/slab/ensure-slab-openings' +import { syncAutoStairOpenings } from '../systems/stair/stair-opening-sync' +import { syncStairRises } from '../systems/stair/stair-rise-query' + +export function materializeLegacyAutoOpenings( + sourceNodes: Record, + refreshExisting = false, +) { + let nodes = sourceNodes as Record + for (const surface of Object.values(nodes)) { + if (surface.type !== 'slab' && surface.type !== 'ceiling') continue + const kept = (surface.holes ?? []).flatMap((hole, index) => { + const metadata = surface.holeMetadata?.[index] + if (metadata?.source !== 'stair' && metadata?.source !== 'elevator') + return [{ hole, metadata: metadata ?? { source: 'manual' as const } }] + const ownerId = metadata.source === 'stair' ? metadata.stairId : metadata.elevatorId + return ownerId && nodes[ownerId]?.type === metadata.source ? [{ hole, metadata }] : [] + }) + if (kept.length === (surface.holes ?? []).length) continue + if (nodes === sourceNodes) nodes = { ...nodes } + nodes[surface.id] = { + ...surface, + holes: kept.map((entry) => entry.hole), + holeMetadata: kept.map((entry) => entry.metadata), + } + } + if ( + !Object.values(nodes).some( + (node) => (node as AnyNode).type === 'stair' || (node as AnyNode).type === 'elevator', + ) + ) + return nodes + if ( + refreshExisting && + !Object.values(nodes).some( + (node) => + (node as SlabNode).type === 'slab' && + (node as SlabNode).autoFromWalls && + !(node as SlabNode).plateRole, + ) + ) + return nodes + if ( + Object.values(nodes).some( + (node) => + (node as AnyNode).type === 'floor-opening' && + ((node as FloorOpeningNode).source === 'stair' || + (node as FloorOpeningNode).source === 'elevator'), + ) + ) + return nodes + let pending = true + while (pending) { + pending = false + for (const derive of [syncAutoElevatorOpenings, syncStairRises, syncAutoStairOpenings]) { + const updates = + derive === syncStairRises + ? syncStairRises(nodes, (stair: StairNode) => stair.position[1], true) + : !refreshExisting + ? ensureMissingSlabOpenings(nodes, derive(nodes)) + : derive(nodes) + if (refreshExisting && derive !== syncStairRises) + for (const update of updates) { + const current = nodes[update.id] + if (current?.type !== 'slab' && current?.type !== 'ceiling') continue + const data = update.data as Partial + if (!data.holes || !data.holeMetadata) continue + const ownerKey = (entry: (typeof current.holeMetadata)[number]) => + entry.source === 'stair' + ? `stair:${entry.stairId}` + : entry.source === 'elevator' + ? `elevator:${entry.elevatorId}` + : undefined + const generated = new Set(data.holeMetadata.map(ownerKey).filter(Boolean)) + for (const [index, hole] of current.holes.entries()) { + const metadata = current.holeMetadata[index] + const owner = metadata && ownerKey(metadata) + if (!owner || generated.has(owner)) continue + data.holes = [...data.holes, hole] + data.holeMetadata = [...data.holeMetadata, metadata] + } + } + const effectiveUpdates = updates.filter(({ id, data }) => + Object.entries(data).some( + ([key, value]) => + JSON.stringify((nodes[id] as unknown as Record)?.[key]) !== + JSON.stringify(value), + ), + ) + if (!effectiveUpdates.length) continue + pending = true + nodes = { ...nodes } + for (const { id, data } of effectiveUpdates) nodes[id] = { ...nodes[id], ...data } as AnyNode + } + } + return nodes +} + +function ringSignature(polygon: Ring) { + const quantized = polygon.map(([x, z]) => [Math.round(x * 10_000), Math.round(z * 10_000)]) + const signatures = [quantized, [...quantized].reverse()].flatMap((ring) => + ring.map((_, index) => JSON.stringify([...ring.slice(index), ...ring.slice(0, index)])), + ) + return signatures.sort()[0] +} + +function openingId(surfaceId: string, ownerId: string | undefined, polygon: Ring) { + const seed = JSON.stringify([surfaceId, ownerId ?? '', ringSignature(polygon)]) + let hash = 0xcbf2_9ce4_8422_2325n + for (const byte of new TextEncoder().encode(seed)) + hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100_0000_01b3n) + return `floor-opening_${hash.toString(36).padStart(16, '0')}` +} + +function collapseOwnedOpenings(sourceNodes: Record) { + const groups = new Map() + for (const value of Object.values(sourceNodes)) { + const opening = value as FloorOpeningNode + if ( + opening.type !== 'floor-opening' || + (opening.source !== 'stair' && opening.source !== 'elevator') || + !opening.ownerId || + !opening.parentId || + (sourceNodes[opening.ownerId] as AnyNode | undefined)?.type !== opening.source + ) + continue + const key = JSON.stringify([opening.source, opening.ownerId, opening.parentId]) + groups.set(key, [...(groups.get(key) ?? []), opening]) + } + let nodes = sourceNodes + const remap = new Map() + for (const openings of groups.values()) { + if (openings.length < 2) continue + openings.sort( + (a, b) => + Number(!!b.surfaceId) - Number(!!a.surfaceId) || + Number(!!b.metadata?.ownerPose) - Number(!!a.metadata?.ownerPose) || + a.id.localeCompare(b.id), + ) + const keeper = openings[0]! + const merged: Partial = {} + for (const field of ['legacyPlateCuts', 'legacyCeilingCuts'] as const) { + const cuts: Record = {} + for (const opening of openings) + for (const [surfaceId, rings] of Object.entries(opening[field] ?? {})) { + const known = new Set((cuts[surfaceId] ?? []).map(ringSignature)) + for (const ring of rings) + if (!known.has(ringSignature(ring))) { + cuts[surfaceId] = [...(cuts[surfaceId] ?? []), ring] + known.add(ringSignature(ring)) + } + } + if (field === 'legacyPlateCuts' && keeper.source === 'stair') { + const entries = Object.entries(cuts) + if (entries.length > 1 && entries.every(([, rings]) => rings.length === 1)) { + const largest = entries + .map(([, rings]) => rings[0]!) + .sort((a, b) => area([{ outer: b, holes: [] }]) - area([{ outer: a, holes: [] }]))[0]! + const extent = (ring: Ring) => [ + Math.min(...ring.map(([x]) => x)), + Math.max(...ring.map(([x]) => x)), + Math.min(...ring.map(([, z]) => z)), + Math.max(...ring.map(([, z]) => z)), + ] + const bounds = extent(largest) + if ( + entries.every(([, rings]) => { + const ring = rings[0]! + return ( + ring.length === largest.length && + extent(ring).every((value, index) => Math.abs(value - bounds[index]!) <= 0.0021) + ) + }) + ) + for (const [surfaceId] of entries) cuts[surfaceId] = [largest] + } + } + if (Object.keys(cuts).length) merged[field] = cuts + } + if (nodes === sourceNodes) nodes = { ...sourceNodes } + nodes[keeper.id] = { ...keeper, ...merged } + for (const duplicate of openings.slice(1)) { + remap.set(duplicate.id, keeper.id) + delete nodes[duplicate.id] + } + } + if (!remap.size) return nodes + for (const value of Object.values(nodes)) { + const node = value as AnyNode + if (node.type === 'level') { + const children = node.children.filter((id) => !remap.has(id)) + if (children.length !== node.children.length) nodes[node.id] = { ...node, children } + continue + } + if (node.type !== 'slab' && node.type !== 'ceiling') continue + const retained: Array<{ hole: Ring; metadata: (typeof node.holeMetadata)[number] }> = [] + const seen = new Set() + for (const [index, hole] of (node.holes ?? []).entries()) { + const metadata = node.holeMetadata?.[index] ?? { source: 'manual' as const } + const openingId = metadata.source === 'floor-opening' ? metadata.openingId : undefined + const mapped = openingId ? remap.get(openingId) : undefined + const next = mapped ? { ...metadata, openingId: mapped } : metadata + const key = next.source === 'floor-opening' ? `${next.openingId}:${ringSignature(hole)}` : '' + if (key && seen.has(key)) continue + if (key) seen.add(key) + retained.push({ hole, metadata: next }) + } + const currentIds = node.type === 'ceiling' ? node.openingIds : undefined + const openingIds = currentIds + ? [...new Set(currentIds.map((id) => remap.get(id) ?? id))] + : undefined + if ( + retained.length !== (node.holes ?? []).length || + retained.some((entry, index) => entry.metadata !== node.holeMetadata?.[index]) || + (openingIds && JSON.stringify(openingIds) !== JSON.stringify(currentIds)) + ) + nodes[node.id] = { + ...node, + holes: retained.map((entry) => entry.hole), + holeMetadata: retained.map((entry) => entry.metadata), + ...(openingIds ? { openingIds } : {}), + } + } + return nodes +} + +export function migrateOwnedFloorOpenings(sourceNodes: Record) { + let nodes = sourceNodes + for (const value of Object.values(sourceNodes)) { + const surface = value as SlabNode | CeilingNode + if ( + (surface.type !== 'slab' && surface.type !== 'ceiling') || + !surface.parentId || + !Array.isArray(surface.holes) + ) + continue + const kept: Array<{ hole: Ring; metadata: (typeof surface.holeMetadata)[number] }> = [] + let removed = false + for (const [index, hole] of surface.holes.entries()) { + const metadata = surface.holeMetadata?.[index] ?? { source: 'manual' as const } + if (metadata.source !== 'stair' && metadata.source !== 'elevator') { + kept.push({ hole, metadata }) + continue + } + if (area([{ outer: hole, holes: [] }]) < 1e-4) { + kept.push({ hole, metadata }) + continue + } + const candidateId = metadata.source === 'stair' ? metadata.stairId : metadata.elevatorId + const owner = candidateId ? (sourceNodes[candidateId] as AnyNode | undefined) : undefined + const ownerId = owner?.type === metadata.source ? candidateId : undefined + const id = openingId(surface.id, ownerId, hole) + const existing = nodes[id] as FloorOpeningNode | undefined + const field = surface.type === 'slab' ? 'legacyPlateCuts' : 'legacyCeilingCuts' + const cuts = { ...(existing?.[field] ?? {}), [surface.id]: [hole] } + if (nodes === sourceNodes) nodes = { ...sourceNodes } + nodes[id] = + existing?.type === 'floor-opening' + ? { ...existing, [field]: cuts } + : FloorOpeningNode.parse({ + id, + parentId: surface.parentId, + name: ownerId + ? `${metadata.source === 'stair' ? 'Stair' : 'Elevator'} opening` + : 'Floor opening', + polygon: ownerId ? canonicalOpeningRing(hole) : hole, + source: ownerId ? metadata.source : 'manual', + ...(ownerId ? { ownerId } : {}), + surfaceId: surface.id, + drawnOn: surface.type === 'slab' ? 'floor' : 'ceiling', + cutsPrimary: true, + cutsAdjacent: false, + [field]: cuts, + }) + const level = nodes[surface.parentId] as AnyNode | undefined + if (level?.type === 'level' && !level.children.includes(id as never)) + nodes[level.id] = { ...level, children: [...level.children, id as never] } + removed = true + if ( + surface.type === 'ceiling' + ? surface.boundary !== 'auto' + : surface.boundary !== 'auto' && !surface.autoFromWalls + ) + kept.push({ hole, metadata: { source: 'floor-opening', openingId: id } }) + } + if (removed) { + if (nodes === sourceNodes) nodes = { ...sourceNodes } + nodes[surface.id] = { + ...surface, + holes: kept.map((entry) => entry.hole), + holeMetadata: kept.map((entry) => entry.metadata), + } + } + } + nodes = collapseOwnedOpenings(nodes) + for (const value of Object.values(nodes)) { + const opening = value as FloorOpeningNode + if ( + opening.type !== 'floor-opening' || + (opening.source !== 'stair' && opening.source !== 'elevator') + ) + continue + const polygon = canonicalOpeningRing(opening.polygon) + if (JSON.stringify(polygon) === JSON.stringify(opening.polygon)) continue + if (nodes === sourceNodes) nodes = { ...sourceNodes } + nodes[opening.id] = { ...opening, polygon } + } + return { nodes, changed: nodes !== sourceNodes } +} diff --git a/packages/core/src/utils/reconcile-structure-on-load.test.ts b/packages/core/src/utils/reconcile-structure-on-load.test.ts new file mode 100644 index 0000000000..7b1e6a79d2 --- /dev/null +++ b/packages/core/src/utils/reconcile-structure-on-load.test.ts @@ -0,0 +1,319 @@ +import { afterEach, expect, test } from 'bun:test' +import { reconcileSceneStructure } from '../lib/structure-reconcile' +import { + type AnyNode, + CeilingNode, + FloorOpeningNode, + LevelNode, + SlabNode, + StairNode, + WallNode, + ZoneNode, +} from '../schema' +import useScene, { clearSceneHistory } from '../store/use-scene' +import { alignLegacyStairCuts } from './reconcile-structure-on-load' +import { + createStructureIdFactory, + migrateCeilingRoomLinks, + migrateRoomZones, + reconcileStructureOnLoad, +} from './scene-migrations' + +function room(suffix = 'load', hasCeiling = true) { + const polygon: [number, number][] = [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ] + const level = LevelNode.parse({ id: `level_${suffix}`, height: 3 }) + const walls = polygon.map((start, i) => + WallNode.parse({ + id: `wall_${suffix}_${i}`, + parentId: level.id, + start, + end: polygon[(i + 1) % 4], + }), + ) + // A room the editor drew (seed and boundaries set) whose construction is still missing. + const zone = ZoneNode.parse({ + id: `zone_${suffix}`, + parentId: level.id, + polygon, + name: 'Room', + spaceRole: 'room', + autoFromWalls: true, + seed: [2, 2], + boundaryWallIds: walls.map((wall) => wall.id).sort(), + ...(hasCeiling ? {} : { hasCeiling: false }), + }) + level.children = [...walls.map((wall) => wall.id), zone.id] + return Object.fromEntries([level, ...walls, zone].map((node) => [node.id, node])) +} +function surfaces(nodes: Record) { + return Object.values(nodes).filter((node) => node.type === 'slab' || node.type === 'ceiling') +} +const previous = useScene.getState() +afterEach(() => { + useScene.setState(previous, true) + clearSceneHistory() +}) + +test('load creates missing plate and ceiling purely, deterministically and idempotently', () => { + const nodes = room(), + snapshot = structuredClone(nodes) + const first = reconcileStructureOnLoad(nodes) + expect(first.changed).toBe(true) + expect(nodes).toEqual(snapshot) + expect( + surfaces(first.nodes) + .map((node) => node.type) + .sort(), + ).toEqual(['ceiling', 'slab']) + expect(reconcileStructureOnLoad(first.nodes)).toEqual({ nodes: first.nodes, changed: false }) + expect(reconcileStructureOnLoad(first.nodes).nodes).toBe(first.nodes) + expect( + reconcileStructureOnLoad(Object.fromEntries(Object.entries(nodes).reverse())).nodes, + ).toEqual(first.nodes) + for (const surface of surfaces(first.nodes)) + expect((first.nodes.level_load as LevelNode).children).toContain(surface.id) +}) + +test('a scene saved after editor reconciliation is an identity no-op on load', () => { + let id = 0 + const saved = reconcileSceneStructure({ + nodes: room(), + mintId: (kind) => `${kind}_editor_${id++}`, + }).nodes + expect(reconcileStructureOnLoad(saved)).toEqual({ nodes: saved, changed: false }) + expect(reconcileStructureOnLoad(saved).nodes).toBe(saved) +}) + +test('load respects hasCeiling false and hasFloor false', () => { + const nodes = room('disabled', false) + expect(surfaces(reconcileStructureOnLoad(nodes).nodes).map((n) => n.type)).toEqual(['slab']) + nodes.zone_disabled = { ...nodes.zone_disabled, hasFloor: false } as ZoneNode + expect(surfaces(reconcileStructureOnLoad(nodes).nodes)).toEqual([]) +}) + +test('legacy rooms without a saved ceiling stay ceilingless beside a room with one', () => { + // A main-era level: two rooms, a ceiling drawn over one of them only. + const level = LevelNode.parse({ id: 'level_partial', height: 3 }) + const ring: [number, number][] = [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ] + const walls = [ + ...ring.map((start, i) => + WallNode.parse({ + id: `wall_partial_${i}`, + parentId: level.id, + start, + end: ring[(i + 1) % 4], + }), + ), + WallNode.parse({ id: 'wall_partial_divider', parentId: level.id, start: [2, 0], end: [2, 4] }), + ] + const ceiling = CeilingNode.parse({ + id: 'ceiling_partial', + parentId: level.id, + autoFromWalls: true, + polygon: [ + [0, 0], + [2, 0], + [2, 4], + [0, 4], + ], + }) + level.children = [...walls.map((wall) => wall.id), ceiling.id] + const legacy = Object.fromEntries([level, ...walls, ceiling].map((node) => [node.id, node])) + const load = (nodes: Record) => + reconcileStructureOnLoad(migrateCeilingRoomLinks(migrateRoomZones(nodes).nodes).nodes, nodes) + .nodes as Record + const loaded = load(legacy) + const ceilings = Object.values(loaded).filter((node) => node.type === 'ceiling') + expect(ceilings.map((node) => node.id)).toEqual(['ceiling_partial']) + const rooms = Object.values(loaded).filter((node): node is ZoneNode => node.type === 'zone') + expect(rooms.map((room) => room.hasCeiling).sort()).toEqual([false, undefined]) + expect(rooms.find((room) => room.hasCeiling === false)!.id).not.toBe( + (ceilings[0] as CeilingNode).zoneId, + ) + expect(load(loaded)).toEqual(loaded) +}) + +test('load keeps a saved ceiling height the kernel would clamp, and reloads unchanged', () => { + const nodes: Record = room('tall') + const ceiling = CeilingNode.parse({ + id: 'ceiling_tall', + parentId: 'level_tall', + polygon: [ + [0, 0], + [4, 0], + [4, 4], + [0, 4], + ], + height: 5, + }) + nodes[ceiling.id] = ceiling + ;(nodes.level_tall as LevelNode).children.push(ceiling.id) + const loaded = reconcileStructureOnLoad(nodes).nodes + expect((loaded.ceiling_tall as CeilingNode).height).toBe(5) + expect(reconcileStructureOnLoad(loaded).nodes).toBe(loaded) +}) + +test('load IDs depend on owning boundaries, not unrelated levels or node insertion order', () => { + const alone = reconcileStructureOnLoad(room()).nodes + const combined = reconcileStructureOnLoad({ ...room('elsewhere'), ...room() }).nodes + expect( + surfaces(combined) + .filter((n) => n.parentId === 'level_load') + .map((n) => n.id) + .sort(), + ).toEqual( + surfaces(alone) + .map((n) => n.id) + .sort(), + ) +}) + +test('shared FNV structure IDs sort UTF-8 boundaries and skip existing and minted IDs', () => { + const first = createStructureIdFactory({})('ceiling', ['wall_é', 'separator_a']) + expect(createStructureIdFactory({})('ceiling', ['separator_a', 'wall_é'])).toBe(first) + const mint = createStructureIdFactory({ [first]: {} }) + const second = mint('ceiling', ['wall_é', 'separator_a']) + expect(second).not.toBe(first) + expect(mint('ceiling', ['wall_é', 'separator_a'])).not.toBe(second) +}) + +test('client hydration creates the same missing construction as the shared final migration', async () => { + const nodes = room() + const expected = reconcileStructureOnLoad(nodes) + useScene.getState().setScene(nodes, ['level_load']) + await new Promise((resolve) => queueMicrotask(resolve)) + expect(surfaces(useScene.getState().nodes)).toEqual(surfaces(expected.nodes)) + expect(reconcileStructureOnLoad(useScene.getState().nodes).changed).toBe(false) +}) + +test('load drops an orphan stair hole instead of turning it into a manual opening', () => { + const saved = reconcileStructureOnLoad(room()).nodes + const plate = surfaces(saved).find((node) => node.type === 'slab')! + const hole: [number, number][] = [ + [-1.123_456_789, 1], + [2, 1], + [2, 2], + [-1.123_456_789, 2], + ] + const nodes = { + ...saved, + [plate.id]: { + ...plate, + holes: [hole], + holeMetadata: [{ source: 'stair', stairId: 'stair_saved' }], + }, + } + const loaded = reconcileStructureOnLoad(nodes) + const migratedPlate = loaded.nodes[plate.id] + expect(migratedPlate?.type).toBe('slab') + if (migratedPlate?.type !== 'slab') return + expect(migratedPlate.holes).toEqual([]) + expect(migratedPlate.holeMetadata).toEqual([]) + expect(Object.values(loaded.nodes).filter((node) => node.type === 'floor-opening')).toEqual([]) + expect(reconcileStructureOnLoad(loaded.nodes).nodes).toBe(loaded.nodes) +}) + +test('a legacy stair cut in a shared stairwell snaps to the ceiling hole its sibling stair recorded', () => { + const stairA = StairNode.parse({ id: 'stair_a', fromLevelId: 'level_0', toLevelId: 'level_1' }) + const stairB = StairNode.parse({ id: 'stair_b', fromLevelId: 'level_0', toLevelId: 'level_1' }) + const ceilingHole: [number, number][] = [ + [0, 0], + [2, 0], + [2, 4], + [0, 4], + ] + const nearlyShared: [number, number][] = [ + [0.1, 0], + [2.1, 0], + [2.1, 4], + [0.1, 4], + ] + const elsewhere: [number, number][] = [ + [5, 5], + [6, 5], + [6, 6], + [5, 6], + ] + const first = FloorOpeningNode.parse({ + id: 'floor-opening_a', + parentId: 'level_1', + source: 'stair', + ownerId: stairA.id, + polygon: ceilingHole, + legacyCeilingCuts: { ceiling_0: [ceilingHole] }, + }) + const second = FloorOpeningNode.parse({ + id: 'floor-opening_b', + parentId: 'level_1', + source: 'stair', + ownerId: stairB.id, + polygon: nearlyShared, + legacyPlateCuts: { slab_1: [nearlyShared, elsewhere] }, + }) + const nodes: Record = Object.fromEntries( + [stairA, stairB, first, second].map((node) => [node.id, node]), + ) + const aligned = alignLegacyStairCuts(nodes) + expect(aligned[second.id]).toMatchObject({ + legacyPlateCuts: { slab_1: [ceilingHole, elsewhere] }, + }) + expect(aligned[first.id]).toBe(first) + expect(nodes[second.id]).toBe(second) + expect(alignLegacyStairCuts(aligned)).toBe(aligned) + // A stair to a different level is not in the same stairwell. + const unrelated = { ...nodes, [stairA.id]: { ...stairA, toLevelId: 'level_2' } } + expect(alignLegacyStairCuts(unrelated)).toBe(unrelated) +}) + +test('new room IDs are remapped through grouped plates and ceilings in one load', () => { + const nodes: Record = room() + delete nodes.zone_load + const divider = WallNode.parse({ + id: 'wall_divider', + parentId: 'level_load', + start: [2, 0], + end: [2, 4], + }) + nodes[divider.id] = divider + const first = reconcileStructureOnLoad(nodes) + const zones = Object.values(first.nodes).filter((node) => node.type === 'zone') + const plates = Object.values(first.nodes).filter((node) => node.type === 'slab') + expect(zones).toHaveLength(2) + expect(plates).toHaveLength(1) + expect(plates[0]!.zoneIds).toEqual(zones.map((zone) => zone.id).sort()) + for (const ceiling of surfaces(first.nodes).filter((node) => node.type === 'ceiling')) { + expect(zones.map((zone) => zone.id)).toContain(ceiling.zoneId) + } + expect(reconcileStructureOnLoad(first.nodes).nodes).toBe(first.nodes) +}) + +test('load preserves legacy recessed slabs while filling missing ceilings', () => { + const nodes: Record = room() + const slab = SlabNode.parse({ + id: 'slab_pool', + parentId: 'level_load', + autoFromWalls: true, + recessed: true, + polygon: (nodes.zone_load as ZoneNode).polygon, + }) + nodes[slab.id] = slab + const first = reconcileStructureOnLoad(nodes) + expect(first.nodes[slab.id]).toEqual({ ...slab, autoFromWalls: false }) + // The recess is the room's floor: no generated wall ring stacks around it. + expect( + surfaces(first.nodes) + .map((node) => node.type) + .sort(), + ).toEqual(['ceiling', 'slab']) + expect(reconcileStructureOnLoad(first.nodes).nodes).toBe(first.nodes) +}) diff --git a/packages/core/src/utils/reconcile-structure-on-load.ts b/packages/core/src/utils/reconcile-structure-on-load.ts new file mode 100644 index 0000000000..a4268450d7 --- /dev/null +++ b/packages/core/src/utils/reconcile-structure-on-load.ts @@ -0,0 +1,331 @@ +import { automaticFloorHeight, floorPlateHoldsUnderside } from '../lib/floor-foundation-datum' +import { upperStoreyFootprints } from '../lib/floor-foundation-stack' +import { area, intersection } from '../lib/polygon-boolean' +import type { SceneNodes } from '../lib/structure-kernel' +import type { AnyNode, CeilingNode, SlabNode } from '../schema' +import { DEFAULT_SLAB_ELEVATION } from '../schema/nodes/slab' +import { getCeilingClampBound } from '../services/storey' +import { planOwnedFloorOpenings } from '../systems/owned-floor-openings' +import { ensureSceneOpenings } from './ensure-scene-openings' +import { migrateExteriorThresholds } from './exterior-threshold-migration' +import { migrateFootprintFollowing } from './floor-follow-migration' +import { migrateFloorOpeningNodes } from './floor-opening-migration' +import { preserveLegacyWallDatums } from './legacy-wall-datums' +import { + materializeLegacyAutoOpenings, + migrateOwnedFloorOpenings, +} from './owned-floor-opening-migration' +import { reconcileStructureWithStableIds } from './structure-id' + +function roomHoles(slab: SlabNode | CeilingNode) { + return (slab.holes ?? []).filter((_, i) => slab.holeMetadata?.[i]?.source === 'room') +} + +function discardOrphanLegacySlabCuts(source: Record) { + let nodes = source + for (const value of Object.values(source)) { + const slab = value as SlabNode | CeilingNode + if ((slab.type !== 'slab' && slab.type !== 'ceiling') || !slab.holes?.length) continue + const kept = slab.holes.flatMap((hole, index) => { + const metadata = slab.holeMetadata?.[index] + const ownerId = metadata?.source === 'stair' ? metadata.stairId : metadata?.elevatorId + const orphan = + (metadata?.source === 'stair' || metadata?.source === 'elevator') && + (!ownerId || (source[ownerId] as AnyNode | undefined)?.type !== metadata.source) + if (orphan) return [] + return [{ hole, metadata: metadata ?? { source: 'manual' as const } }] + }) + if (kept.length === slab.holes.length) continue + if (nodes === source) nodes = { ...source } + nodes[slab.id] = { + ...slab, + holes: kept.map((entry) => entry.hole), + holeMetadata: kept.map((entry) => entry.metadata), + } + } + return nodes +} + +function rehomeRetiredPlateCuts(source: Record, legacy: Record) { + let nodes = source + const plates = Object.values(source).filter( + (node): node is SlabNode => node.type === 'slab' && node.plateRole !== undefined, + ) + for (const opening of Object.values(source)) { + if (opening.type !== 'floor-opening' || !opening.legacyPlateCuts) continue + let cuts: typeof opening.legacyPlateCuts | undefined + for (const [sourceId, rings] of Object.entries(opening.legacyPlateCuts)) { + if (source[sourceId]?.type === 'slab') continue + const former = legacy[sourceId] + if (former?.type !== 'slab') continue + const target = plates + .filter( + (plate) => + plate.parentId === former.parentId && + Math.abs(plate.elevation - former.elevation) < 0.005 && + rings.some((ring) => area(intersection(ring, plate.polygon)) > 1e-4), + ) + .map((plate) => ({ + plate, + overlap: area(intersection(former.polygon, plate.polygon)), + })) + .sort((a, b) => b.overlap - a.overlap || a.plate.id.localeCompare(b.plate.id))[0]?.plate + if (!target) continue + cuts ??= { ...opening.legacyPlateCuts } + delete cuts[sourceId] + cuts[target.id] = [...(cuts[target.id] ?? []), ...rings] + } + if (!cuts) continue + if (nodes === source) nodes = { ...source } + nodes[opening.id] = { ...opening, legacyPlateCuts: cuts } + } + return nodes +} + +export function alignLegacyStairCuts(source: Record) { + let nodes = source + const openings = Object.values(source).filter((node) => node.type === 'floor-opening') + for (const opening of openings) { + if (opening.source !== 'stair' || !opening.legacyPlateCuts) continue + const stair = opening.ownerId ? source[opening.ownerId] : undefined + if (stair?.type !== 'stair') continue + const ceilings = openings.filter((other) => { + if ( + other === opening || + other.source !== 'stair' || + other.parentId !== opening.parentId || + !other.ownerId || + other.ownerId.localeCompare(opening.ownerId ?? '') >= 0 + ) + return false + const owner = other.ownerId ? source[other.ownerId] : undefined + return ( + owner?.type === 'stair' && + owner.fromLevelId === stair.fromLevelId && + owner.toLevelId === stair.toLevelId && + other.legacyCeilingCuts !== undefined + ) + }) + if (!ceilings.length) continue + let cuts: typeof opening.legacyPlateCuts | undefined + for (const [plateId, rings] of Object.entries(opening.legacyPlateCuts)) { + const matched = rings.map((ring) => { + const size = area([{ outer: ring, holes: [] }]) + const candidate = ceilings + .flatMap((ceiling) => Object.values(ceiling.legacyCeilingCuts ?? {}).flat()) + .map((hole) => ({ hole, shared: area(intersection(ring, hole)) })) + .sort((a, b) => b.shared - a.shared)[0] + return candidate && candidate.shared >= size * 0.6 ? candidate.hole : ring + }) + if (JSON.stringify(matched) === JSON.stringify(rings)) continue + cuts ??= { ...opening.legacyPlateCuts } + cuts[plateId] = matched + } + if (!cuts) continue + if (nodes === source) nodes = { ...source } + nodes[opening.id] = { ...opening, legacyPlateCuts: cuts } + } + return nodes +} + +export function reconcileStructureOnLoad( + sourceNodes: Record, + legacyNodes: Record = sourceNodes, + options: { legacyOpeningsPrepared?: boolean } = {}, +) { + const legacyOpeningsPrepared = + options.legacyOpeningsPrepared || + Object.values(sourceNodes).some( + (node) => + (node as AnyNode).type === 'level' && + (node as AnyNode & { metadata?: { legacyAutoOpeningsMigrated?: boolean } }).metadata + ?.legacyAutoOpeningsMigrated === true, + ) + const materialized = legacyOpeningsPrepared + ? sourceNodes + : materializeLegacyAutoOpenings(sourceNodes) + const legacyRecessed = Object.values(materialized).filter((node): node is SlabNode => { + const slab = node as SlabNode + return ( + slab.type === 'slab' && + slab.recessed === true && + slab.autoFromWalls === true && + !slab.boundary + ) + }) + const openings = migrateFloorOpeningNodes(materialized) + let input = legacyRecessed.length ? { ...openings.nodes } : openings.nodes + input = ensureSceneOpenings(input).nodes + for (const node of Object.values(sourceNodes)) { + const plate = node as SlabNode + if ( + plate.type !== 'slab' || + plate.plateRole !== 'base' || + plate.floorHeight === undefined || + !floorPlateHoldsUnderside(sourceNodes as Record, plate) + ) + continue + const restingUnderside = + automaticFloorHeight(sourceNodes as Record, plate) - DEFAULT_SLAB_ELEVATION + const { floorHeight, ...withoutLift } = plate + if (input === openings.nodes) input = { ...openings.nodes } + input[plate.id] = { + ...withoutLift, + elevation: floorHeight, + thickness: Math.max(plate.thickness, floorHeight - restingUnderside), + ...(plate.foundation?.type === 'solid' + ? { foundation: { ...plate.foundation, type: 'none' } } + : {}), + } + } + // M4 deliberately leaves these authored recesses intact. Let their coverage + // identify the room whose floor they supply without making them candidates for retirement. + for (const slab of legacyRecessed) { + input[slab.id] = { ...slab, autoFromWalls: false } + for (const zone of Object.values(input)) { + if ( + (zone as AnyNode).type !== 'zone' || + (zone as import('../schema').ZoneNode).parentId !== slab.parentId + ) + continue + const room = zone as import('../schema').ZoneNode + if (room.floor?.sourceSlabId || room.hasFloor === false) continue + const covered = area(intersection(room.polygon, slab.polygon)) + if (covered < area([{ outer: room.polygon, holes: room.holes }]) * 0.95) continue + input[room.id] = { ...room, floor: { ...room.floor, sourceSlabId: slab.id } } + } + } + input = migrateOwnedFloorOpenings(input).nodes + input = rehomeRetiredPlateCuts( + input as Record, + legacyNodes as Record, + ) + let result = reconcileStructureWithStableIds({ nodes: input as SceneNodes }) + if ( + result.patches.some( + (patch) => + patch.op === 'update' && + (input[patch.id] as AnyNode | undefined)?.type === 'slab' && + 'zoneIds' in patch.data, + ) + ) { + for (let pass = 0; pass < 2; pass++) { + const settled = reconcileStructureWithStableIds({ nodes: result.nodes }) + if (!settled.patches.length) break + result = settled + } + } + let restoredNodes: Record | undefined + if (legacyRecessed.length) { + restoredNodes = { ...result.nodes } + for (const slab of legacyRecessed) restoredNodes[slab.id] = { ...slab, autoFromWalls: false } + } + for (const [id, node] of Object.entries(result.nodes)) { + const before = input[id] as SlabNode | CeilingNode | undefined + if ( + node === before || + (node.type !== 'slab' && node.type !== 'ceiling') || + before?.type !== node.type || + node.boundary !== 'auto' || + before.boundary !== 'auto' || + node.holeMetadata?.some((entry) => entry.source === 'floor-opening') || + before.holeMetadata?.some((entry) => entry.source === 'floor-opening') || + JSON.stringify([ + node.polygon, + node.type === 'slab' ? node.zoneIds : node.zoneId, + roomHoles(node), + ]) !== + JSON.stringify([ + before.polygon, + before.type === 'slab' ? before.zoneIds : before.zoneId, + roomHoles(before), + ]) + ) + continue + // Loading an unchanged plate must not clip or quantise saved user/stair holes. + const metadataKey = (metadata: unknown) => + JSON.stringify(metadata && Object.entries(metadata).sort(([a], [b]) => a.localeCompare(b))) + const savedHoles = before.holes ?? [] + const savedMetadata = before.holeMetadata ?? [] + const derivedMetadata = node.holeMetadata ?? [] + const oldCuts = new Set(savedMetadata.map(metadataKey)) + const added = (node.holes ?? []).flatMap((hole, index) => + oldCuts.has(metadataKey(derivedMetadata[index])) + ? [] + : [{ hole, metadata: derivedMetadata[index] ?? { source: 'manual' as const } }], + ) + const restored = { + ...node, + holes: [...savedHoles, ...added.map((entry) => entry.hole)], + holeMetadata: [...savedMetadata, ...added.map((entry) => entry.metadata)], + } + restoredNodes ??= { ...result.nodes } + restoredNodes[id] = JSON.stringify(restored) === JSON.stringify(before) ? before : restored + } + const cleaned = discardOrphanLegacySlabCuts(restoredNodes ?? result.nodes) + const materializedOwned = legacyOpeningsPrepared + ? cleaned + : materializeLegacyAutoOpenings(cleaned) + const owned = migrateOwnedFloorOpenings(materializedOwned) + let nodes = owned.nodes as Record + const rehomed = rehomeRetiredPlateCuts(nodes, legacyNodes as Record) + nodes = alignLegacyStairCuts(rehomed) + const intentChanges = planOwnedFloorOpenings(nodes, { + skipExistingSurfaces: true, + enforceReach: false, + materializedNodes: materializedOwned as Record, + }) + if (intentChanges.length) { + nodes = { ...nodes } + for (const change of intentChanges) { + if (change.op === 'create') nodes[change.node.id] = change.node + else if (change.op === 'delete') delete nodes[change.id] + else nodes[change.id] = { ...nodes[change.id], ...change.data } as AnyNode + } + } + if (owned.changed || nodes !== owned.nodes || intentChanges.length) + nodes = reconcileStructureWithStableIds({ nodes }).nodes as Record + nodes = ensureSceneOpenings(nodes).nodes + nodes = preserveLegacyWallDatums(legacyNodes as Record, nodes) + for (const level of Object.values(nodes)) { + if (level.type !== 'level' || !level.metadata?.legacyRoomMigrationPending) continue + const { legacyRoomMigrationPending: _pending, ...metadata } = level.metadata + nodes = { ...nodes, [level.id]: { ...level, metadata } } + } + const followed = migrateFootprintFollowing(nodes) + // Walls that now follow the storey plane reach the ceilings, which stop at their faces. + if (followed !== nodes) + nodes = reconcileStructureWithStableIds({ nodes: followed }).nodes as Record + for (const ceiling of Object.values(nodes)) { + if (ceiling.type !== 'ceiling' || ceiling.height === undefined || !ceiling.parentId) continue + const saved = legacyNodes[ceiling.id] as CeilingNode | undefined + // Loading never moves a saved height: the kernel's write clamp would drop a + // legacy ceiling stored above its storey, which the scene has always shown there. + if (saved?.type === 'ceiling' && saved.height !== undefined) { + if (ceiling.height === saved.height) continue + const restored = { ...ceiling, height: saved.height } + const loaded = sourceNodes[ceiling.id] + nodes = { + ...nodes, + [ceiling.id]: + JSON.stringify(restored) === JSON.stringify(loaded) ? (loaded as AnyNode) : restored, + } + continue + } + const bound = getCeilingClampBound(ceiling.parentId, nodes, ceiling.polygon) + if (ceiling.height > bound + 1e-6) + nodes = { ...nodes, [ceiling.id]: { ...ceiling, height: bound } } + } + + nodes = migrateExteriorThresholds(nodes, legacyNodes) + + if ( + Object.keys(nodes).length === Object.keys(sourceNodes).length && + Object.entries(nodes).every(([id, node]) => node === sourceNodes[id]) + ) { + nodes = sourceNodes as SceneNodes + } + // Build the support map during load so the first height gesture stays responsive. + upperStoreyFootprints(nodes) + return { nodes, changed: nodes !== sourceNodes } +} diff --git a/packages/core/src/utils/room-zone-migration.test.ts b/packages/core/src/utils/room-zone-migration.test.ts new file mode 100644 index 0000000000..4666a66904 --- /dev/null +++ b/packages/core/src/utils/room-zone-migration.test.ts @@ -0,0 +1,710 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { area, containsPoint, distanceToBoundary, type Ring } from '../lib/polygon-boolean' +import { detectRoomFaces } from '../lib/room-graph' +import { createRoomTopologyIndex } from '../lib/space-detection' +import { reconcileLevelStructure } from '../lib/structure-kernel' +import { + type AnyNode, + CeilingNode, + LevelNode, + SeparatorNode, + SlabNode, + WallNode, + ZoneNode, +} from '../schema' +import { + ensureSceneOpenings, + healSceneNodes, + migrateCeilingRoomLinks, + migrateFloorPlates, + migrateRoomZones, + migrateSlabSlots, + migrateVerticalSceneNodes, + migrateWallFaceBands, + migrateWallFaceKeys, + normalizeLegacyStructure, + reconcileStructureOnLoad, +} from './scene-migrations' + +type Nodes = Record +const rectangle = (x = 0, y = 0, width = 10, height = 10): Ring => [ + [x, y], + [x + width, y], + [x + width, y + height], + [x, y + height], +] +function walls(polygon: Ring, prefix = 'outer', levelId = 'level_main') { + return polygon.map((start, i) => + WallNode.parse({ + id: `wall_${prefix}_${i}`, + parentId: levelId, + start, + end: polygon[(i + 1) % polygon.length], + }), + ) +} +function scene(polygon = rectangle(), levelId = 'level_main'): Nodes { + const boundary = walls(polygon, 'outer', levelId) + const level = LevelNode.parse({ id: levelId, children: boundary.map((wall) => wall.id) }) + return Object.fromEntries([level, ...boundary].map((node) => [node.id, node])) +} +function add(nodes: Nodes, node: any) { + nodes[node.id] = node + nodes[node.parentId].children.push(node.id) +} +function zones(nodes: Record): ZoneNode[] { + return Object.values(nodes).filter((node: any) => node.type === 'zone') as ZoneNode[] +} +function freeze(value: any) { + if (!value || typeof value !== 'object') return + for (const child of Object.values(value)) freeze(child) + Object.freeze(value) +} + +describe('M3 room zones', () => { + test('creates schema-complete reachable rooms, is pure, deterministic, and byte-idempotent', () => { + const source = scene() + freeze(source) + const first = migrateRoomZones(source) + expect(first.createdZoneIds).toHaveLength(1) + const id = first.createdZoneIds[0]! + expect(id).toMatch(/^zone_[a-z0-9]{16}$/) + expect(first.adoptedZoneIds).toEqual([]) + const room = zones(first.nodes)[0]! + expect(ZoneNode.parse(room)).toEqual(room) + expect(room).toMatchObject({ + name: 'Room 1', + color: '#3b82f6', + parentId: 'level_main', + seed: [5, 5], + holes: [], + boundarySeparatorIds: [], + }) + expect((first.nodes.level_main as any).children).toEqual([...source.level_main.children, id]) + expect(zones(source)).toEqual([]) + expect(migrateRoomZones(source).createdZoneIds).toEqual(first.createdZoneIds) + const second = migrateRoomZones(first.nodes) + expect(JSON.stringify(second.nodes)).toBe(JSON.stringify(first.nodes)) + expect(second.nodes).toBe(first.nodes) + expect(second.createdZoneIds).toEqual([]) + expect(second.adoptedZoneIds).toEqual([]) + expect(migrateRoomZones(scene(rectangle(), 'level_other')).createdZoneIds).not.toEqual( + first.createdZoneIds, + ) + expect( + migrateRoomZones(Object.fromEntries(Object.entries(source).reverse())).createdZoneIds, + ).toEqual(first.createdZoneIds) + }) + + for (const spaceRole of [undefined, 'generic', 'room']) { + test(`adopts a matching ${spaceRole ?? 'role-less'} zone and preserves authored data and seed`, () => { + const source = scene() + const legacy = { + id: 'zone_existing', + type: 'zone', + parentId: 'level_main', + polygon: rectangle(0, 0, 9.5, 10), + name: 'Kitchen', + color: '#abcdef', + seed: [2, 2], + floorFinish: 'Timber', + wallFinish: 'Paint', + ceilingFinish: 'ACT', + ceilingHeight: 3.2, + floor: { finish: 'library:oak' }, + ...(spaceRole ? { spaceRole } : {}), + } + add(source, legacy) + const migrated = migrateRoomZones(source) + expect(migrated.createdZoneIds).toEqual([]) + expect(migrated.adoptedZoneIds).toEqual([legacy.id]) + expect(migrated.nodes[legacy.id]).toMatchObject({ + ...legacy, + polygon: rectangle(), + spaceRole: 'room', + autoFromWalls: true, + boundaryWallIds: Object.values(source) + .filter((n) => n.type === 'wall') + .map((n) => n.id) + .sort(), + boundarySeparatorIds: [], + holes: [], + }) + expect(JSON.stringify(migrateRoomZones(migrated.nodes).nodes)).toBe( + JSON.stringify(migrated.nodes), + ) + }) + } + + for (const [label, polygon, adopted] of [ + ['covers half the face', rectangle(0, 0, 5, 10), true], + ['covers just under half the face', rectangle(0, 0, 4.999, 10), false], + ['has half its area outside the face', rectangle(-5, 0, 10, 10), true], + ['has most of its area outside the face', rectangle(-5.2, 0, 10.2, 10), false], + ] as const) { + test(`adoption threshold: a zone that ${label}`, () => { + const source = scene() + for (const wall of Object.values(source)) if (wall.type === 'wall') wall.thickness = 0 + add(source, { + id: 'zone_threshold', + type: 'zone', + parentId: 'level_main', + name: 'Existing', + polygon, + }) + const result = migrateRoomZones(source) + expect(result.adoptedZoneIds).toEqual(adopted ? ['zone_threshold'] : []) + expect(result.createdZoneIds.length).toBe(adopted ? 0 : 1) + }) + } + + test('leaves unmatched generic zones untouched, including one with the same bounds', () => { + const source = scene() + const generic = ZoneNode.parse({ + id: 'zone_analysis', + parentId: 'level_main', + name: 'Analysis', + polygon: [ + [0, 0], + [10, 0], + [10, 1], + [1, 1], + [1, 10], + [0, 10], + ], + }) + add(source, generic) + const result = migrateRoomZones(source) + expect(result.nodes[generic.id]).toBe(generic) + expect(result.createdZoneIds).toHaveLength(1) + }) + + test('only adopts same-level zones and does not overwrite an occupied deterministic id', () => { + const source = scene() + const id = migrateRoomZones(source).createdZoneIds[0]! + const unrelated = ZoneNode.parse({ + id, + parentId: 'level_other', + name: 'Analysis', + polygon: rectangle(), + }) + source[id] = unrelated + const result = migrateRoomZones(source) + expect(result.nodes[id]).toBe(unrelated) + expect(result.createdZoneIds[0]).not.toBe(id) + expect(migrateRoomZones(source).createdZoneIds).toEqual(result.createdZoneIds) + expect(migrateRoomZones(result.nodes).createdZoneIds).toEqual([]) + }) + + test('nested rooms match topology holes, subtract holes for IoU, and seed inside usable area', () => { + const source = scene() + for (const wall of walls(rectangle(3, 3, 4, 4), 'inner')) add(source, wall) + const oldOuter = ZoneNode.parse({ + id: 'zone_filled_outer', + parentId: 'level_main', + name: 'Analysis', + polygon: rectangle(), + }) + add(source, oldOuter) + const result = migrateRoomZones(source) + // The filled zone holds 84 % of its area in the ring face and covers all of it. + expect(result.createdZoneIds).toHaveLength(1) + expect(result.adoptedZoneIds).toEqual([oldOuter.id]) + expect((result.nodes[oldOuter.id] as ZoneNode).holes).toHaveLength(1) + expect((result.nodes[oldOuter.id] as ZoneNode).name).toBe('Analysis') + const rooms = zones(result.nodes).filter((zone) => zone.autoFromWalls) + const outer = rooms.find((zone) => zone.holes.length === 1)! + const inner = rooms.find((zone) => zone.holes.length === 0)! + expect(outer.boundaryWallIds).toHaveLength(8) + expect(inner.boundaryWallIds).toHaveLength(4) + expect(area([{ outer: outer.polygon, holes: outer.holes }])).toBe(84) + for (const room of rooms) { + const polygon = [{ outer: room.polygon, holes: room.holes }] + expect(containsPoint(polygon, room.seed!)).toBe(true) + expect(distanceToBoundary(polygon, room.seed!)).toBeGreaterThan(0) + } + const index = createRoomTopologyIndex() + index.rebuild(source) + const topology = index.getLevelTopology('level_main')! + expect(rooms.map((room) => ({ polygon: room.polygon, holes: room.holes }))).toEqual( + topology.rooms.map((room) => ({ polygon: room.polygon, holes: room.holes })), + ) + expect(JSON.stringify(migrateRoomZones(result.nodes).nodes)).toBe(JSON.stringify(result.nodes)) + }) + + test('adopts a holed zone regardless of ring winding', () => { + const source = scene() + for (const wall of walls(rectangle(3, 3, 4, 4), 'inner')) add(source, wall) + add( + source, + ZoneNode.parse({ + id: 'zone_ring', + parentId: 'level_main', + name: 'Hall', + polygon: rectangle().reverse(), + holes: [rectangle(3, 3, 4, 4)], + }), + ) + expect(migrateRoomZones(source).adoptedZoneIds).toEqual(['zone_ring']) + }) + + test('concave faces use an interior pole when the area centroid lies outside', () => { + const polygon: Ring = [ + [0, 0], + [10, 0], + [10, 2], + [2, 2], + [2, 10], + [0, 10], + ] + const room = zones(migrateRoomZones(scene(polygon)).nodes)[0]! + expect(containsPoint([{ outer: polygon, holes: [] }], room.seed!)).toBe(true) + expect(distanceToBoundary([{ outer: polygon, holes: [] }], room.seed!)).toBeGreaterThan(1) + }) + + test('separators split faces and contribute to deterministic identity', () => { + const source = scene() + const separator = SeparatorNode.parse({ + id: 'separator_middle', + parentId: 'level_main', + start: [5, 0], + end: [5, 10], + }) + add(source, separator) + const result = migrateRoomZones(source) + expect(result.createdZoneIds).toHaveLength(2) + for (const room of zones(result.nodes)) + expect(room.boundarySeparatorIds).toEqual([separator.id]) + const renamed = { ...source, separator_other: { ...separator, id: 'separator_other' } } + delete renamed[separator.id] + expect(migrateRoomZones(renamed).createdZoneIds).not.toEqual(result.createdZoneIds) + expect(JSON.stringify(migrateRoomZones(result.nodes).nodes)).toBe(JSON.stringify(result.nodes)) + }) + + test('open loops and the exterior never generate rooms', () => { + const source = scene() + delete source.wall_outer_0 + expect(migrateRoomZones(source).createdZoneIds).toEqual([]) + expect(detectRoomFaces([])).toEqual([]) + }) +}) + +describe('M6 ceiling room links', () => { + test('links auto and matching height-less ceilings, preserves legacy flags and children, and is idempotent', () => { + const source = scene() + for (const [id, fields] of [ + ['ceiling_auto', { autoFromWalls: true, height: 8, children: ['item_light'] }], + ['ceiling_absent', {}], + ['ceiling_false', { autoFromWalls: false }], + ['ceiling_explicit', { autoFromWalls: false, height: 2 }], + ['ceiling_unmatched', { autoFromWalls: true, polygon: rectangle(30, 30) }], + ] as const) + add(source, { type: 'ceiling', id, parentId: 'level_main', polygon: rectangle(), ...fields }) + const rooms = migrateRoomZones(source) + freeze(rooms.nodes) + const result = migrateCeilingRoomLinks(rooms.nodes) + expect(result.linkedCeilingIds).toEqual(['ceiling_auto', 'ceiling_absent', 'ceiling_false']) + for (const id of result.linkedCeilingIds) { + expect(result.nodes[id]).toEqual({ + ...(rooms.nodes[id] as object), + zoneId: rooms.createdZoneIds[0], + boundary: 'auto', + }) + } + expect(result.nodes.ceiling_explicit).toBe(rooms.nodes.ceiling_explicit) + expect(result.nodes.ceiling_unmatched).toBe(rooms.nodes.ceiling_unmatched) + const again = migrateCeilingRoomLinks(result.nodes) + expect(again.nodes).toBe(result.nodes) + expect(JSON.stringify(again.nodes)).toBe(JSON.stringify(result.nodes)) + }) + + test('height-less ceilings need an actual face; matching a stale room zone is insufficient', () => { + const source = scene() + delete source.wall_outer_0 + add( + source, + ZoneNode.parse({ + id: 'zone_stale', + name: 'Room', + parentId: 'level_main', + polygon: rectangle(), + spaceRole: 'room', + autoFromWalls: true, + }), + ) + add( + source, + CeilingNode.parse({ id: 'ceiling_stale', parentId: 'level_main', polygon: rectangle() }), + ) + expect(migrateCeilingRoomLinks(source).nodes).toBe(source) + }) + + test('matches holes and same-level rooms with the same inclusive IoU threshold', () => { + const source = scene() + for (const wall of walls(rectangle(3, 3, 4, 4), 'inner')) add(source, wall) + add( + source, + CeilingNode.parse({ + id: 'ceiling_ring', + parentId: 'level_main', + polygon: rectangle(), + holes: [rectangle(3, 3, 4, 4)], + autoFromWalls: true, + }), + ) + add( + source, + CeilingNode.parse({ + id: 'ceiling_filled', + parentId: 'level_main', + polygon: rectangle(), + autoFromWalls: true, + }), + ) + add( + source, + CeilingNode.parse({ + id: 'ceiling_foreign', + parentId: 'level_main', + polygon: rectangle(30, 30), + autoFromWalls: true, + }), + ) + source.zone_foreign = ZoneNode.parse({ + id: 'zone_foreign', + name: 'Foreign', + spaceRole: 'room', + polygon: rectangle(30, 30), + parentId: 'level_other', + }) + const rooms = migrateRoomZones(source) + const result = migrateCeilingRoomLinks(rooms.nodes) + expect(result.linkedCeilingIds).toEqual(['ceiling_ring']) + expect((result.nodes.ceiling_ring as any).zoneId).toBe( + zones(rooms.nodes).find((zone) => zone.holes.length === 1)!.id, + ) + for (const width of [9, 8.999]) { + const plain = scene() + // 2 m walls hide the missing strip, so only the IoU threshold decides the link. + for (const node of Object.values(plain)) if (node.type === 'wall') node.thickness = 2 + add( + plain, + CeilingNode.parse({ + id: 'ceiling_threshold', + parentId: 'level_main', + polygon: rectangle(0, 0, width, 10), + autoFromWalls: true, + }), + ) + expect(migrateCeilingRoomLinks(migrateRoomZones(plain).nodes).linkedCeilingIds.length).toBe( + width === 9 ? 1 : 0, + ) + } + }) + + test('rooms M3 migrates keep exactly the legacy ceilings: none where none was drawn', () => { + const source = scene(rectangle(0, 0, 8, 4)) + add( + source, + WallNode.parse({ id: 'wall_divider', parentId: 'level_main', start: [4, 0], end: [4, 4] }), + ) + add( + source, + CeilingNode.parse({ + id: 'ceiling_left', + parentId: 'level_main', + polygon: rectangle(0, 0, 4, 4), + autoFromWalls: true, + }), + ) + const rooms = migrateRoomZones(source) + freeze(rooms.nodes) + const result = migrateCeilingRoomLinks(rooms.nodes) + expect(result.linkedCeilingIds).toEqual(['ceiling_left']) + const linked = (result.nodes.ceiling_left as CeilingNode).zoneId + expect(result.ceilinglessZoneIds).toEqual(rooms.createdZoneIds.filter((id) => id !== linked)) + expect(result.nodes[linked!]).not.toHaveProperty('hasCeiling') + for (const id of result.ceilinglessZoneIds) + expect(result.nodes[id]).toMatchObject({ hasCeiling: false }) + const again = migrateCeilingRoomLinks(migrateRoomZones(result.nodes).nodes) + expect(again.nodes).toBe(result.nodes) + }) + + test('a level of knee-high walls without legacy ceilings gets none', () => { + const source = scene() + for (const node of Object.values(source)) if (node.type === 'wall') node.height = 0.5 + const result = migrateCeilingRoomLinks(migrateRoomZones(source).nodes) + expect(zones(result.nodes).map((zone) => zone.hasCeiling)).toEqual([false]) + }) + + test('levels the kernel already reconciled and reloads keep their rooms ceiling intent', () => { + const migrated = migrateRoomZones(scene()) + const zone = zones(migrated.nodes)[0]! + const reconciled: Nodes = { ...migrated.nodes } + add( + reconciled, + SlabNode.parse({ + id: 'slab_plate', + parentId: 'level_main', + polygon: rectangle(), + boundary: 'auto', + plateRole: 'base', + }), + ) + expect(migrateCeilingRoomLinks(reconciled).nodes).toBe(reconciled) + // A reload: the level no longer carries M3's migration mark. + const { legacyRoomMigrationPending: _pending, ...metadata } = (migrated.nodes.level_main as any) + .metadata + const reloaded = { + ...migrated.nodes, + level_main: { ...(migrated.nodes.level_main as any), metadata }, + } + expect(migrateCeilingRoomLinks(reloaded).nodes).toBe(reloaded) + expect(zone.hasCeiling).toBeUndefined() + }) + + test('a legacy ceiling drawn off its room face stays manual rather than visibly moving', () => { + const source = scene() + add( + source, + CeilingNode.parse({ + id: 'ceiling_overhang', + parentId: 'level_main', + polygon: rectangle(0, -0.5, 10, 10.5), + autoFromWalls: true, + }), + ) + const rooms = migrateRoomZones(source) + const result = migrateCeilingRoomLinks(rooms.nodes) + expect(result.linkedCeilingIds).toEqual([]) + expect(result.nodes.ceiling_overhang).toBe(rooms.nodes.ceiling_overhang) + expect(result.ceilinglessZoneIds).toEqual(rooms.createdZoneIds) + }) +}) + +test('adopts the clear inner faces of a 4×3 room with centred 0.2 m walls', () => { + const source = scene(rectangle(0, 0, 4, 3)) + for (const wall of Object.values(source)) if (wall.type === 'wall') wall.thickness = 0.2 + add( + source, + ZoneNode.parse({ + id: 'zone_clear', + parentId: 'level_main', + name: 'Office', + polygon: rectangle(0.1, 0.1, 3.8, 2.8), + }), + ) + const migrated = migrateRoomZones(source) + expect(migrated.createdZoneIds).toEqual([]) + expect(migrated.adoptedZoneIds).toEqual(['zone_clear']) + expect(zones(migrated.nodes)[0]!.polygon).toEqual(rectangle(0, 0, 4, 3)) + expect(JSON.stringify(migrateRoomZones(migrated.nodes).nodes)).toBe( + JSON.stringify(migrated.nodes), + ) +}) + +describe('M3 adoption of hand-drawn zones', () => { + test('a zone drawn to the outer wall faces is adopted', () => { + const source = scene(rectangle(0, 0, 4, 3)) + for (const wall of Object.values(source)) if (wall.type === 'wall') wall.thickness = 0.2 + add(source, { + id: 'zone_outer', + type: 'zone', + parentId: 'level_main', + name: 'Study', + polygon: rectangle(-0.3, -0.3, 4.6, 3.6), + }) + const migrated = migrateRoomZones(source) + expect(migrated.adoptedZoneIds).toEqual(['zone_outer']) + expect(migrated.createdZoneIds).toEqual([]) + }) + + test('a zone spanning a closet is the room it mostly covers; the closet gets the next room number', () => { + const source = scene(rectangle(0, 0, 6, 4)) + for (const [id, start, end] of [ + ['wall_closet_side', [4, 0], [4, 2]], + ['wall_closet_top', [4, 2], [6, 2]], + ] as const) + add(source, WallNode.parse({ id, parentId: 'level_main', start, end })) + add(source, { + id: 'zone_bedroom', + type: 'zone', + parentId: 'level_main', + name: 'Bedroom', + polygon: rectangle(0, 0, 6, 4), + }) + const migrated = migrateRoomZones(source) + expect(migrated.adoptedZoneIds).toEqual(['zone_bedroom']) + expect(migrated.createdZoneIds).toHaveLength(1) + const bedroom = migrated.nodes.zone_bedroom as ZoneNode + expect(bedroom.name).toBe('Bedroom') + expect(area([{ outer: bedroom.polygon, holes: bedroom.holes }])).toBeCloseTo(20) + expect((migrated.nodes[migrated.createdZoneIds[0]!] as ZoneNode).name).toBe('Room 1') + }) + + test('an aggregate zone over several rooms stays a zone; its rooms are numbered past existing ones', () => { + const source = scene(rectangle(0, 0, 9, 3)) + for (const x of [3, 6]) + add( + source, + WallNode.parse({ + id: `wall_split_${x}`, + parentId: 'level_main', + start: [x, 0], + end: [x, 3], + }), + ) + const flat = ZoneNode.parse({ + id: 'zone_flat', + parentId: 'level_main', + name: 'Apartment', + polygon: rectangle(0, 0, 9, 3), + }) + add(source, flat) + for (const [id, name] of [ + ['zone_legacy_label', 'Room 2'], + ['zone_slab_like', 'Room 3 Slab'], + ['zone_cleared', ''], + ] as const) + add( + source, + ZoneNode.parse({ id, parentId: 'level_main', name, polygon: rectangle(20, 20, 1, 1) }), + ) + const migrated = migrateRoomZones(source) + expect(migrated.nodes.zone_flat).toBe(flat) + expect(migrated.createdZoneIds).toHaveLength(3) + expect( + migrated.createdZoneIds.map((id) => (migrated.nodes[id] as ZoneNode).name).sort(), + ).toEqual(['Room 1', 'Room 3', 'Room 4']) + expect((migrated.nodes.zone_cleared as ZoneNode).name).toBe('') + }) + + test('of two zones in one room the one covering more is adopted; the other stays untouched', () => { + const source = scene() + const dining = ZoneNode.parse({ + id: 'zone_a_dining', + parentId: 'level_main', + name: 'Dining', + polygon: rectangle(0, 0, 6, 10), + }) + add(source, dining) + add( + source, + ZoneNode.parse({ + id: 'zone_b_kitchen', + parentId: 'level_main', + name: 'Kitchen', + polygon: rectangle(0, 0, 8, 10), + }), + ) + const migrated = migrateRoomZones(source) + expect(migrated.adoptedZoneIds).toEqual(['zone_b_kitchen']) + expect(migrated.nodes[dining.id]).toBe(dining) + expect(migrated.createdZoneIds).toEqual([]) + }) +}) + +describe('existing rooms and ties across load paths', () => { + test('a reload keeps an existing room whose face grew, never a replacement', () => { + // Kitchen was adopted when a wall at x = 4 closed it; that wall is gone now. + const source = scene(rectangle(0, 0, 10, 4)) + const kitchen = ZoneNode.parse({ + id: 'zone_kitchen', + parentId: 'level_main', + name: 'Kitchen', + polygon: rectangle(0, 0, 4, 4), + seed: [2, 2], + spaceRole: 'room', + autoFromWalls: true, + boundaryWallIds: ['wall_outer_0', 'wall_outer_2', 'wall_outer_3', 'wall_gone'], + }) + add(source, kitchen) + const migrated = migrateRoomZones(source) + expect(migrated.createdZoneIds).toEqual([]) + expect(migrated.nodes.zone_kitchen).toMatchObject({ + name: 'Kitchen', + polygon: rectangle(0, 0, 10, 4), + }) + const level = reconcileLevelStructure({ + levelId: 'level_main', + nodes: migrated.nodes as Record, + mintId: (kind) => `${kind}_minted`, + }) + expect(level.patches.filter((patch) => patch.op === 'delete')).toEqual([]) + expect(level.events.filter((event) => event.type === 'retired')).toEqual([]) + }) + + test('a zone split evenly between two rooms adopts the same one on load and live', () => { + const source = scene(rectangle(0, 0, 8, 4)) + add( + source, + WallNode.parse({ id: 'wall_middle', parentId: 'level_main', start: [4, 0], end: [4, 4] }), + ) + add( + source, + ZoneNode.parse({ + id: 'zone_even', + parentId: 'level_main', + name: 'Even', + polygon: rectangle(2, 0, 4, 4), + }), + ) + const loaded = migrateRoomZones(source).nodes.zone_even as ZoneNode + const live = reconcileLevelStructure({ + levelId: 'level_main', + nodes: source as Record, + mintId: (kind) => `${kind}_minted`, + }).patches.find((patch) => patch.op === 'update' && patch.id === 'zone_even') + expect(loaded.autoFromWalls).toBe(true) + expect(live?.op === 'update' && live.data.polygon).toEqual(loaded.polygon) + }) +}) + +// Prod "Wawa House" (level 0): walls drawn a few centimetres short of their corners and +// twelve hand-drawn zones. Before this rule Living Room and Master Bedroom had no room, +// and Entrance and Bathroom got a duplicate "Room" beside them. +describe('hand-drawn zones in a production house', () => { + const source = JSON.parse( + readFileSync(new URL('./__fixtures__/project_hrY3qVVq16yo5Out.json', import.meta.url), 'utf8'), + ) as Record + const load = (nodes: Record) => { + const vertical = migrateVerticalSceneNodes( + healSceneNodes(normalizeLegacyStructure(nodes)).nodes, + ).nodes + const rooms = migrateRoomZones(vertical).nodes + const plates = migrateFloorPlates(migrateCeilingRoomLinks(rooms).nodes).nodes + const openings = ensureSceneOpenings(migrateSlabSlots(plates).nodes).nodes + const walls = migrateWallFaceBands(migrateWallFaceKeys(openings).nodes).nodes + return reconcileStructureOnLoad(walls, vertical).nodes as Record + } + const first = load(source) + const named = Object.values(source).filter((node: any) => node.type === 'zone') as ZoneNode[] + + test('every enclosed named zone becomes its room, keeping id and name', () => { + for (const zone of named) { + const after = first[zone.id] as ZoneNode + expect(after?.name).toBe(zone.name) + expect(after.spaceRole === 'room' && after.autoFromWalls).toBe(zone.name !== 'Swimming Pool') + } + }) + + test('unnamed rooms are numbered, never "Room", and no face holds two rooms', () => { + const rooms = zones(first).filter((zone) => zone.spaceRole === 'room' && zone.autoFromWalls) + expect(rooms).toHaveLength(17) + expect(rooms.filter((zone) => zone.name === 'Room')).toEqual([]) + expect( + rooms + .filter((zone) => !source[zone.id]) + .map((zone) => zone.name) + .sort(), + ).toEqual(['Room 1', 'Room 2', 'Room 3', 'Room 4', 'Room 5', 'Room 6']) + const keys = rooms.map((zone) => [...zone.boundaryWallIds].sort().join('|')) + expect(new Set(keys).size).toBe(keys.length) + }) + + test('the load is deterministic and a second load is a no-op', () => { + expect(JSON.stringify(load(source))).toBe(JSON.stringify(first)) + expect(JSON.stringify(load(first))).toBe(JSON.stringify(first)) + }) +}) diff --git a/packages/core/src/utils/room-zone-migration.ts b/packages/core/src/utils/room-zone-migration.ts new file mode 100644 index 0000000000..9f884080e0 --- /dev/null +++ b/packages/core/src/utils/room-zone-migration.ts @@ -0,0 +1,327 @@ +import { floorRoomFaces } from '../lib/floor-room-faces' +import { + area, + difference, + intersection, + type Polygon, + type Ring, + union, +} from '../lib/polygon-boolean' +import { polygonInteriorPoint } from '../lib/polygon-label' +import type { RoomFace } from '../lib/room-graph' +import { roomNameAllocator } from '../lib/room-name' +import { + adoptableFace, + compareAdoptionFits, + compareExistingRooms, + existingRoomFace, + type IdentityFace, + ROOM_MATCH_IOU, + type ZoneFaceFit, + zoneFaceFits, +} from '../lib/room-zone-adoption' +import type { SeparatorNode } from '../schema/nodes/separator' +import type { WallNode } from '../schema/nodes/wall' +import { ZoneNode } from '../schema/nodes/zone' +import { calculateLevelMiters, getWallPlanFootprint } from '../systems/wall/wall-footprint' +import { omitUndefined } from './omit-undefined' + +type SceneNodes = Record +type Footprint = { polygon: Ring; holes?: Ring[] } + +/** Visible outline change (m²) above which a legacy ceiling is not handed to its room. */ +const LEGACY_CEILING_REDRAW_AREA = 0.01 + +export type RoomZoneMigration = { + nodes: Record + createdZoneIds: string[] + adoptedZoneIds: string[] +} + +export type CeilingRoomLinkMigration = { + nodes: Record + linkedCeilingIds: string[] + /** Rooms M3 just migrated on a never-reconciled level that no legacy ceiling served: `hasCeiling: false`. */ + ceilinglessZoneIds: string[] +} + +function facesByLevel(nodes: SceneNodes) { + const boundaries = new Map() + for (const node of Object.values(nodes)) { + if (!node || nodes[node.parentId]?.type !== 'level') continue + if (node.type !== 'wall' && node.type !== 'separator') continue + const level = boundaries.get(node.parentId) ?? { walls: [], separators: [] } + if (node.type === 'wall') level.walls.push(node) + else level.separators.push(node) + boundaries.set(node.parentId, level) + } + return new Map( + [...boundaries] + .sort(([a], [b]) => a.localeCompare(b)) + .map(([levelId, level]) => [ + levelId, + floorRoomFaces([...level.walls, ...level.separators]).map( + (room): RoomFace => ({ + key: room.id, + polygon: room.referencePolygon, + holes: room.holes, + boundaryWallIds: [ + ...new Set( + room.spans + .filter((span) => span.kind === 'wall') + .map((span) => span.boundaryId as WallNode['id']), + ), + ].sort(), + boundarySeparatorIds: [ + ...new Set( + room.spans + .filter((span) => span.kind === 'separator') + .map((span) => span.boundaryId as SeparatorNode['id']), + ), + ].sort(), + }), + ), + ]), + ) +} + +function polygonOf(footprint: Footprint): Polygon { + return { outer: footprint.polygon, holes: footprint.holes ?? [] } +} + +function footprintIoU(a: Footprint, b: Footprint): number { + const left = polygonOf(a) + const right = polygonOf(b) + const combinedArea = area(union([left, right])) + return combinedArea > 0 ? area(intersection(left, right)) / combinedArea : 0 +} + +function roomZoneId(levelId: string, face: RoomFace, attempt = 0): ZoneNode['id'] { + const identity = JSON.stringify([ + levelId, + [...face.boundaryWallIds].sort(), + [...face.boundarySeparatorIds].sort(), + ...(attempt ? [attempt] : []), + ]) + // FNV-1a over UTF-8 is identical on the client and authority, including non-ASCII legacy IDs. + let hash = 0xcbf29ce484222325n + for (const byte of new TextEncoder().encode(identity)) { + hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100000001b3n) + } + return `zone_${hash.toString(36).padStart(16, '0')}` +} + +export function migrateRoomZones(sourceNodes: Record): RoomZoneMigration { + const nodes: SceneNodes = { ...sourceNodes } + const createdZoneIds: string[] = [] + const adoptedZoneIds: string[] = [] + for (const [levelId, faces] of facesByLevel(nodes)) { + const createdBefore = createdZoneIds.length + const adoptedBefore = adoptedZoneIds.length + const zones = Object.values(nodes) + .filter( + (node) => + node?.type === 'zone' && node.parentId === levelId && node.floor?.support !== 'open', + ) + .sort((a, b) => a.id.localeCompare(b.id)) + const walls = Object.values(nodes).filter( + (node): node is WallNode => node?.type === 'wall' && node.parentId === levelId, + ) + const miters = calculateLevelMiters(walls) + const footprints = new Map( + walls.map((wall) => [ + wall.id, + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ]), + ) + const adoptionFaces: IdentityFace[] = faces.map((face) => ({ + key: face.key, + boundaryWallIds: face.boundaryWallIds, + boundarySeparatorIds: face.boundarySeparatorIds, + polygon: polygonOf(face), + clear: difference( + polygonOf(face), + union( + face.boundaryWallIds.flatMap((id) => (footprints.has(id) ? [footprints.get(id)!] : [])), + ), + ).sort((a, b) => area([b]) - area([a]))[0] ?? { outer: [], holes: [] }, + })) + // Existing rooms keep their faces under the kernel's identity rule first, so a + // reload never replaces one with a new room the kernel would then keep instead. + const zoneByFace = new Map() + const matched = new Set() + const keeping = new Map() + for (const zone of zones) { + if (zone.spaceRole !== 'room' || zone.autoFromWalls !== true) continue + matched.add(zone.id) + const index = existingRoomFace(zone, adoptionFaces) + if (index !== undefined) keeping.set(index, [...(keeping.get(index) ?? []), zone]) + } + for (const [index, rooms] of keeping) + zoneByFace.set(index, rooms.sort(compareExistingRooms(adoptionFaces[index]!))[0]) + const candidates = new Map() + for (const zone of zones) { + if (matched.has(zone.id)) continue + const fit = adoptableFace(zoneFaceFits(zone, adoptionFaces)) + if (!fit || zoneByFace.has(fit.face)) continue + const list = candidates.get(fit.face) ?? [] + list.push({ id: zone.id, fit }) + candidates.set(fit.face, list) + } + for (const [index, list] of candidates) + zoneByFace.set(index, nodes[list.sort(compareAdoptionFits)[0]!.id]) + const nextRoomName = roomNameAllocator( + Object.values(nodes).filter((node) => node?.type === 'zone' && node.parentId === levelId), + ) + faces.forEach((face, index) => { + const zone = zoneByFace.get(index) + if (zone) { + const adopted = { + ...zone, + spaceRole: 'room', + autoFromWalls: true, + boundaryWallIds: face.boundaryWallIds, + boundarySeparatorIds: face.boundarySeparatorIds, + seed: zone.seed ?? polygonInteriorPoint(face, true), + polygon: face.polygon, + holes: face.holes, + } + if (JSON.stringify(zone) !== JSON.stringify(adopted)) { + nodes[zone.id] = omitUndefined(adopted) + adoptedZoneIds.push(zone.id) + } + return + } + let attempt = 0 + let id = roomZoneId(levelId, face) + while (nodes[id]) id = roomZoneId(levelId, face, ++attempt) + nodes[id] = omitUndefined( + ZoneNode.parse({ + id, + parentId: levelId, + name: nextRoomName(), + spaceRole: 'room', + autoFromWalls: true, + polygon: face.polygon, + holes: face.holes, + boundaryWallIds: face.boundaryWallIds, + boundarySeparatorIds: face.boundarySeparatorIds, + seed: polygonInteriorPoint(face, true), + }), + ) + const level = nodes[levelId] + nodes[levelId] = omitUndefined({ ...level, children: [...(level.children ?? []), id] }) + createdZoneIds.push(id) + }) + if (createdZoneIds.length !== createdBefore || adoptedZoneIds.length !== adoptedBefore) { + const level = nodes[levelId] + nodes[levelId] = { + ...level, + metadata: { ...level.metadata, legacyRoomMigrationPending: true }, + } + } + } + return { + nodes: createdZoneIds.length || adoptedZoneIds.length ? nodes : sourceNodes, + createdZoneIds, + adoptedZoneIds, + } +} + +export function migrateCeilingRoomLinks( + sourceNodes: Record, +): CeilingRoomLinkMigration { + const nodes: SceneNodes = { ...sourceNodes } + const linkedCeilingIds: string[] = [] + const ceilinglessZoneIds: string[] = [] + const zones = Object.values(nodes) + .filter((node) => node?.type === 'zone' && node.spaceRole === 'room') + .sort((a, b) => a.id.localeCompare(b.id)) + // Levels the room kernel has already written derived plates or ceilings on. + const reconciledLevels = new Set( + Object.values(nodes).flatMap((node) => + (node?.type === 'ceiling' || node?.type === 'slab') && + (node.boundary === 'auto' || node.plateRole) + ? [node.parentId] + : [], + ), + ) + let faces: ReturnType | undefined + const reachingWalls = new Map() + // What of the ceiling's outline would change if the room redrew it, outside the + // storey-high walls that hide it: the room face differs from the drawn outline there. + const redrawnArea = (ceiling: any, zone: any) => { + let walls = reachingWalls.get(ceiling.parentId) + if (!walls) { + const levelWalls = Object.values(nodes).filter( + (node): node is WallNode => node?.type === 'wall' && node.parentId === ceiling.parentId, + ) + const miters = calculateLevelMiters(levelWalls) + walls = union( + levelWalls + .filter((wall) => wall.height == null) + .map((wall) => + getWallPlanFootprint(wall, miters).map(({ x, y }): [number, number] => [x, y]), + ), + ) + reachingWalls.set(ceiling.parentId, walls) + } + // The room keeps the ceiling's own cutouts (stairs, manual holes) and adds its face's. + const drawn: Polygon = { outer: ceiling.polygon, holes: ceiling.holes ?? [] } + const cuts = union(ceiling.holes ?? []) + const face = cuts.length ? difference(polygonOf(zone), cuts) : [polygonOf(zone)] + const changed = union([...difference(drawn, face), ...difference(face, drawn)]) + return area(walls.length ? difference(changed, walls) : changed) + } + for (const [id, ceiling] of Object.entries(nodes)) { + if (ceiling?.type !== 'ceiling' || nodes[ceiling.parentId]?.type !== 'level') continue + // Overlapping stacked rooms already have authoritative ceiling links. + if (ceiling.boundary === 'auto' && nodes[ceiling.zoneId]?.floor?.support === 'open') continue + if (ceiling.autoFromWalls !== true) { + if (ceiling.height !== undefined) continue + faces ??= facesByLevel(nodes) + if ( + !faces.get(ceiling.parentId)?.some((face) => footprintIoU(ceiling, face) >= ROOM_MATCH_IOU) + ) + continue + } + const zone = zones.find( + (candidate) => + candidate.floor?.support !== 'open' && + candidate.parentId === ceiling.parentId && + footprintIoU(ceiling, candidate) >= ROOM_MATCH_IOU, + ) + if (!zone || (ceiling.zoneId === zone.id && ceiling.boundary === 'auto')) continue + // Linking hands the outline to the room, which redraws it from the walls: a legacy + // ceiling drawn elsewhere than its room face would visibly move, so it stays manual. + if (ceiling.boundary !== 'auto' && redrawnArea(ceiling, zone) > LEGACY_CEILING_REDRAW_AREA) + continue + nodes[id] = omitUndefined({ ...ceiling, zoneId: zone.id, boundary: 'auto' }) + linkedCeilingIds.push(id) + } + // A legacy room keeps exactly the ceiling it had: one linked above, or none. Without + // this the kernel would give every room it never had a ceiling a new one on load. + // Only on the load that migrates the level (M3 marks it), so a reload writes nothing. + const linkedZoneIds = new Set( + Object.values(nodes).flatMap((node) => + node?.type === 'ceiling' && node.boundary === 'auto' && node.zoneId ? [node.zoneId] : [], + ), + ) + for (const zone of zones) { + if ( + nodes[zone.parentId]?.metadata?.legacyRoomMigrationPending !== true || + reconciledLevels.has(zone.parentId) || + zone.hasCeiling === false || + zone.floor?.support === 'open' || + linkedZoneIds.has(zone.id) + ) + continue + nodes[zone.id] = { ...zone, hasCeiling: false } + ceilinglessZoneIds.push(zone.id) + } + return { + nodes: linkedCeilingIds.length || ceilinglessZoneIds.length ? nodes : sourceNodes, + linkedCeilingIds, + ceilinglessZoneIds, + } +} diff --git a/packages/core/src/utils/scene-migrations.ts b/packages/core/src/utils/scene-migrations.ts index a5087855d0..df8ae0a313 100644 --- a/packages/core/src/utils/scene-migrations.ts +++ b/packages/core/src/utils/scene-migrations.ts @@ -2,11 +2,42 @@ // scene authority. Everything exported here must stay pure data logic with no // store, React, or Three.js imports so it can run in Server Components and // API routes. + +export type { NodePatch, SceneNodes, StructureEvent } from '../lib/structure-kernel' +export { + reconcileSceneStructure, + type SceneStructureInput, + type SceneStructureResult, + type StructureIdFactory, +} from '../lib/structure-reconcile' +export { ensureSceneOpenings } from './ensure-scene-openings' +export { migrateFloorOpeningNodes } from './floor-opening-migration' +export { + type FloorPlateMigrationReport, + migrateFloorPlates, + migrateSlabSlots, +} from './floor-plate-migration' +export { healScenePlanCoordinates } from './heal-plan-coordinates' export { type HealSceneResult, healSceneNodes } from './heal-scene-graph' +export { migrateStructuralMaterialSlots } from './legacy-material-slots' +export { materializeNodeDefaults, STRUCTURE_NODE_KINDS } from './node-defaults' +export { normalizeLegacyStructure } from './normalize-legacy-structure' +export { + materializeLegacyAutoOpenings, + migrateOwnedFloorOpenings, +} from './owned-floor-opening-migration' +export { reconcileStructureOnLoad } from './reconcile-structure-on-load' export { type RetiredSceneNodeMigration, removeRetiredDrawingSheetNodes, } from './retired-scene-nodes' +export { + type CeilingRoomLinkMigration, + migrateCeilingRoomLinks, + migrateRoomZones, + type RoomZoneMigration, +} from './room-zone-migration' +export { createStructureIdFactory, reconcileStructureWithStableIds } from './structure-id' export { migrateVerticalSceneNodes, type VerticalSceneMigration, @@ -15,3 +46,4 @@ export { migrateLegacyWallAssemblies, type WallAssemblyMigration, } from './wall-assembly-migration' +export { migrateWallFaceBands, migrateWallFaceKeys } from './wall-face-migration' diff --git a/packages/core/src/utils/structure-id.ts b/packages/core/src/utils/structure-id.ts new file mode 100644 index 0000000000..dd50e8264d --- /dev/null +++ b/packages/core/src/utils/structure-id.ts @@ -0,0 +1,141 @@ +import { comparePlateComponents, floorPlateId } from '../lib/floor-plate-id' +import type { SceneNodes } from '../lib/structure-kernel' +import { + reconcileSceneStructure, + type SceneStructureInput, + type SceneStructureResult, + type StructureIdFactory, +} from '../lib/structure-reconcile' +import type { AnyNode, SlabNode } from '../schema' + +export function createStructureIdFactory(nodes: Record) { + const minted = new Set() + return (kind: Parameters[0], boundaryIds: readonly string[]) => { + const seed = JSON.stringify([...new Set(boundaryIds)].sort()) + for (let attempt = 0; ; attempt++) { + let hash = 0xcbf2_9ce4_8422_2325n + for (const byte of new TextEncoder().encode(`${seed}|${kind}|${attempt}`)) { + hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100_0000_01b3n) + } + const id = `${kind}_${hash.toString(36).padStart(16, '0')}` + if (minted.has(id) || Object.hasOwn(nodes, id)) continue + minted.add(id) + return id + } + } +} + +function boundaries(node: AnyNode, nodes: SceneNodes): string[] { + if (node.type === 'zone') return [...node.boundaryWallIds, ...node.boundarySeparatorIds] + const zoneIds = + node.type === 'slab' + ? (node.zoneIds ?? []) + : node.type === 'ceiling' && node.zoneId + ? [node.zoneId] + : [] + return [ + ...new Set( + zoneIds.flatMap((id) => (nodes[id]?.type === 'zone' ? boundaries(nodes[id]!, nodes) : [])), + ), + ].sort() +} + +function remapReferences(value: T, ids: Map): T { + const fields = value as Record + const changes: Record = {} + for (const key of ['id', 'parentId', 'zoneId', 'supportSlabId', 'deckSlabId', 'survivorId']) { + const id = fields[key] + if (typeof id === 'string' && ids.has(id)) changes[key] = ids.get(id) + } + for (const key of ['children', 'zoneIds', 'members']) { + const references = fields[key] + if (Array.isArray(references) && references.some((id) => ids.has(id))) { + const mapped = references.map((id) => ids.get(id) ?? id) + changes[key] = + key === 'zoneIds' || (key === 'children' && fields.type === 'ceiling') + ? mapped.sort() + : mapped + } + } + return Object.keys(changes).length ? { ...value, ...changes } : value +} + +export function reconcileStructureWithStableIds( + input: Omit, +): SceneStructureResult { + const provisional = createStructureIdFactory(input.nodes) + const result = reconcileSceneStructure({ ...input, mintId: (kind) => provisional(kind, []) }) + const created = result.patches.flatMap((patch) => (patch.op === 'create' ? [patch.node] : [])) + if (!created.length) return result + // The kernel's mint callback receives only a kind. Resolve the owning room + // boundaries from its completed plan, without deriving construction a second time. + const mint = createStructureIdFactory(input.nodes) + const ids = new Map() + for (const node of created.sort((a, b) => { + const key = (n: AnyNode) => + JSON.stringify([n.type, boundaries(n, result.nodes), 'polygon' in n ? n.polygon : []]) + const left = key(a), + right = key(b) + return left < right ? -1 : left > right ? 1 : 0 + })) { + if ( + node.type === 'zone' || + (node.type === 'slab' && !node.plateRole) || + node.type === 'ceiling' + ) + ids.set(node.id, mint(node.type, boundaries(node, result.nodes))) + } + const components = new Map() + const occupied = new Set([...Object.keys(input.nodes), ...ids.values()]) + const plates = created + .filter( + (node): node is SlabNode => + node.type === 'slab' && + !!node.plateRole && + !( + node.plateRole === 'base' && + node.zoneIds?.some((id) => { + const zone = result.nodes[id] + return zone?.type === 'zone' && !!zone.floor?.footprint + }) + ), + ) + .sort((a, b) => + comparePlateComponents( + { outer: a.polygon, holes: a.holes }, + { outer: b.polygon, holes: b.holes }, + ), + ) + for (const plate of plates) { + const zoneIds = (plate.zoneIds ?? []).map((id) => ids.get(id) ?? id).sort() + const key = JSON.stringify([ + plate.parentId, + plate.plateRole === 'base' ? 'base' : 'room', + zoneIds, + ]) + let component = components.get(key) ?? 0 + let id: string + do { + id = floorPlateId(plate.parentId!, plate.plateRole!, zoneIds, component++) + } while (occupied.has(id)) + occupied.add(id) + components.set(key, component) + ids.set(plate.id, id) + } + return { + nodes: Object.fromEntries( + Object.entries(result.nodes).map(([id, node]) => [ + ids.get(id) ?? id, + remapReferences(node, ids), + ]), + ), + patches: result.patches.map((patch) => + patch.op === 'create' + ? { ...patch, node: remapReferences(patch.node, ids) } + : patch.op === 'update' + ? { ...patch, data: remapReferences(patch.data, ids) } + : patch, + ), + events: result.events.map((event) => remapReferences(event, ids)), + } +} diff --git a/packages/core/src/utils/vertical-scene-migration.ts b/packages/core/src/utils/vertical-scene-migration.ts index ad188f057f..d490f8a3a1 100644 --- a/packages/core/src/utils/vertical-scene-migration.ts +++ b/packages/core/src/utils/vertical-scene-migration.ts @@ -112,6 +112,10 @@ export function migrateVerticalSceneNodes( }, slabs, walls, + undefined, + undefined, + 0, + nodes, ).elevation const effectiveHeight = wall.height ?? DEFAULT_WALL_HEIGHT const top = Math.max(0, electedBase) + effectiveHeight @@ -134,15 +138,22 @@ export function migrateVerticalSceneNodes( } } - // Preserve the exact occupied interval of legacy slabs. + // Preserve the exact occupied interval of legacy slabs. The elevation every + // renderer assumes for a slab without one is written too: later migrations do + // arithmetic on it, and the loader's schema defaults would otherwise supply it + // only after them, so a saved and reloaded scene would migrate differently. for (const [id, node] of Object.entries(nodes)) { - if (node?.type !== 'slab' || 'thickness' in node) continue + if (node?.type !== 'slab') continue const elevation = getFiniteNumber(node.elevation, 0.05) + if ('thickness' in node) { + if (node.elevation !== elevation) replaceNode(id, { ...node, elevation }) + continue + } replaceNode( id, elevation < 0 - ? { ...node, thickness: 0.05, recessed: true } - : { ...node, thickness: elevation }, + ? { ...node, elevation, thickness: 0.05, recessed: true } + : { ...node, elevation, thickness: elevation }, ) } @@ -199,9 +210,13 @@ export function migrateVerticalSceneNodes( }, siblings.filter((sibling) => sibling.type === 'slab'), siblings.filter((sibling) => sibling.type === 'wall'), + undefined, + undefined, + 0, + nodes, ) const elected = support.electedSlabId ? nodes[support.electedSlabId] : null - if (!elected) continue + if (!elected || elected.plateRole) continue const pinnedBase = getFiniteNumber(node.supportOffset, 0) const electedTop = getFiniteNumber(elected.elevation, 0.05) const electedBottom = electedTop - getFiniteNumber(elected.thickness, 0.05) diff --git a/packages/core/src/utils/wall-assembly-migration.test.ts b/packages/core/src/utils/wall-assembly-migration.test.ts index 9244d1f934..19cc18a1a9 100644 --- a/packages/core/src/utils/wall-assembly-migration.test.ts +++ b/packages/core/src/utils/wall-assembly-migration.test.ts @@ -64,6 +64,20 @@ const withSides = ( sides: (typeof SIDES)[number], ) => (sides ? { ...wall, ...sides } : wall) +/** + * F2 draws an undetermined outside on side B, where the 3D cladding goes; WS5 + * drew it on the front. The WS5 reference pins only that choice to side B, so + * every other part of the stack and the drawing is compared as WS5 made it. + */ +const outsideOnB = (wall: T): T => + ws5.resolveWallExteriorSide(wall as ws5.WallAssemblySideSource) === null + ? { ...wall, frontSide: 'interior', backSide: 'exterior' } + : wall +const ws5Resolved = (wall: Parameters[0]) => { + const resolved = ws5.resolveWallAssembly(wall) + return { ...resolved, exteriorSideResolved: resolved.exteriorSide ?? -1 } +} + describe('WS5 → F2 wall assembly migration', () => { test('converts every WS5 stack to valid F2 layers and keeps every other field', () => { expect(migrated.changed).toBe(true) @@ -111,7 +125,7 @@ describe('WS5 → F2 wall assembly migration', () => { expect(stack.presetId).toBe(assembly.preset) expect(stack.cavityInsulation).toBe(assembly.cavityInsulation) expect(wallAssemblyToLegacy(stack)).toEqual(assembly) - expect(resolveWallAssembly(wall)).toEqual(ws5.resolveWallAssembly(legacy)) + expect(resolveWallAssembly(wall)).toEqual(ws5Resolved(legacy)) expect(migrateLegacyWallAssemblies(result.nodes)).toEqual({ changed: false, nodes: result.nodes, @@ -124,9 +138,11 @@ describe('WS5 → F2 wall assembly migration', () => { for (const sides of SIDES) { const was = withSides(legacy, sides) const now = withSides(next, sides) - expect(resolveWallAssembly(now)).toEqual(ws5.resolveWallAssembly(was)) - expect(wallLayerBoundaryOffsets(now)).toEqual(ws5.wallLayerBoundaryOffsets(was)) - expect(wallLayerBoundaryOffsets(now, 0.3)).toEqual(ws5.wallLayerBoundaryOffsets(was, 0.3)) + expect(resolveWallAssembly(now)).toEqual(ws5Resolved(was)) + expect(wallLayerBoundaryOffsets(now)).toEqual(ws5.wallLayerBoundaryOffsets(outsideOnB(was))) + expect(wallLayerBoundaryOffsets(now, 0.3)).toEqual( + ws5.wallLayerBoundaryOffsets(outsideOnB(was), 0.3), + ) } expect(wallAssemblyFinishRef(next)).toBe(ws5.wallAssemblyFinishRef(legacy)) expect(wallAssemblyUnverifiedNote(next)).toBe(ws5.wallAssemblyUnverifiedNote(legacy)) @@ -134,15 +150,16 @@ describe('WS5 → F2 wall assembly migration', () => { }) test('the 2D layer lines are identical, corners and junctions included', () => { + const legacyOnB = legacyWalls.map(outsideOnB) const before = ws5.calculateLevelLayerMiters( - legacyWalls, - calculateLevelMiters(legacyWalls as unknown as WallNode[]), + legacyOnB, + calculateLevelMiters(legacyOnB as unknown as WallNode[]), (w) => ws5.wallLayerBoundaryOffsets(w), ) const after = calculateLevelLayerMiters(f2Walls, calculateLevelMiters(f2Walls), (w) => wallLayerBoundaryOffsets(w), ) - for (const [index, legacy] of legacyWalls.entries()) { + for (const [index, legacy] of legacyOnB.entries()) { const next = f2Walls[index]! expect(getWallLayerPolylines(next, after, wallLayerBoundaryOffsets(next))).toEqual( ws5.getWallLayerPolylines(legacy, before, ws5.wallLayerBoundaryOffsets(legacy)), @@ -286,7 +303,14 @@ describe('the scene loader migrates stored WS5 walls', () => { expect(loaded.assembly).toEqual( migrated.nodes[legacy.id] ? (migrated.nodes[legacy.id] as WallNode).assembly : undefined, ) - expect(resolveWallAssembly(loaded)).toEqual(ws5.resolveWallAssembly(legacy)) + // Load re-derives wall sides from the detected rooms; the stack follows them. + expect(resolveWallAssembly(loaded)).toEqual( + ws5Resolved({ + ...legacy, + frontSide: loaded.frontSide, + backSide: loaded.backSide, + }), + ) } }) diff --git a/packages/core/src/utils/wall-face-migration.test.ts b/packages/core/src/utils/wall-face-migration.test.ts new file mode 100644 index 0000000000..64e7853f8b --- /dev/null +++ b/packages/core/src/utils/wall-face-migration.test.ts @@ -0,0 +1,424 @@ +import { describe, expect, test } from 'bun:test' +import { + getEffectiveWallSurfaceMaterial, + getWallTrimFaces, + getWallTrimSlotId, + type WallNode, +} from '../schema/nodes/wall' +import { + buildWallFinishLayout, + resolveWallFaceChain, + resolveWallFinish, +} from '../systems/wall/wall-finish' +import { migrateWallFaceBands, migrateWallFaceKeys } from './wall-face-migration' + +type Raw = Record +type Face = 'a' | 'b' +type Side = 'interior' | 'exterior' + +// ── The renderer before phase 7, restated as a pure oracle ─────────────────── +// Face finish: `viewer/systems/wall/wall-system.tsx` getWallFaceMaterialIndex + +// `wall-materials.ts` resolveWallFaceMaterial / resolveWallSlotMaterial. +// Trims: `nodes/wall/treatments.tsx` resolveTreatmentSideSign + slot lookup. + +const WALL_HEIGHT = 2.5 +const SUFFIX: Record = { interior: 'Interior', exterior: 'Exterior' } +const TRIM_DEFAULTS: Record = { + skirting: 'library:preset-softwhite', + crown: 'library:preset-white', + chairRail: 'library:preset-cream', +} + +function oldSide(node: Raw, face: Face): Side { + const stored = face === 'a' ? node.frontSide : node.backSide + return stored === 'interior' || stored === 'exterior' + ? stored + : face === 'a' + ? 'interior' + : 'exterior' +} + +function oldChain(node: Raw, side: Side): string { + const ref = node.slots?.[side] + if (ref) return `ref:${ref}` + const spec = getEffectiveWallSurfaceMaterial(node, side) + if (spec.materialPreset) return `preset:${spec.materialPreset}` + if (spec.material) return `inline:${JSON.stringify(spec.material)}` + return 'default:library:concrete-drywall' +} + +function oldBands(node: Raw) { + const raw = { + enabled: false, + count: 1, + lowerHeight: 0.84, + middleHeight: 0.61, + upperHeight: 0.61, + ...(node.faceBands ?? {}), + } + const count = raw.enabled ? Math.max(1, Math.min(4, Math.round(raw.count ?? 3))) : 1 + const lower = count >= 2 ? Math.max(0, Math.min(WALL_HEIGHT, raw.lowerHeight)) : 0 + const middle = count >= 3 ? Math.max(0, Math.min(WALL_HEIGHT - lower, raw.middleHeight)) : 0 + const upper = + count >= 4 ? Math.max(0, Math.min(WALL_HEIGHT - lower - middle, raw.upperHeight)) : 0 + return { + enabled: raw.enabled && count > 1, + count, + lowerTop: lower, + middleTop: lower + middle, + upperTop: lower + middle + upper, + } +} + +function oldFaceFinish(node: Raw, face: Face, y: number): string { + const side = oldSide(node, face) + const bands = oldBands(node) + if (!bands.enabled) return oldChain(node, side) + const band = + y < bands.lowerTop + ? 'lower' + : y < bands.middleTop + ? 'middle' + : bands.count >= 4 && y < bands.upperTop + ? 'upper' + : bands.count >= 4 + ? 'top' + : 'upper' + const ref = node.slots?.[`${band}${SUFFIX[side]}`] + return ref ? `ref:${ref}` : oldChain(node, side) +} + +function oldTrimFace(node: Raw, side: Side): Face { + if (node.frontSide === side) return 'a' + if (node.backSide === side) return 'b' + return side === 'interior' ? 'a' : 'b' +} + +function oldTrims(node: Raw, face: Face): string[] { + const out: string[] = [] + for (const kind of ['skirting', 'crown', 'chairRail']) { + const trim = node[kind] + if (!trim?.enabled) continue + const sides: Side[] = + (trim.sides ?? 'both') === 'both' ? ['interior', 'exterior'] : [trim.sides] + for (const side of sides) { + if (oldTrimFace(node, side) !== face) continue + out.push(`${kind}:${node.slots?.[`${kind}${SUFFIX[side]}`] || TRIM_DEFAULTS[kind]}`) + } + } + return out +} + +// ── The phase-7 renderer on a migrated node ────────────────────────────────── + +function newFaceFinish(node: Raw, face: Face, y: number): string { + const hit = resolveWallFinish(buildWallFinishLayout(node as WallNode, []), face, 1, y) + if (hit.source !== 'slot') return `ref:${hit.ref}` + const chain = resolveWallFaceChain(node as WallNode, face) + if (chain.kind === 'ref') return `ref:${chain.ref}` + if (chain.kind === 'default') return `default:${chain.ref}` + return chain.spec.materialPreset + ? `preset:${chain.spec.materialPreset}` + : `inline:${JSON.stringify(chain.spec.material)}` +} + +function newTrims(node: Raw, face: Face): string[] { + const out: string[] = [] + for (const kind of ['skirting', 'crown', 'chairRail'] as const) { + const trim = node[kind] + if (!trim?.enabled || !getWallTrimFaces(trim.sides ?? 'both').includes(face)) continue + out.push(`${kind}:${node.slots?.[getWallTrimSlotId(face, kind)] || TRIM_DEFAULTS[kind]}`) + } + return out +} + +function migrate(node: Raw): Raw { + const nodes = { [node.id]: node } + return migrateWallFaceBands(migrateWallFaceKeys(nodes).nodes).nodes[node.id] as Raw +} + +// ── Fixtures ──────────────────────────────────────────────────────────────── + +const FRONT_SIDES: unknown[] = ['interior', 'exterior', 'unknown', undefined, { color: '#A02424' }] +const BACK_SIDES: unknown[] = ['interior', 'exterior', 'unknown', undefined] +const HEIGHTS = [-0.2, 0.1, 0.5, 0.79, 0.81, 1.2, 1.35, 1.8, 2.4] + +const SCENARIOS: Record = { + 'both side slots': { slots: { interior: 'library:in', exterior: 'library:out' } }, + 'interior slot + legacy exterior preset': { + slots: { interior: 'library:in' }, + exteriorMaterialPreset: 'library:legacy-out', + }, + 'legacy inline + non-ref preset + wall-wide fallback': { + interiorMaterial: { properties: { color: '#111111' } }, + exteriorMaterialPreset: 'white', + material: { properties: { color: '#999999' } }, + }, + 'wall-wide legacy only': { materialPreset: 'library:general' }, + 'legacy side fields with a partial side': { + interiorMaterialPreset: 'library:legacy-in', + materialPreset: 'library:general', + }, + 'empty-string slot falls through to legacy': { + slots: { interior: '' }, + interiorMaterialPreset: 'library:legacy-in', + }, + 'no finish at all': {}, + ...Object.fromEntries( + [2, 3, 4].map((count) => [ + `${count} bands`, + { + faceBands: { enabled: true, count, lowerHeight: 0.8, middleHeight: 0.5, upperHeight: 0.4 }, + slots: { + interior: 'library:in', + lowerInterior: 'library:low-in', + middleExterior: 'library:mid-out', + upperInterior: 'library:up-in', + upperExterior: 'library:up-out', + topExterior: 'library:top-out', + lowerExterior: 'library:low-out', + }, + }, + ]), + ), + 'bands disabled keep their dead slots out of sight': { + faceBands: { enabled: false, count: 3 }, + slots: { lowerInterior: 'library:low-in' }, + }, + 'band slots over legacy inline faces': { + faceBands: { enabled: true, count: 2, lowerHeight: 1 }, + slots: { lowerExterior: 'library:low-out' }, + exteriorMaterial: { properties: { color: '#222222' } }, + }, + trims: { + skirting: { enabled: true, sides: 'interior' }, + crown: { enabled: true, sides: 'exterior' }, + chairRail: { enabled: true, sides: 'both' }, + slots: { + skirtingInterior: 'library:skirt-in', + skirtingExterior: 'library:skirt-out', + crownExterior: 'library:crown-out', + chairRailInterior: 'library:rail-in', + chairRailExterior: 'library:rail-out', + }, + }, +} + +function wall(extra: Raw, frontSide: unknown, backSide: unknown): Raw { + const node: Raw = { + id: 'wall_m1', + type: 'wall', + start: [0, 0], + end: [4, 0], + children: [], + ...extra, + } + if (frontSide !== undefined) node.frontSide = frontSide + if (backSide !== undefined) node.backSide = backSide + return node +} + +function degenerate(node: Raw) { + return oldTrimFace(node, 'interior') === oldTrimFace(node, 'exterior') +} + +describe('M1 + M2 keep every face looking the same', () => { + for (const [name, extra] of Object.entries(SCENARIOS)) { + test(name, () => { + for (const frontSide of FRONT_SIDES) { + for (const backSide of BACK_SIDES) { + const legacy = wall(structuredClone(extra), frontSide, backSide) + const migrated = migrate(legacy) + const label = `${JSON.stringify(frontSide)}/${JSON.stringify(backSide)}` + for (const face of ['a', 'b'] as const) { + for (const y of HEIGHTS) { + expect([label, face, y, newFaceFinish(migrated, face, y)]).toEqual([ + label, + face, + y, + oldFaceFinish(legacy, face, y), + ]) + } + if (degenerate(legacy)) continue + expect([label, face, newTrims(migrated, face)]).toEqual([ + label, + face, + oldTrims(legacy, face), + ]) + } + // Nothing semantic survives: rendering never needs frontSide / backSide again. + const keys = Object.keys(migrated.slots ?? {}) + expect(keys.filter((key) => /interior|exterior|^front$|^back$/i.test(key))).toEqual([]) + for (const key of [ + 'interiorMaterial', + 'interiorMaterialPreset', + 'exteriorMaterial', + 'exteriorMaterialPreset', + 'faceBands', + ]) + expect(key in migrated).toBe(false) + expect(migrated.frontSide).toEqual(legacy.frontSide) + } + } + }) + } + + test('a side pair that drew both trims on one face keeps that face and trims the other', () => { + // exterior/exterior: the old renderer drew the interior and exterior trim on face a. + const legacy = wall(structuredClone(SCENARIOS.trims!), 'exterior', 'exterior') + expect(oldTrims(legacy, 'a')).toEqual([ + 'skirting:library:skirt-in', + 'crown:library:crown-out', + 'chairRail:library:rail-in', + 'chairRail:library:rail-out', + ]) + expect(oldTrims(legacy, 'b')).toEqual([]) + const migrated = migrate(legacy) + expect(newTrims(migrated, 'a')).toEqual([ + 'skirting:library:skirt-in', + 'crown:library:crown-out', + 'chairRail:library:rail-in', + ]) + // `both` now draws the second face instead of doubling the first; it keeps the exterior finish. + expect(newTrims(migrated, 'b')).toEqual(['chairRail:library:rail-out']) + }) + + test('stray front / back keys fill a face M1 left empty and never override a side slot', () => { + expect( + migrate(wall({ slots: { front: 'library:f', back: 'library:b' } }, 'exterior', 'interior')) + .slots, + ).toEqual({ + a: 'library:f', + b: 'library:b', + }) + expect( + migrate( + wall( + { slots: { interior: 'library:in', front: 'library:f', back: 'library:b' } }, + 'exterior', + 'interior', + ), + ).slots, + ).toEqual({ a: 'library:f', b: 'library:in' }) + }) + + test('a corrupt side value falls back like the renderer did (front → interior)', () => { + const migrated = migrate( + wall( + { slots: { interior: 'library:in', exterior: 'library:out' } }, + { color: '#A02424' }, + 'exterior', + ), + ) + expect(migrated.slots).toEqual({ a: 'library:in', b: 'library:out' }) + }) +}) + +describe('M2 face bands → paint regions', () => { + test('band heights become full-width horizontal regions on each face', () => { + const migrated = migrate( + wall( + { + faceBands: { + enabled: true, + count: 4, + lowerHeight: 0.8, + middleHeight: 0.5, + upperHeight: 0.4, + }, + slots: { + lowerInterior: 'library:1', + middleInterior: 'library:2', + upperInterior: 'library:3', + topInterior: 'library:4', + middleExterior: 'library:b2', + }, + }, + 'interior', + 'exterior', + ), + ) + expect(migrated.faceRegions).toEqual([ + { id: 'band-a-lower', face: 'a', v1: 0.8, finish: 'library:1' }, + { id: 'band-a-middle', face: 'a', v0: 0.8, v1: 1.3, finish: 'library:2' }, + { id: 'band-a-upper', face: 'a', v0: 1.3, v1: 1.7000000000000002, finish: 'library:3' }, + { id: 'band-a-top', face: 'a', v0: 1.7000000000000002, finish: 'library:4' }, + { id: 'band-b-middle', face: 'b', v0: 0.8, v1: 1.3, finish: 'library:b2' }, + ]) + expect(migrated.slots).toEqual({}) + }) + + test('two and three bands, reversed sides, and existing regions stay on top', () => { + const two = migrate( + wall( + { + faceBands: { enabled: true, count: 2, lowerHeight: 1.1 }, + slots: { lowerInterior: 'library:low', upperExterior: 'library:up' }, + faceRegions: [{ id: 'mine', face: 'a', u0: 1, finish: 'library:mine' }], + }, + 'exterior', + 'interior', + ), + ) + expect(two.faceRegions).toEqual([ + { id: 'band-a-upper', face: 'a', v0: 1.1, finish: 'library:up' }, + { id: 'band-b-lower', face: 'b', v1: 1.1, finish: 'library:low' }, + { id: 'mine', face: 'a', u0: 1, finish: 'library:mine' }, + ]) + const three = migrate( + wall( + { faceBands: { enabled: true, count: 3 }, slots: { middleInterior: 'library:mid' } }, + 'interior', + 'exterior', + ), + ) + expect(three.faceRegions).toEqual([ + { id: 'band-a-middle', face: 'a', v0: 0.84, v1: 1.45, finish: 'library:mid' }, + ]) + }) + + test('disabled or single bands leave no regions and drop the config', () => { + for (const faceBands of [ + { enabled: false, count: 3 }, + { enabled: true, count: 1 }, + { enabled: true }, + ]) { + const migrated = migrate( + wall({ faceBands, slots: { lowerInterior: 'library:x' } }, 'interior', 'exterior'), + ) + expect(migrated.faceRegions).toBeUndefined() + expect('faceBands' in migrated).toBe(false) + expect(migrated.slots).toEqual({}) + } + }) +}) + +describe('idempotence', () => { + test('M1 and M2 are no-ops on their own output, even after the sides are reclassified', () => { + for (const extra of Object.values(SCENARIOS)) { + const once = migrate(wall(structuredClone(extra), 'exterior', 'interior')) + expect(migrate(once)).toEqual(once) + const nodes = { [once.id]: once } + expect(migrateWallFaceKeys(nodes).nodes).toBe(nodes) + expect(migrateWallFaceBands(nodes).nodes).toBe(nodes) + // The kernel keeps rewriting sides after edits; a migrated wall must not move again. + const reclassified = { ...once, frontSide: 'interior', backSide: 'exterior' } + expect(migrate(reclassified)).toEqual(reclassified) + } + }) + + test('untouched scenes come back as the same object', () => { + const nodes = { + wall_plain: { + id: 'wall_plain', + type: 'wall', + start: [0, 0], + end: [1, 0], + slots: { a: 'library:x' }, + }, + slab_x: { id: 'slab_x', type: 'slab', slots: { interior: 'library:y' } }, + } + expect(migrateWallFaceKeys(nodes).nodes).toBe(nodes) + expect(migrateWallFaceBands(nodes).nodes).toBe(nodes) + }) +}) diff --git a/packages/core/src/utils/wall-face-migration.ts b/packages/core/src/utils/wall-face-migration.ts new file mode 100644 index 0000000000..e0b967dcdb --- /dev/null +++ b/packages/core/src/utils/wall-face-migration.ts @@ -0,0 +1,281 @@ +import type { WallFace, WallFaceRegion } from '../schema/nodes/wall' + +// Load migrations M1 and M2 of the room-first structure plan. Both are pure, +// idempotent and server-safe: they read and write plain node records only. +// +// M1 re-keys wall finishes from semantic sides (`interior` / `exterior`) onto +// geometric faces (`a` = left of start → end, `b` = right), using the side the +// wall stored when it was saved — exactly the mapping the renderer applied: +// an unknown or corrupt side falls back to front → interior, back → exterior. +// +// M2 turns enabled face bands into full-width horizontal paint regions with +// the same heights and finishes, then drops `faceBands`. + +type RawNode = Record +type LegacySide = 'interior' | 'exterior' + +const LEGACY_SUFFIX: Record = { + interior: 'Interior', + exterior: 'Exterior', +} +const BANDS = ['lower', 'middle', 'upper', 'top'] as const +type Band = (typeof BANDS)[number] +const BAND_SUFFIX: Record = { + lower: 'Lower', + middle: 'Middle', + upper: 'Upper', + top: 'Top', +} +const TRIMS = [ + ['skirting', 'Skirting'], + ['crown', 'Crown'], + ['chairRail', 'ChairRail'], +] as const +const LEGACY_MATERIAL_KEYS = [ + 'interiorMaterial', + 'interiorMaterialPreset', + 'exteriorMaterial', + 'exteriorMaterialPreset', +] as const + +const SEMANTIC_SLOT_KEYS = new Set([ + 'interior', + 'exterior', + 'front', + 'back', + ...BANDS.flatMap((band) => [`${band}Interior`, `${band}Exterior`]), + ...TRIMS.flatMap(([kind]) => [`${kind}Interior`, `${kind}Exterior`]), +]) + +/** Band slot keys M1 emits for M2 to consume (`aLower` … `bTop`). */ +export function wallBandSlotKey(face: WallFace, band: Band): string { + return `${face}${BAND_SUFFIX[band]}` +} + +function isRecord(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) +} + +function slotRecord(node: RawNode): Record { + return isRecord(node.slots) ? node.slots : {} +} + +function hasRef(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 +} + +/** The side a face showed: the stored classification, else front → interior, back → exterior. */ +function legacyFaceSide(node: RawNode, face: WallFace): LegacySide { + const stored = face === 'a' ? node.frontSide : node.backSide + if (stored === 'interior' || stored === 'exterior') return stored + return face === 'a' ? 'interior' : 'exterior' +} + +/** The face a legacy trim side drew on (the treatment renderer's side sign). */ +function legacyTrimFace(node: RawNode, side: LegacySide): WallFace { + if (node.frontSide === side) return 'a' + if (node.backSide === side) return 'b' + return side === 'interior' ? 'a' : 'b' +} + +function trimSides(config: unknown): unknown { + return isRecord(config) ? config.sides : undefined +} + +function needsFaceKeyMigration(node: RawNode): boolean { + if (Object.keys(slotRecord(node)).some((key) => SEMANTIC_SLOT_KEYS.has(key))) return true + if (LEGACY_MATERIAL_KEYS.some((key) => node[key] !== undefined)) return true + return TRIMS.some(([kind]) => { + const sides = trimSides(node[kind]) + return sides === 'interior' || sides === 'exterior' + }) +} + +function hasLegacyMaterial(spec: { material?: unknown; materialPreset?: unknown }) { + return spec.material !== undefined || typeof spec.materialPreset === 'string' +} + +function migrateWallNode(node: RawNode): RawNode { + const source = slotRecord(node) + const slots: Record = {} + for (const [key, value] of Object.entries(source)) { + if (!SEMANTIC_SLOT_KEYS.has(key)) slots[key] = value + } + const put = (key: string, value: unknown) => { + if (!hasRef(slots[key]) && hasRef(value)) slots[key] = value + } + const faceSide = { a: legacyFaceSide(node, 'a'), b: legacyFaceSide(node, 'b') } + + for (const face of ['a', 'b'] as const) { + const suffix = LEGACY_SUFFIX[faceSide[face]] + put(face, source[faceSide[face]]) + for (const band of BANDS) put(wallBandSlotKey(face, band), source[`${band}${suffix}`]) + } + + const next: RawNode = { ...node } + for (const [kind, suffix] of TRIMS) { + const sides = trimSides(node[kind]) + const interiorFace = legacyTrimFace(node, 'interior') + const exteriorFace = legacyTrimFace(node, 'exterior') + // Drawn sides claim their face first. When both legacy sides drew on one + // face (a degenerate side pair), that face keeps the interior trim and the + // other face — which `both` now also draws — takes the exterior one. + const order: LegacySide[] = + sides === 'exterior' ? ['exterior', 'interior'] : ['interior', 'exterior'] + for (const side of order) { + put( + `${side === 'interior' ? interiorFace : exteriorFace}${suffix}`, + source[`${kind}${LEGACY_SUFFIX[side]}`], + ) + } + if (interiorFace === exteriorFace) + put(`${interiorFace === 'a' ? 'b' : 'a'}${suffix}`, source[`${kind}Exterior`]) + if (sides === 'interior' || sides === 'exterior') { + next[kind] = { + ...(node[kind] as Record), + sides: sides === 'interior' ? interiorFace : exteriorFace, + } + } + } + + // Stray geometric aliases written by older tools: only fill a face M1 left empty. + put('a', source.front) + put('b', source.back) + + const legacyFaceMaterials: Record = isRecord(node.legacyFaceMaterials) + ? { ...node.legacyFaceMaterials } + : {} + for (const face of ['a', 'b'] as const) { + if (hasRef(slots[face]) || legacyFaceMaterials[face] !== undefined) continue + const side = faceSide[face] + const spec = { + material: node[`${side}Material`], + materialPreset: node[`${side}MaterialPreset`], + } + if (!hasLegacyMaterial(spec)) continue + legacyFaceMaterials[face] = Object.fromEntries( + Object.entries(spec).filter(([, value]) => value !== undefined), + ) + } + + for (const key of LEGACY_MATERIAL_KEYS) delete next[key] + if (Object.keys(slots).length > 0 || node.slots !== undefined) next.slots = slots + if (Object.keys(legacyFaceMaterials).length > 0) next.legacyFaceMaterials = legacyFaceMaterials + return next +} + +/** + * M1: wall slot keys `interior` / `exterior` (and their band and trim variants, + * plus stray `front` / `back`) become geometric `a` / `b` keys; legacy inline + * side finishes move to `legacyFaceMaterials`; single-sided trims name a face. + * The resolved finish of every face is unchanged. + */ +export function migrateWallFaceKeys(sourceNodes: Record) { + let nodes: Record | null = null + for (const [id, node] of Object.entries(sourceNodes)) { + if (!isRecord(node) || node.type !== 'wall' || !needsFaceKeyMigration(node)) continue + nodes ??= { ...sourceNodes } + nodes[id] = migrateWallNode(node) + } + return { nodes: nodes ?? sourceNodes, changed: nodes !== null } +} + +type RawBands = { + enabled?: unknown + count?: unknown + lowerHeight?: unknown + middleHeight?: unknown + upperHeight?: unknown +} + +const BAND_DEFAULTS = { lowerHeight: 0.84, middleHeight: 0.61, upperHeight: 0.61 } + +function finiteHeight(value: unknown, fallback: number) { + return Math.max(0, typeof value === 'number' && Number.isFinite(value) ? value : fallback) +} + +/** Band count the renderer drew for a stored config (1 = no bands). */ +function drawnBandCount(raw: RawBands): number { + if (raw.enabled !== true) return 1 + const count = raw.count === undefined ? 1 : raw.count + if (typeof count !== 'number' || !Number.isFinite(count)) return 1 + return Math.max(1, Math.min(4, Math.round(count))) +} + +function bandRegions(node: RawNode, slots: Record): WallFaceRegion[] { + const raw = (isRecord(node.faceBands) ? node.faceBands : {}) as RawBands + const count = drawnBandCount(raw) + if (count < 2) return [] + const lower = finiteHeight(raw.lowerHeight, BAND_DEFAULTS.lowerHeight) + const middle = count >= 3 ? finiteHeight(raw.middleHeight, BAND_DEFAULTS.middleHeight) : 0 + const upper = count >= 4 ? finiteHeight(raw.upperHeight, BAND_DEFAULTS.upperHeight) : 0 + const bounds: Array<[Band, number | undefined, number | undefined]> = + count === 2 + ? [ + ['lower', undefined, lower], + ['upper', lower, undefined], + ] + : count === 3 + ? [ + ['lower', undefined, lower], + ['middle', lower, lower + middle], + ['upper', lower + middle, undefined], + ] + : [ + ['lower', undefined, lower], + ['middle', lower, lower + middle], + ['upper', lower + middle, lower + middle + upper], + ['top', lower + middle + upper, undefined], + ] + const regions: WallFaceRegion[] = [] + for (const face of ['a', 'b'] as const) { + for (const [band, v0, v1] of bounds) { + const finish = slots[wallBandSlotKey(face, band)] + // An unpainted band showed the face finish, which is what shows without a region. + if (!hasRef(finish)) continue + if (v0 !== undefined && v1 !== undefined && v1 <= v0) continue + regions.push({ + id: `band-${face}-${band}`, + face, + ...(v0 === undefined ? {} : { v0 }), + ...(v1 === undefined ? {} : { v1 }), + finish, + }) + } + } + return regions +} + +const BAND_SLOT_KEYS = new Set( + (['a', 'b'] as const).flatMap((face) => BANDS.map((band) => wallBandSlotKey(face, band))), +) + +/** + * M2: enabled face bands (2–4) become full-width horizontal `faceRegions` with + * the same heights and finishes; `faceBands` and the band slot keys are dropped. + * Runs after M1 (it reads the geometric band keys M1 writes). + */ +export function migrateWallFaceBands(sourceNodes: Record) { + let nodes: Record | null = null + for (const [id, node] of Object.entries(sourceNodes)) { + if (!isRecord(node) || node.type !== 'wall') continue + const slots = slotRecord(node) + const bandKeys = Object.keys(slots).filter((key) => BAND_SLOT_KEYS.has(key)) + if (node.faceBands === undefined && !('faceBands' in node) && bandKeys.length === 0) continue + const regions = bandRegions(node, slots) + const next: RawNode = { ...node } + delete next.faceBands + if (bandKeys.length > 0) { + next.slots = Object.fromEntries( + Object.entries(slots).filter(([key]) => !BAND_SLOT_KEYS.has(key)), + ) + } + if (regions.length > 0) { + const existing = Array.isArray(node.faceRegions) ? node.faceRegions : [] + next.faceRegions = [...regions, ...existing] + } + nodes ??= { ...sourceNodes } + nodes[id] = next + } + return { nodes: nodes ?? sourceNodes, changed: nodes !== null } +} diff --git a/packages/editor/src/components/editor-2d/floorplan-cursor-indicator-overlay.tsx b/packages/editor/src/components/editor-2d/floorplan-cursor-indicator-overlay.tsx index 422c27a66d..eeb7037792 100644 --- a/packages/editor/src/components/editor-2d/floorplan-cursor-indicator-overlay.tsx +++ b/packages/editor/src/components/editor-2d/floorplan-cursor-indicator-overlay.tsx @@ -2,6 +2,7 @@ import { Icon } from '@iconify/react' import { memo, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { wallCursorIcon } from '../../lib/tool-cursor-icon' import useEditor, { type FloorplanSelectionTool } from '../../store/use-editor' import { useFloorplanDraftPreview } from '../../store/use-floorplan-draft-preview' import { furnishTools } from '../ui/action-menu/furnish-tools' @@ -45,8 +46,8 @@ export const FloorplanCursorIndicatorOverlay = memo(function FloorplanCursorIndi }: FloorplanCursorIndicatorOverlayProps) { const mode = useEditor((state) => state.mode) const tool = useEditor((state) => state.tool) - const structureLayer = useEditor((state) => state.structureLayer) const catalogCategory = useEditor((state) => state.catalogCategory) + const wallMode = useEditor((state) => state.continuationByContext.wall) const cursorPoint = useFloorplanDraftPreview((state) => state.cursorPoint) const anchorRef = useRef(null) const [projectedCursorPosition, setProjectedCursorPosition] = @@ -65,15 +66,18 @@ export const FloorplanCursorIndicatorOverlay = memo(function FloorplanCursorIndi return furnishTools.find((entry) => entry.catalogCategory === catalogCategory) ?? null } + // The wall shows its Rooms variant, like the 3D cursor bubble. + if (tool === 'wall') return wallCursorIcon(wallMode) + return structureTools.find((entry) => entry.id === tool) ?? null - }, [catalogCategory, mode, movingOpeningType, tool]) + }, [catalogCategory, mode, movingOpeningType, tool, wallMode]) const indicator = useMemo(() => { if (activeFloorplanToolConfig) { return { kind: 'asset', iconSrc: activeFloorplanToolConfig.iconSrc } } - if (mode === 'select' && floorplanSelectionTool === 'marquee' && structureLayer !== 'zones') { + if (mode === 'select' && floorplanSelectionTool === 'marquee') { return { kind: 'icon', icon: 'mdi:select-drag' } } @@ -86,7 +90,7 @@ export const FloorplanCursorIndicatorOverlay = memo(function FloorplanCursorIndi } return null - }, [activeFloorplanToolConfig, floorplanSelectionTool, mode, structureLayer]) + }, [activeFloorplanToolConfig, floorplanSelectionTool, mode]) useLayoutEffect(() => { const anchor = anchorRef.current diff --git a/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx b/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx index cdf0ec9e2e..6d6f7e51df 100644 --- a/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx +++ b/packages/editor/src/components/editor-2d/floorplan-registry-action-menu.tsx @@ -38,6 +38,7 @@ import useInteractionScope, { useMovingNode, } from '../../store/use-interaction-scope' import { NodeActionMenu } from '../editor/node-action-menu' +import { startZoneRoomTransform } from '../editor/room-controls' import { IconRefGlyph } from '../ui/icon-ref' function SideAddGlyph({ direction }: { direction: 'left' | 'right' }) { @@ -258,6 +259,7 @@ export function FloorplanRegistryActionMenu() { const canAddHole = node.type === 'slab' || node.type === 'ceiling' const handleMove = () => { + if (startZoneRoomTransform(node, 'move')) return sfxEmitter.emit('sfx:item-pick') const sceneNodes = useScene.getState().nodes setMovingNode(resolveMoveActionNode(node, sceneNodes) as never) @@ -321,6 +323,7 @@ export function FloorplanRegistryActionMenu() { const handleDuplicate = () => { if (!node.parentId) return + if (startZoneRoomTransform(node, 'duplicate')) return sfxEmitter.emit('sfx:item-pick') if (registryMoveDisabled(node)) { try { diff --git a/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.test.ts b/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.test.ts index 7e7d4d3f5d..ab9133da96 100644 --- a/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.test.ts +++ b/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.test.ts @@ -15,6 +15,7 @@ import { FLOORPLAN_NODE_EXTENSION_KEY, floorplanGeometryMetadata, } from '../../../lib/floorplan/floorplan-extension' +import type { SessionWrites } from '../../../lib/session-writes' import { buildFloorplanEntryGeometry, cancelFloorplanAffordanceDrag, @@ -30,6 +31,7 @@ import { isFloorplanOpeningPlacementState, resolveFloorplanHandleUnitsPerPixel, siteToFloorplanTransform, + splitFloorplanHandles, splitFloorplanOverlay, subscribeFloorplanAffordanceToolCancel, } from './floorplan-registry-layer' @@ -385,7 +387,13 @@ describe('floorplan affordance cancellation', () => { canCommit: () => true, commit, } - const snapshots = [{ id: 'wall_a' as AnyNodeId, data: { width: 1 } }] + const revert = mock(() => {}) + const writes = { + record: (run: () => unknown) => run(), + revert, + changes: () => ({ create: [], update: [], delete: [] }), + size: 0, + } as unknown as SessionWrites const drag = { pointerId: 7, captureTarget: { @@ -394,12 +402,11 @@ describe('floorplan affordance cancellation', () => { } as unknown as Element, handleId: 'wall_a:endpoint', session, - snapshots, + writes, historyPaused: true, lastPlanPoint: [0, 0] as [number, number], } const dragRef = { current: drag } - const restoreSnapshots = mock(() => {}) const resumeHistory = mock(() => {}) const clearPreview = mock(() => {}) const clearSnapFeedback = mock(() => {}) @@ -410,7 +417,6 @@ describe('floorplan affordance cancellation', () => { const unsubscribe = subscribeFloorplanAffordanceToolCancel( () => cancelFloorplanAffordanceDrag(dragRef, { - restoreSnapshots, resumeHistory, clearPreview, clearSnapFeedback, @@ -429,7 +435,7 @@ describe('floorplan affordance cancellation', () => { expect(dragRef.current).toBeNull() expect(releasePointerCapture).toHaveBeenCalledWith(7) - expect(restoreSnapshots).toHaveBeenCalledWith(snapshots) + expect(revert).toHaveBeenCalledTimes(1) expect(resumeHistory).toHaveBeenCalledTimes(1) expect(clearPreview).toHaveBeenCalledTimes(2) expect(clearPreview).toHaveBeenNthCalledWith(1, 'wall_a') @@ -829,3 +835,30 @@ describe('isFloorplanHierarchyVisible', () => { expect(visibleUnder(nodes, 'level_a', 'wall_a')).toBe(true) }) }) + +describe('the handles pass', () => { + test('grabbable handles leave the overlay for a pass of their own, under the same transform', () => { + const label = { kind: 'text', x: 0, y: 0, text: 'Wall 1' } as FloorplanGeometry + const corner = { + kind: 'endpoint-handle', + point: [1, 0], + state: 'idle', + affordance: 'move-endpoint', + payload: { wallId: 'wall_a', endpoint: 'end' }, + } as FloorplanGeometry + const tree = { + kind: 'group', + transform: 'rotate(30)', + children: [label, { kind: 'group', children: [corner] }], + } as FloorplanGeometry + expect(splitFloorplanHandles(tree)).toEqual({ + rest: { kind: 'group', transform: 'rotate(30)', children: [label] }, + handles: { + kind: 'group', + transform: 'rotate(30)', + children: [{ kind: 'group', children: [corner] }], + }, + } as never) + expect(splitFloorplanHandles(label)).toEqual({ rest: label, handles: null }) + }) +}) diff --git a/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.tsx b/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.tsx index 9673419b47..0f0c0e0f5e 100644 --- a/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.tsx +++ b/packages/editor/src/components/editor-2d/renderers/floorplan-registry-layer.tsx @@ -23,6 +23,7 @@ import { resolveBuildingForLevel, resolveSelectionProxyId, resumeSceneHistory, + type SlabNode, useInteractive, useLiveNodeOverrides, useLiveTransforms, @@ -43,6 +44,14 @@ import { } from 'react' import { useShallow } from 'zustand/react/shallow' import { markToolCancelConsumed } from '../../../hooks/use-keyboard' +import { + hoverRoomFromHit, + resolvePlanRoomHit, + roomPickingEnabled, + selectionModifiersFromEvent, + useRoomRecords, +} from '../../../hooks/use-selected-room' +import { useCeilingEditSession } from '../../../lib/ceiling-edit-session' import { ROTATE_HANDLE_DRAG_LABEL } from '../../../lib/contextual-help' import { canDirectRotateNode, @@ -53,6 +62,7 @@ import { snapDirectRotationDelta, } from '../../../lib/direct-manipulation' import { createEditorApi } from '../../../lib/editor-api' +import { isRoomOwnedPlate, roomOwnedPlateDrillTarget } from '../../../lib/floor-footprints' import { type FloorplanAnnotationVisibility, filterFloorplanAnnotationGeometry, @@ -86,7 +96,12 @@ import { isIdle, tangentReshapeScope, } from '../../../lib/interaction/scope' +import { runFloorplanWallPush, WALL_PUSH_AFFORDANCE } from '../../../lib/room-handle-drag' +import { sameRoom } from '../../../lib/room-selection' +import { selectRoom, selectRoomFromHit } from '../../../lib/room-selection-commands' +import { roomKeyForZone } from '../../../lib/room-zone-routing' import { emitCanvasNodeSelection } from '../../../lib/selection-routing' +import { createSessionWrites, type SessionWrites } from '../../../lib/session-writes' import { sfxEmitter } from '../../../lib/sfx-bus' import { clearSurfacePlanSnapFeedback } from '../../../lib/surface-plan-snap' import { paintZoneMembership } from '../../../lib/units' @@ -101,8 +116,11 @@ import useInteractionScope, { useMovingNode, } from '../../../store/use-interaction-scope' import { expandSessionSelectionForNode } from '../../../store/use-session-groups' +import { FloorRegionControls2D } from '../../editor/floor-region-controls' import { startGroupPickUp } from '../../editor/group-actions' import { classifyParticipant } from '../../editor/group-transform-shared' +import { RoomHandleDragPreview2D, RoomHandles2D } from '../../editor/room-handles-2d' +import { RoomHighlight2D } from '../../editor/room-highlight' import { suppressBoxSelectForPointer } from '../../tools/select/box-select-state' import { FloorplanGroupSelectionBox, @@ -180,22 +198,19 @@ const ScaleAwareFloorplanGroupSelectionBox = memo(function ScaleAwareFloorplanGr return }) -/** - * Snapshot of node fields captured at drag-start, used by the single-undo - * dance to revert untracked before re-applying as a single tracked - * change. The dispatcher only knows about the `affectedIds` the - * affordance declares; it captures whatever fields exist on each node by - * cloning the full record minus the registry-managed `id` / `type`. - */ -type NodeSnapshot = { id: AnyNodeId; data: Record } - type ActiveDrag = { pointerId: number captureTarget: Element /** Key for the visual `active` flag — e.g. `${nodeId}:${endpoint}`. */ handleId: string session: FloorplanAffordanceSession - snapshots: NodeSnapshot[] + /** + * What the session itself wrote to the scene during `apply()` (legacy + * sessions only; override-only sessions write nothing). Cancel and commit + * take back exactly these writes, so a collaborator's edit to the same node + * mid-drag survives. + */ + writes: SessionWrites historyPaused: boolean /** * Last plan point handed to `session.apply` (the grab point until the first @@ -219,7 +234,6 @@ type ActiveDrag = { } type FloorplanAffordanceCancelEffects = { - restoreSnapshots: (snapshots: NodeSnapshot[]) => void resumeHistory: () => void clearPreview: (id: AnyNodeId) => void clearSnapFeedback: () => void @@ -243,7 +257,7 @@ export function cancelFloorplanAffordanceDrag( drag.captureTarget.releasePointerCapture?.(drag.pointerId) } - effects.restoreSnapshots(drag.snapshots) + drag.writes.revert() if (drag.historyPaused) { effects.resumeHistory() drag.historyPaused = false @@ -379,6 +393,7 @@ type CacheEntry = { deps: NodeDeps base: FloorplanGeometry | null overlay: FloorplanGeometry | null + handles: FloorplanGeometry | null node: AnyNode } @@ -434,7 +449,7 @@ type FloorplanLevelDataHook = (args: { nodes: Record }) => unknown -type FloorplanRenderPass = 'base' | 'overlay' +type FloorplanRenderPass = 'base' | 'overlay' | 'handles' const POINTER_CURSOR_STYLE = { cursor: 'pointer' } as const // Group members advertise the drag-to-move-the-selection gesture. @@ -487,21 +502,6 @@ function floorplanEntryYieldsToToolNow(): boolean { }) } -function snapshotNode(node: AnyNode): NodeSnapshot { - // Shallow-clone every non-id, non-type field. Arrays / vec tuples are - // deep-cloned to detach from the live store reference. - const data: Record = {} - for (const [key, value] of Object.entries(node)) { - if (key === 'id' || key === 'type' || key === 'object' || key === 'parentId') continue - data[key] = Array.isArray(value) ? [...(value as unknown[])] : value - } - return { id: node.id, data } -} - -function snapshotsToUpdates(snapshots: NodeSnapshot[]) { - return snapshots.map((s) => ({ id: s.id, data: s.data })) -} - // Stable empty sentinel used by per-entry builders while the floor plan is // hidden; committed scene edits still flow through `useScene`. const EMPTY_LIVE_OVERRIDES: Map = new Map() @@ -565,6 +565,7 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { }, [selectedLevelId, ambientBuildingSourceId, nodes]) const levelId = selectedLevelId ?? ambientLevelId + useRoomRecords(levelId) const isAmbient = !selectedLevelId && !!ambientLevelId const activeBuildingId = useMemo( () => (levelId ? resolveBuildingForLevel(levelId as AnyNodeId, nodes) : null), @@ -585,13 +586,11 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { // `handleClickStop` / `handleSelect`, so the tool never sees it. Pass // clicks through in that case (`floorplanEntryYieldsToToolNow`). const editorMode = useEditor((s) => s.mode) - const structureLayer = useEditor((s) => s.structureLayer) const floorplanSelectionTool = useEditor((s) => s.floorplanSelectionTool) const endpointReshape = useEndpointReshape() const isMarqueeSelectionActive = editorMode === 'select' && floorplanSelectionTool === 'marquee' && - structureLayer !== 'zones' && !movingNode && !endpointReshape // While the floor plan is not on screen (pure 3D view), per-entry live @@ -698,6 +697,18 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { swallowNextClick(200) return } + // A room's fill or label is the room (the same panel, pill and Escape + // ladder as a click on its floor); clicking the room already selected + // keeps it. Other zones stay zones. + if (clickedNode?.type === 'zone' && !options.shouldToggle) { + const room = roomKeyForZone(clickedNode.id) + if (room) { + if (!sameRoom(useEditor.getState().room, room)) selectRoom(room) + swallowNextClick(200) + return + } + } + if (clickedNode?.type === 'zone') useEditor.getState().clearRoom() const currentSelectedIds = useViewer.getState().selection.selectedIds let nextSelectedIds: string[] if (options.shouldToggle) { @@ -755,13 +766,13 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { ) const handleClickStop = useCallback((event: React.MouseEvent) => { - if (floorplanEntryYieldsToToolNow()) return + if (floorplanEntryYieldsToToolNow() || !isIdle(useInteractionScope.getState().scope)) return event.stopPropagation() }, []) const startDirectMoveDrag = useCallback( (id: AnyNodeId, event: ReactPointerEvent): boolean => { - if (event.button !== 0) return false + if (event.button !== 0 || event.altKey) return false const node = useScene.getState().nodes[id] if (!node || !isRegistryMovable(node.type)) return false @@ -1016,7 +1027,30 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { // the stores at event time. Commit clears the interaction scope before // React paints the next frame; a render-time `undefined` handler leaves // a short dead zone where the first post-placement selection is lost. - if (floorplanEntryYieldsToToolNow()) return + if (floorplanEntryYieldsToToolNow() || !isIdle(useInteractionScope.getState().scope)) return + const point = clientToPlan(event.clientX, event.clientY) + if ( + event.button === 0 && + point && + roomPickingEnabled() && + selectRoomFromHit(resolvePlanRoomHit(id, point), selectionModifiersFromEvent(event), id) + ) { + event.stopPropagation() + swallowNextClick(200) + return + } + // A room-owned plate past its room: the same routing as the 3D click. + const plate = useScene.getState().nodes[id] + if (event.button === 0 && point && roomPickingEnabled() && isRoomOwnedPlate(plate)) { + const footprint = roomOwnedPlateDrillTarget(useScene.getState().nodes, plate as SlabNode) + if (footprint) handleSelect(footprint.id as AnyNodeId, event) + else { + const hit = resolvePlanRoomHit(id, point) + if (hit) selectRoom(hit) + event.stopPropagation() + } + return + } if (startDirectMoveDrag(id, event)) return if (startDirectRotateDrag(id, event)) return if (startGroupMoveDrag(id, event)) return @@ -1242,6 +1276,16 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { if (event.button !== 0) return if (movingNode) return + // A wall push arrow runs the same push drag as the 3D arrows (its own + // gesture, preview and commit), not a registry affordance session. + if (affordance === WALL_PUSH_AFFORDANCE) { + event.preventDefault() + event.stopPropagation() + suppressBoxSelectForPointer(event) + runFloorplanWallPush(payload, event.clientX, event.clientY) + return + } + const sceneNodes = useScene.getState().nodes const node = sceneNodes[nodeId] if (!node) return @@ -1267,13 +1311,9 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { sceneApi: createSceneApi(useScene), }) - const snapshots: NodeSnapshot[] = [] - for (const id of session.affectedIds) { - const n = sceneNodes[id] - if (n) snapshots.push(snapshotNode(n)) - } - pauseSceneHistory(useScene) + const writes = createSessionWrites() + writes.watch(session.affectedIds) // Rotation readout setup. The wedge radius tracks the grab distance // from the pivot (≈ the handle's orbit), nudged inward so the swept @@ -1305,7 +1345,7 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { captureTarget, handleId, session, - snapshots, + writes, historyPaused: true, lastPlanPoint: initialPlanPoint, rotation, @@ -1338,8 +1378,6 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { cancelFloorplanAffordanceDrag( dragRef, { - restoreSnapshots: (snapshots) => - useScene.getState().updateNodes(snapshotsToUpdates(snapshots)), resumeHistory: () => resumeSceneHistory(useScene), clearPreview: (id) => { useLiveNodeOverrides.getState().clear(id) @@ -1365,15 +1403,17 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { if (!planPoint) return drag.lastPlanPoint = planPoint - drag.session.apply({ - planPoint, - modifiers: { - shiftKey: event.shiftKey, - altKey: event.altKey, - ctrlKey: event.ctrlKey, - metaKey: event.metaKey, - }, - }) + drag.writes.record(() => + drag.session.apply({ + planPoint, + modifiers: { + shiftKey: event.shiftKey, + altKey: event.altKey, + ctrlKey: event.ctrlKey, + metaKey: event.metaKey, + }, + }), + ) // Live rotation readout. Sweep from the bearing at grab to the // current pointer bearing around the pivot — the same measurement @@ -1410,11 +1450,11 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { // Sessions with a `commit` hook own their atomic write (e.g. // affordances that publish to `useLiveNodeOverrides` during // `apply()` and never touch scene mid-drag). Mirrors the move - // overlay's `session.commit` path — revert untracked (no-op when - // the session never wrote to scene), resume history, then let - // the session do the tracked write. + // overlay's `session.commit` path — take back what the session wrote + // (nothing, for those), resume history, then let the session do the + // tracked write. if (commitValid && drag.session.commit) { - useScene.getState().updateNodes(snapshotsToUpdates(drag.snapshots)) + drag.writes.revert() if (drag.historyPaused) { resumeSceneHistory(useScene) drag.historyPaused = false @@ -1431,37 +1471,23 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { } // Legacy compatibility for sessions that still wrote preview state into - // `useScene` during `apply()`: capture the final state BEFORE the revert - // so we know what to re-apply post-resume. New sessions should provide a - // `commit()` hook and preview through live overrides/transforms instead. - const sceneNodes = useScene.getState().nodes - const finalUpdates: Array<{ id: AnyNodeId; data: Record }> = [] - for (const snap of drag.snapshots) { - const current = sceneNodes[snap.id] - if (!current) continue - const data: Record = {} - let changed = false - for (const [key, before] of Object.entries(snap.data)) { - const after = (current as unknown as Record)[key] - if (!deepEqual(before, after)) { - data[key] = Array.isArray(after) ? [...(after as unknown[])] : after - changed = true - } - } - if (changed) finalUpdates.push({ id: snap.id, data }) - } + // `useScene` during `apply()`: the fields they wrote are re-applied as + // one tracked change after the untracked revert. New sessions should + // provide a `commit()` hook and preview through live overrides/transforms. + const changes = drag.writes.changes() + const changed = changes.create.length + changes.update.length + changes.delete.length > 0 - if (commitValid && finalUpdates.length > 0) { + if (commitValid && changed) { // Legacy single-undo dance (mirrors the old 3D move-endpoint-tool): - // 1. Revert to baseline while history is still paused (untracked). + // 1. Take back the session's writes while history is still paused. // 2. Resume history. - // 3. Re-apply the final state — recorded as one tracked change. - useScene.getState().updateNodes(snapshotsToUpdates(drag.snapshots)) + // 3. Re-apply them — recorded as one tracked change. + drag.writes.revert() if (drag.historyPaused) { resumeSceneHistory(useScene) drag.historyPaused = false } - useScene.getState().updateNodes(finalUpdates) + useScene.getState().applyNodeChanges(changes) commitPerfAction() sfxEmitter.emit('sfx:structure-build') } else { @@ -1469,7 +1495,7 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { // resume without committing. Also clear any live overrides // the session published (no-op when the session writes to // scene directly). - useScene.getState().updateNodes(snapshotsToUpdates(drag.snapshots)) + drag.writes.revert() if (drag.historyPaused) { resumeSceneHistory(useScene) drag.historyPaused = false @@ -1505,15 +1531,17 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { ) { return } - drag.session.apply({ - planPoint: drag.lastPlanPoint, - modifiers: { - shiftKey: event.shiftKey, - altKey: event.altKey, - ctrlKey: event.ctrlKey, - metaKey: event.metaKey, - }, - }) + drag.writes.record(() => + drag.session.apply({ + planPoint: drag.lastPlanPoint, + modifiers: { + shiftKey: event.shiftKey, + altKey: event.altKey, + ctrlKey: event.ctrlKey, + metaKey: event.metaKey, + }, + }), + ) } window.addEventListener('pointermove', onPointerMove) @@ -1543,6 +1571,48 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { const palette = renderCtx?.palette + const renderEntries = (pass: FloorplanRenderPass) => + entries.map((entry) => ( + + )) + return ( // The outer wrapper stops `click` events that escape an entry's // `onClick={handleClickStop}`. The base+overlay split means @@ -1568,48 +1638,9 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { strokes, hatches). Lower-rank kinds (zones) paint first so higher-rank kinds (slabs, then walls / items / shelves) layer on top in the expected document-order z-stack. */} - - {entries.map((entry) => ( - - ))} - + {renderEntries('base')} + + {/* Overlay pass — interactive handles (vertex / midpoint / edge / move) and labels (text / dimensions). Painted after every base entry so polygon-editor chrome on a selected slab stays above @@ -1617,48 +1648,12 @@ export const FloorplanRegistryLayer = memo(function FloorplanRegistryLayer() { slab + wall geometry sitting on top of the zone. Each overlay still routes through the same selection-handling `` so a click on a zone's name selects the zone. */} - - {entries.map((entry) => ( - - ))} - + {renderEntries('overlay')} + {/* Handles pass — every grabbable handle above every node's overlay, + so a neighbour's outline never covers a selected wall's corner. */} + {renderEntries('handles')} + + {/* Click-to-type dimension labels. Portals its HTML input to document.body, so mounting it inside the SVG tree is safe. */} @@ -2027,10 +2022,15 @@ const FloorplanRegistryEntry = memo(function FloorplanRegistryEntry({ }: FloorplanRegistryEntryProps): React.ReactElement | null { const selected = useViewer((state) => state.selection.selectedIds.includes(nodeId)) const highlighted = useViewer((state) => state.previewSelectedIds.includes(nodeId)) - const suppressHandles = useViewer( + const multiSelected = useViewer( (state) => state.selection.selectedIds.length > 1 && state.selection.selectedIds.includes(nodeId), ) + // A ceiling's vertex / edge handles belong to its Edit ceiling session. + const ceilingWithoutSession = useCeilingEditSession( + (state) => node.type === 'ceiling' && state.session?.ceilingId !== nodeId, + ) + const suppressHandles = multiSelected || ceilingWithoutSession const selectedLevelId = useViewer((state) => state.selection.levelId) const selectionProxyId = resolveSelectionProxyId( node, @@ -2045,7 +2045,7 @@ const FloorplanRegistryEntry = memo(function FloorplanRegistryEntry({ state.activeRotateNodeId === nodeId ? nodeId : null, ) const groupMoveCursor = - suppressHandles && classifyParticipant(node, selectedLevelId, nodes) !== null + multiSelected && classifyParticipant(node, selectedLevelId, nodes) !== null const live = useLiveTransforms((s) => (floorplanVisible ? s.transforms.get(nodeId) : undefined)) const liveOverride = useLiveNodeOverrides((s) => floorplanVisible ? s.overrides.get(nodeId) : undefined, @@ -2070,19 +2070,35 @@ const FloorplanRegistryEntry = memo(function FloorplanRegistryEntry({ // Mirror the sidebar tree nodes' hover wiring — `useViewer.hoveredId` drives // the highlight halo in 3D as well as registry floor-plan hover strokes. - const handlePointerEnter = useCallback(() => { - const currentNode = useScene.getState().nodes[nodeId] - setHoveredId( - currentNode - ? resolveSelectionProxyId( - currentNode, - useScene.getState().nodes as Record, - ) - : nodeId, - ) - }, [nodeId, setHoveredId]) + const handlePointerEnter = useCallback( + (event: ReactPointerEvent) => { + if (floorplanEntryYieldsToToolNow() || !isIdle(useInteractionScope.getState().scope)) return + const point = clientToPlan(event.clientX, event.clientY) + if ( + point && + roomPickingEnabled() && + hoverRoomFromHit( + resolvePlanRoomHit(nodeId, point), + selectionModifiersFromEvent(event), + nodeId, + ) + ) + return + const currentNode = useScene.getState().nodes[nodeId] + setHoveredId( + currentNode + ? resolveSelectionProxyId( + currentNode, + useScene.getState().nodes as Record, + ) + : nodeId, + ) + }, + [nodeId, setHoveredId], + ) const handlePointerLeave = useCallback(() => { + useEditor.getState().setHoveredRoom(null) const node = useScene.getState().nodes[nodeId] const targetId = node ? resolveSelectionProxyId( @@ -2164,7 +2180,7 @@ const FloorplanRegistryEntry = memo(function FloorplanRegistryEntry({ wallDimensionReference, visibilityRootId, }) - const rawGeometry = cacheEntry ? (pass === 'base' ? cacheEntry.base : cacheEntry.overlay) : null + const rawGeometry = cacheEntry ? cacheEntry[pass] : null const visibleGeometry = rawGeometry ? filterFloorplanAnnotationGeometry(rawGeometry, presentationVisibility) : null @@ -2172,7 +2188,7 @@ const FloorplanRegistryEntry = memo(function FloorplanRegistryEntry({ // dimension chrome (all of which live in the overlay pass) while keeping // its highlighted body geometry. const geometry = - visibleGeometry && suppressHandles && pass === 'overlay' + visibleGeometry && suppressHandles && pass !== 'base' ? stripHandleChrome(visibleGeometry) : visibleGeometry if (!geometry) return null @@ -2187,6 +2203,7 @@ const FloorplanRegistryEntry = memo(function FloorplanRegistryEntry({ onClick={entryClick} onPointerDown={entryPointerDown} onPointerEnter={handlePointerEnter} + onPointerMove={handlePointerEnter} onPointerLeave={handlePointerLeave} style={groupMoveCursor ? MOVE_CURSOR_STYLE : POINTER_CURSOR_STYLE} > @@ -2471,10 +2488,13 @@ export function buildFloorplanEntryGeometry({ transform: ctxOverrides.outputTransform, } : unprojectedGeometry - const { base, overlay } = geometry + const { base, overlay: overlayWithHandles } = geometry ? splitFloorplanOverlay(geometry) : { base: null, overlay: null } - const entry: CacheEntry = { deps, base, overlay, node: effectiveNode } + const { rest: overlay, handles } = overlayWithHandles + ? splitFloorplanHandles(overlayWithHandles) + : { rest: null, handles: null } + const entry: CacheEntry = { deps, base, overlay, handles, node: effectiveNode } geometryCache.set(nodeId, entry) return entry } @@ -2927,12 +2947,13 @@ export const InteractiveGeometry = memo(function InteractiveGeometry({ // body (matches the 3D `HANDLE_OFFSET`). const bi = 0.03 // base inset const arrowD = `M ${bi},${-sh} L ${bi + sl},${-sh} L ${bi + sl},${-hh} L ${bi + sl + hl},0 L ${bi + sl},${hh} L ${bi + sl},${sh} L ${bi},${sh} Z` - // Indigo palette to match the 3D `WallMoveSideHandles` arrows + // Indigo palette to match the 3D wall push arrows // (`ARROW_COLOR` / `ARROW_HOVER_COLOR`) and the corner-sphere // accent in `floating-action-menu.tsx`. const fill = isHovered ? '#a5b4fc' : '#8381ed' const angleDeg = (g.angle * 180) / Math.PI - const cursor = g.affordance ? 'ew-resize' : 'move' + const cursor = + g.affordance === WALL_PUSH_AFFORDANCE ? 'grab' : g.affordance ? 'ew-resize' : 'move' const affordance = g.affordance const payload = g.payload // No hover-grow: a scaling transform would enlarge the hit area @@ -3519,6 +3540,42 @@ export function splitFloorplanOverlay(g: FloorplanGeometry): { return { base: g, overlay: null } } +/** The kinds a pointer grabs: they paint and hit-test above every node's outline. */ +const HANDLE_KINDS = new Set([ + 'endpoint-handle', + 'midpoint-handle', + 'edge-handle', + 'move-handle', + 'move-arrow', + 'rotate-arrow', +]) + +/** + * Splits an overlay tree into its grabbable handles and the rest (labels, + * dimensions, outlines). The handles render in a pass of their own after + * every node's overlay: an outline painted later (a neighbouring wall's body) + * would otherwise cover a selected wall's corner handle and take its press — + * the 2D twin of the 3D handle hit priority. + */ +export function splitFloorplanHandles(g: FloorplanGeometry): { + rest: FloorplanGeometry | null + handles: FloorplanGeometry | null +} { + if (HANDLE_KINDS.has(g.kind)) return { rest: null, handles: g } + if (g.kind !== 'group') return { rest: g, handles: null } + const rest: FloorplanGeometry[] = [] + const handles: FloorplanGeometry[] = [] + for (const child of g.children) { + const split = splitFloorplanHandles(child) + if (split.rest) rest.push(split.rest) + if (split.handles) handles.push(split.handles) + } + return { + rest: rest.length ? { ...g, children: rest } : null, + handles: handles.length ? { ...g, children: handles } : null, + } +} + /** * Per-node edit chrome hidden while a multi-selection is active: the group is * manipulated as one rigid piece (drag to move, R/T to rotate), so individual @@ -3707,29 +3764,6 @@ function depsValueEqual(a: unknown, b: unknown): boolean { */ export { floorplanLayerRank } -function deepEqual(a: unknown, b: unknown): boolean { - if (a === b) return true - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) return false - for (let i = 0; i < a.length; i++) { - if (!deepEqual(a[i], b[i])) return false - } - return true - } - if (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null) { - const aKeys = Object.keys(a as Record) - const bKeys = Object.keys(b as Record) - if (aKeys.length !== bKeys.length) return false - for (const key of aKeys) { - if (!deepEqual((a as Record)[key], (b as Record)[key])) { - return false - } - } - return true - } - return false -} - const ROTATION_WEDGE_COLOR = '#8381ed' const ROTATION_WEDGE_SEGMENTS = 48 diff --git a/packages/editor/src/components/editor/capture-level-picker.tsx b/packages/editor/src/components/editor/capture-level-picker.tsx new file mode 100644 index 0000000000..9a54de3e2e --- /dev/null +++ b/packages/editor/src/components/editor/capture-level-picker.tsx @@ -0,0 +1,72 @@ +'use client' + +import { type BuildingNode, getLevelDisplayName, type LevelNode, useScene } from '@pascal-app/core' +import { useViewer } from '@pascal-app/viewer' +import { useShallow } from 'zustand/react/shallow' +import { cn } from '../../lib/utils' +import useEditor from '../../store/use-editor' + +const rowClass = (selected: boolean) => + cn( + 'flex w-full min-w-0 items-center rounded-lg px-2.5 py-1.5 text-left font-medium text-xs transition-colors', + selected + ? 'bg-white/10 text-foreground' + : 'text-muted-foreground/70 hover:bg-white/5 hover:text-muted-foreground', + ) + +/** + * The capture view's level picker: the editor's level list, top floor first, + * under a "Whole building" row that shows every level (the default on entering + * capture). A level shows itself and the levels below it, as while editing. + */ +export function CaptureLevelPicker() { + const captureLevelId = useEditor((s) => s.captureLevelId) + const setCaptureLevel = useEditor((s) => s.setCaptureLevel) + const buildingId = useViewer((s) => s.selection.buildingId) + const levels = useScene( + useShallow((state) => { + const building = ( + buildingId + ? state.nodes[buildingId] + : Object.values(state.nodes).find((n) => n?.type === 'building') + ) as BuildingNode | undefined + if (building?.type !== 'building') return [] as LevelNode[] + return building.children + .map((id) => state.nodes[id]) + .filter((node): node is LevelNode => node?.type === 'level') + .sort((a, b) => b.level - a.level) + }), + ) + if (levels.length < 2) return null + + return ( +
+ +
+ {levels.map((level) => ( + + ))} +
+ ) +} diff --git a/packages/editor/src/components/editor/delete-confirmation-dialog.tsx b/packages/editor/src/components/editor/delete-confirmation-dialog.tsx index 05194a00bc..300f4e2e62 100644 --- a/packages/editor/src/components/editor/delete-confirmation-dialog.tsx +++ b/packages/editor/src/components/editor/delete-confirmation-dialog.tsx @@ -1,7 +1,17 @@ 'use client' -import { useEffect } from 'react' -import useDeleteConfirmation from '../../store/use-delete-confirmation' +import { + type AnyNode, + type DeleteZonePayload, + type StructureNodes, + useScene, +} from '@pascal-app/core' +import { useEffect, useMemo, useRef } from 'react' +import { cn } from '../../lib/utils' +import useDeleteConfirmation, { + type DeleteConfirmationRequest, + type RoomConstructionChange, +} from '../../store/use-delete-confirmation' import { Dialog, DialogContent, @@ -11,10 +21,268 @@ import { DialogTitle, } from '../ui/primitives/dialog' +const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}` + +function sentenceList(parts: string[]) { + if (parts.length <= 1) return parts.join('') + return `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}` +} + +/** + * A mezzanine takes its own plate (with its railing) and the ceiling core + * derived over it; kept items come down to the floor below. + */ +function mezzanineDeletionDescription(room: DeleteZonePayload, nodes: StructureNodes) { + const hasCeiling = Object.values(nodes).some( + (node) => node.type === 'ceiling' && node.zoneId === room.zoneId, + ) + const sentences = [ + hasCeiling + ? 'Removes the mezzanine floor, its railing and the ceiling over it.' + : 'Removes the mezzanine floor and its railing.', + ] + const items = room.itemIds.length + if (items) + sentences.push( + `${count(items, 'item')} ${items === 1 ? 'is' : 'are'} on it. Keep ${items === 1 ? 'it' : 'them'} on the floor below, or delete ${items === 1 ? 'it' : 'them'} too.`, + ) + return sentences.join(' ') +} + +/** + * An area Divide made goes back into the room across its dividing line: the + * line and the area's own finish go, the walls and anything standing in it stay. + */ +function mergeDescription(room: DeleteZonePayload, nodes: StructureNodes) { + const into = nodes[room.mergedIntoZoneId ?? '']?.name?.trim() + const lines = room.separatorIds.length === 1 ? 'dividing line' : 'dividing lines' + const sentences = [ + `Merges it back into ${into || 'the room next to it'}: removes the ${lines} and its floor finish. The walls stay.`, + ] + const items = room.itemIds.length + if (items) + sentences.push( + `${count(items, 'item')} inside ${items === 1 ? 'stays where it is' : 'stay where they are'}.`, + ) + return sentences.join(' ') +} + +function roomDeletionDescription(room: DeleteZonePayload, nodes: StructureNodes) { + if (isMezzanine(room, nodes)) return mezzanineDeletionDescription(room, nodes) + if (room.mode === 'merge') return mergeDescription(room, nodes) + const sentences: string[] = [] + const typeCount = (type: string) => + room.openingIds.filter((id) => nodes[id]?.type === type).length + const removed = [ + room.wallIds.length ? count(room.wallIds.length, 'wall') : '', + room.separatorIds.length ? count(room.separatorIds.length, 'separator') : '', + typeCount('door') ? count(typeCount('door'), 'door') : '', + typeCount('window') ? count(typeCount('window'), 'window') : '', + ].filter(Boolean) + sentences.push( + removed.length + ? `Removes ${sentenceList(removed)}, with the floor finish and ceiling.` + : 'Removes the floor finish and ceiling.', + ) + if (room.keptSharedWallIds.length + room.keptSharedSeparatorIds.length > 0) + sentences.push('Walls shared with other rooms stay.') + if (room.opensZoneIds.length) { + const names = room.opensZoneIds.map((id) => nodes[id]?.name?.trim() || 'the next room') + sentences.push(`Opens into ${sentenceList(names)}.`) + } + const items = room.itemIds.length + if (items) + sentences.push( + `${count(items, 'item')} ${items === 1 ? 'is' : 'are'} inside. Keep ${items === 1 ? 'it' : 'them'} where ${items === 1 ? 'it is' : 'they are'}, or delete ${items === 1 ? 'it' : 'them'} too.`, + ) + return sentences.join(' ') +} + +/** A hosted node's kind from its type and structure — never from its name. */ +function hostedKind(node: AnyNode | undefined) { + if (node?.type === 'door' || node?.type === 'window') return node.type + if (node?.type === 'item' && node.asset.interactive?.effects.some((e) => e.kind === 'light')) + return 'light' + return 'item' +} + +function hostedName(node: AnyNode | undefined) { + return (node?.name || (node?.type === 'item' ? node.asset.name : '') || '').trim() +} + +function shownNames(names: string[]) { + const named = [...new Set(names.filter(Boolean))] + return named.slice(0, 3).join(', ') + (named.length > 3 ? ', …' : '') +} + +/** "1 door (Front door), 2 windows and 1 light": counts per kind, a few names, no ids. */ +export function hostedSummary(ids: readonly string[], nodes: StructureNodes) { + const groups = new Map() + for (const id of ids) { + const kind = hostedKind(nodes[id]) + groups.set(kind, [...(groups.get(kind) ?? []), hostedName(nodes[id])]) + } + return sentenceList( + [...groups].map(([kind, names]) => { + const shown = shownNames(names) + return `${count(names.length, kind)}${shown ? ` (${shown})` : ''}` + }), + ) +} + +const pronouns = (one: boolean) => + one + ? { it: 'it', is: 'is', its: 'its', verb: (v: string) => `${v}s` } + : { it: 'them', is: 'are', its: 'their', verb: (v: string) => v } + +function ceilingContent( + change: RoomConstructionChange, + nodes: StructureNodes, + room: string, + canKeep: boolean, +): DeleteConfirmationContent { + const ids = change.hostedIds + const p = pronouns(ids.length === 1) + const manual = change.manualCeilings ?? [] + const sentences: string[] = [] + if (manual.length) { + const names = shownNames(manual) + sentences.push( + manual.length === 1 + ? `Removes the hand-drawn ceiling${names ? ` (${names})` : ''}.` + : `Removes ${manual.length} hand-drawn ceilings${names ? ` (${names})` : ''}.`, + ) + if (change.alsoCovers?.length) + sentences.push( + `${manual.length === 1 ? 'It also covers' : 'They also cover'} ${sentenceList(change.alsoCovers)}.`, + ) + } + // Lights are known from their light effect; anything else reads as an item. + const lights = ids.length > 0 && ids.every((id) => hostedKind(nodes[id]) === 'light') + if (ids.length) { + const names = shownNames(ids.map((id) => hostedName(nodes[id]))) + sentences.push( + lights + ? `${hostedSummary(ids, nodes)} ${p.verb('hang')} from it.` + : `${count(ids.length, 'item')} ${p.is} on the ceiling${names ? ` (${names})` : ''}.`, + `Keep ${p.it} in place, or delete ${p.it} too.`, + ) + } + return { + title: `Remove the ceiling from ${room}?`, + description: sentences.length ? sentences.join(' ') : 'Removes the ceiling.', + keepLabel: ids.length && canKeep ? (lights ? 'Keep lights' : 'Keep items') : null, + confirmLabel: ids.length ? 'Remove all' : 'Remove', + destructive: true, + } +} + +function constructionContent( + change: RoomConstructionChange, + nodes: StructureNodes, + canKeep: boolean, +): DeleteConfirmationContent { + const room = change.roomName.trim() || 'this room' + const hosted = hostedSummary(change.hostedIds, nodes) + const p = pronouns(change.hostedIds.length === 1) + if (change.part === 'walls' && change.action === 'add') { + return { + title: `Add walls to ${room}?`, + description: `Adds ${count(change.wallCount ?? 0, 'wall')} · the room loses ${(change.areaLoss ?? 0).toFixed(2)} m² of floor.`, + keepLabel: null, + confirmLabel: 'Add walls', + destructive: false, + } + } + if (change.part === 'walls') { + const walls = count(change.wallCount ?? 0, 'wall') + return { + title: `Remove walls from ${room}?`, + description: [ + hosted + ? `Turns ${walls} into separators and removes ${hosted}.` + : `Turns ${walls} into separators.`, + change.sharedWalls ? 'Shared walls remain.' : '', + ] + .filter(Boolean) + .join(' '), + keepLabel: null, + confirmLabel: 'Remove walls', + destructive: true, + } + } + if (change.part === 'floor') { + return { + title: `Remove the floor from ${room}?`, + description: hosted + ? `${hosted} ${p.verb('stand')} on it. Keep ${p.it} at ${p.its} height, or delete ${p.it} too.` + : 'Removes the floor.', + keepLabel: hosted && canKeep ? 'Keep items' : null, + confirmLabel: hosted ? 'Delete items' : 'Remove', + destructive: true, + } + } + return ceilingContent(change, nodes, room, canKeep) +} + +export type DeleteConfirmationContent = { + title: string + description: string + /** Delete the room but leave its items in place — offered only when it has items. */ + keepLabel: string | null + confirmLabel: string + /** Red confirm for removals; adding walls confirms in the neutral style. */ + destructive: boolean +} + +/** The words and choices the confirmation offers, from the request alone. */ +function isMezzanine(room: DeleteZonePayload, nodes: StructureNodes) { + const zone = nodes[room.zoneId] + return zone?.type === 'zone' && zone.floor?.support === 'open' +} + +export function deleteConfirmationContent( + request: DeleteConfirmationRequest, + nodes: StructureNodes, +): DeleteConfirmationContent { + if (request.construction) + return constructionContent(request.construction, nodes, !!request.onKeepContents) + const room = request.room + if (!room) + return { + title: `Delete ${count(request.count, 'element')}?`, + description: + 'This removes every selected element. You can undo the deletion while it remains in the editor history.', + keepLabel: null, + confirmLabel: 'Delete', + destructive: true, + } + const merge = room.mode === 'merge' + // A merged area's items always stay, so there is nothing to choose. + const hasItems = room.itemIds.length > 0 && !merge + return { + title: `Delete ${room.name.trim() || (isMezzanine(room, nodes) ? 'this mezzanine' : merge ? 'this area' : 'this room')}?`, + description: roomDeletionDescription(room, nodes), + keepLabel: hasItems && request.onKeepContents ? 'Keep items' : null, + confirmLabel: hasItems ? 'Delete all' : 'Delete', + destructive: true, + } +} + export function DeleteConfirmationDialog() { const request = useDeleteConfirmation((state) => state.request) const cancel = useDeleteConfirmation((state) => state.cancel) const confirm = useDeleteConfirmation((state) => state.confirm) + const nodes = useScene((state) => (request ? state.nodes : null)) + const live = useMemo( + () => (request && nodes ? deleteConfirmationContent(request, nodes) : null), + [request, nodes], + ) + // Hold the last words through the close animation so the dialog never empties. + const shown = useRef(live) + if (live) shown.current = live + const content = shown.current + const blocked = !!request?.conflict useEffect(() => cancel, [cancel]) @@ -26,10 +294,12 @@ export function DeleteConfirmationDialog() { showCloseButton={false} > - Delete {request?.count ?? 0} elements? + {content?.title} - This removes every selected element. You can undo the deletion while it remains in the - editor history. + {content?.description} + {request?.conflict && ( + {request.conflict} + )} @@ -40,12 +310,32 @@ export function DeleteConfirmationDialog() { > Cancel + {content?.keepLabel && ( + + )} diff --git a/packages/editor/src/components/editor/editor-layout-v2.tsx b/packages/editor/src/components/editor/editor-layout-v2.tsx index c2d85c052e..58b844798f 100644 --- a/packages/editor/src/components/editor/editor-layout-v2.tsx +++ b/packages/editor/src/components/editor/editor-layout-v2.tsx @@ -2,13 +2,13 @@ import { type ReactNode, useCallback, useEffect, useRef } from 'react' import { useIsMobile } from '../../hooks/use-mobile' +import { SIDEBAR_MIN_WIDTH, setSidebarTabIds } from '../../lib/sidebar-panel' import useEditor from '../../store/use-editor' import { useSidebarStore } from '../ui/primitives/sidebar' import { IconRail, type SidebarTab } from '../ui/sidebar/tab-bar' import { EditorLayoutMobile } from './editor-layout-mobile' -const SIDEBAR_MIN_WIDTH = 300 const SIDEBAR_MAX_WIDTH = 800 const SIDEBAR_COLLAPSE_THRESHOLD = 220 // Matches the `w-14` rail in ; the resize math is relative to it. @@ -36,6 +36,12 @@ function LeftColumn({ const isResizing = useRef(false) + // Publish the rail's tabs so keyboard shortcuts (B, P) can open a panel. + useEffect(() => { + setSidebarTabIds(tabs.map((tab) => tab.id)) + return () => setSidebarTabIds([]) + }, [tabs]) + // Ensure active panel is a valid tab useEffect(() => { if (tabs.length > 0 && !tabs.some((t) => t.id === activePanel)) { diff --git a/packages/editor/src/components/editor/floating-action-menu.tsx b/packages/editor/src/components/editor/floating-action-menu.tsx index 04e6d882bf..d6e5ebd668 100644 --- a/packages/editor/src/components/editor/floating-action-menu.tsx +++ b/packages/editor/src/components/editor/floating-action-menu.tsx @@ -18,6 +18,7 @@ import { getWallThickness, ItemNode, isCurvedWall, + isDerivedNode, isRegistryMovable, isRegistrySelectable, isSplineFence, @@ -56,6 +57,8 @@ import { duplicateWithoutMove, registryMoveDisabled } from '../../lib/node-actio import { playBlockedQuickActionFeedback } from '../../lib/quick-action-feedback' import { collectQuickActionNodeScope } from '../../lib/quick-action-nodes' import { duplicateRoofSubtree } from '../../lib/roof-duplication' +import { deleteSelectedSeparator } from '../../lib/room-structure-commands' +import { captureElementActionOrigin, completeElementAction } from '../../lib/room-zone-routing' import { emitDeleteSFX, sfxEmitter } from '../../lib/sfx-bus' import { cn } from '../../lib/utils' import useEditor from '../../store/use-editor' @@ -67,6 +70,7 @@ import useInteractionScope, { import { IconRefGlyph } from '../ui/icon-ref' import { formatMeasurement, MeasurementPill } from './measurement-pill' import { NodeActionMenu } from './node-action-menu' +import { startZoneRoomTransform } from './room-controls' /** * A kind shows the system pill when it exposes typed ports — `def.ports` @@ -127,6 +131,8 @@ const MENU_Y_OFFSETS: Record = { // Slab: clears the height arrow that sits at elevation + 0.22 plus the // chevron's own visual reach, so the menu floats just above it. slab: 0.7, + // Room: measured from the top of its walls, with a wall's clearance. + zone: 0.5, // Ceiling: clears the upward height arrow that sits ~0.22 above the // ceiling plane, plus extra headroom so the menu doesn't crowd the // chevron at any zoom level. @@ -136,7 +142,7 @@ const MENU_Y_OFFSETS: Record = { shelf: 0.6, } -function getMenuYOffset(node: AnyNode | null): number { +export function getMenuYOffset(node: AnyNode | null): number { if (!node) return MENU_Y_OFFSET_DEFAULT + EXTRA_MENU_LIFT if (node.type === 'stair-segment') { return (MENU_Y_OFFSETS[`stair-${node.segmentType}`] ?? MENU_Y_OFFSET_DEFAULT) + EXTRA_MENU_LIFT @@ -490,6 +496,7 @@ export function FloatingActionMenu() { (e: React.MouseEvent) => { e.stopPropagation() if (!node) return + if (startZoneRoomTransform(node, 'move')) return sfxEmitter.emit('sfx:item-pick') const sceneNodes = useScene.getState().nodes setMovingNode(resolveMoveActionNode(node, sceneNodes) as any) @@ -501,6 +508,7 @@ export function FloatingActionMenu() { (e: React.MouseEvent) => { e.stopPropagation() if (!node?.parentId) return + if (startZoneRoomTransform(node, 'duplicate')) return sfxEmitter.emit('sfx:item-pick') if (registryMoveDisabled(node)) { @@ -730,9 +738,15 @@ export function FloatingActionMenu() { (e: React.MouseEvent) => { e.stopPropagation() if (!selectedId) return + const origin = captureElementActionOrigin([selectedId]) + if (node?.type === 'separator') { + deleteSelectedSeparator(selectedId as AnyNodeId, origin) + return + } emitDeleteSFX(node?.type) setSelection({ selectedIds: [] }) useScene.getState().deleteNode(selectedId as AnyNodeId) + completeElementAction(origin) }, [node?.type, selectedId, setSelection], ) @@ -771,6 +785,8 @@ export function FloatingActionMenu() { if ( !(selectedId && node && isValidType && !isFloorplanHovered && mode !== 'delete') || + // A footprint's floor has one control, its height handle; no pill. + (node.type === 'slab' && node.plateRole === 'base') || endpointReshape || isCurveReshape || !menuVisibility.root @@ -802,7 +818,11 @@ export function FloatingActionMenu() { ? handleFind : undefined } - onAddHole={node && HOLE_TYPES.includes(node.type) ? handleAddHole : undefined} + onAddHole={ + node && HOLE_TYPES.includes(node.type) && !isDerivedNode(node) + ? handleAddHole + : undefined + } onCurve={ (node?.type === 'fence' && !isSplineFence(node) && !isCurvedWall(node)) || (node?.type === 'wall' && canCurveSelectedWall) diff --git a/packages/editor/src/components/editor/floor-openings-overlay.tsx b/packages/editor/src/components/editor/floor-openings-overlay.tsx new file mode 100644 index 0000000000..1dfd57d98b --- /dev/null +++ b/packages/editor/src/components/editor/floor-openings-overlay.tsx @@ -0,0 +1,243 @@ +'use client' + +import { + type AnyNode, + type AnyNodeId, + type FloorOpeningNode, + resolveCeilingHeight, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { useViewer } from '@pascal-app/viewer' +import { type ThreeEvent, useFrame } from '@react-three/fiber' +import { useEffect, useMemo, useRef } from 'react' +import { + BufferGeometry, + DoubleSide, + Float32BufferAttribute, + type Group, + ShapeUtils, + Vector2, +} from 'three' +import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' +import { useCeilingEditSession } from '../../lib/ceiling-edit-session' +import { EDITOR_LAYER } from '../../lib/constants' +import { openingRoom, roomSurfaceOpenings, useFloorEditSession } from '../../lib/floor-edit-session' +import { useOpeningDraft } from '../../lib/floor-opening-draft' +import { roomFloorElevation } from '../../lib/room-handle-drag' +import { PolygonEditor } from '../tools/shared/polygon-editor' + +// The openings of the room being edited ("Edit floor", "Edit ceiling", or a +// "Cut opening" in progress), outlined where they cut: amber, a light fill to +// click them by, and the selected one's corner handles. Openings are intent +// nodes with no mesh of their own — the surfaces they cut show the void. + +const COLOR = '#f59e0b' +const LIFT = 0.015 + +type Nodes = Readonly> + +/** Where an opening is drawn: its room's floor, or the ceiling it was drawn on. */ +export function openingElevation(nodes: Nodes, opening: FloorOpeningNode): number { + if (opening.hostZoneId) return roomFloorElevation(nodes, opening.hostZoneId) + const zoneId = openingRoom(nodes, opening) + if (opening.drawnOn === 'ceiling') { + const ceiling = Object.values(nodes).find( + (node) => + node.type === 'ceiling' && node.parentId === opening.parentId && node.zoneId === zoneId, + ) + return ceiling?.type === 'ceiling' + ? resolveCeilingHeight(ceiling, nodes as Record) + : 2.5 + } + return zoneId ? roomFloorElevation(nodes, zoneId) : 0.05 +} + +function useShownOpenings(): { levelId: string | null; openings: FloorOpeningNode[] } { + const nodes = useScene((s) => s.nodes) + const floorSession = useFloorEditSession((s) => s.session) + const ceilingSession = useCeilingEditSession((s) => s.session) + const draftHost = useOpeningDraft((s) => s.host) + const selectedId = useViewer((s) => + s.selection.selectedIds.length === 1 ? s.selection.selectedIds[0] : null, + ) + return useMemo(() => { + const shown = new Map() + const add = (list: FloorOpeningNode[]) => { + for (const opening of list) shown.set(opening.id, opening) + } + let levelId: string | null = null + if (floorSession) { + add(roomSurfaceOpenings(nodes, floorSession.zoneId, 'floor')) + levelId = floorSession.levelId + } + if (ceilingSession?.zoneId) { + add(roomSurfaceOpenings(nodes, ceilingSession.zoneId, 'ceiling')) + levelId = ceilingSession.levelId + } + if (draftHost) { + add(roomSurfaceOpenings(nodes, draftHost.zoneId, draftHost.drawnOn)) + levelId = draftHost.levelId + } + const selected = selectedId ? nodes[selectedId as AnyNodeId] : undefined + if (selected?.type === 'floor-opening') { + shown.set(selected.id, selected) + levelId = selected.parentId + } + return { + levelId, + openings: [...shown.values()].filter((opening) => opening.parentId === levelId), + } + }, [nodes, floorSession, ceilingSession, draftHost, selectedId]) +} + +function outlineGeometry(polygon: FloorOpeningNode['polygon'], y: number) { + const positions: number[] = [] + polygon.forEach((a, i) => { + const b = polygon[(i + 1) % polygon.length]! + positions.push(a[0], y, a[1], b[0], y, b[1]) + }) + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + return geometry +} + +function fillGeometry(polygon: FloorOpeningNode['polygon'], y: number) { + const contour = polygon.map(([x, z]) => new Vector2(x, z)) + const positions: number[] = [] + for (const triangle of ShapeUtils.triangulateShape(contour, [])) + for (const index of triangle) positions.push(contour[index]!.x, y, contour[index]!.y) + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + return geometry +} + +function OpeningOutline({ + opening, + elevation, + selected, + materials, +}: { + opening: FloorOpeningNode + elevation: number + selected: boolean + materials: { + line: LineBasicNodeMaterial + fill: MeshBasicNodeMaterial + fillSelected: MeshBasicNodeMaterial + } +}) { + const geometry = useMemo( + () => ({ + line: outlineGeometry(opening.polygon, elevation + LIFT), + fill: fillGeometry(opening.polygon, elevation + LIFT), + }), + [opening.polygon, elevation], + ) + useEffect( + () => () => { + geometry.line.dispose() + geometry.fill.dispose() + }, + [geometry], + ) + const select = (event: ThreeEvent) => { + event.stopPropagation() + useViewer.getState().setSelection({ selectedIds: [opening.id] }) + } + return ( + + {}} + renderOrder={1001} + /> + + + ) +} + +export function FloorOpeningsOverlay3D() { + const { levelId, openings } = useShownOpenings() + const nodes = useScene((s) => s.nodes) + const readOnly = useScene((s) => s.readOnly) + const selectedId = useViewer((s) => + s.selection.selectedIds.length === 1 ? s.selection.selectedIds[0] : null, + ) + const root = useRef(null) + const materials = useMemo( + () => ({ + line: new LineBasicNodeMaterial({ color: COLOR, depthTest: false, depthWrite: false }), + fill: new MeshBasicNodeMaterial({ + color: COLOR, + depthTest: false, + depthWrite: false, + opacity: 0.12, + side: DoubleSide, + transparent: true, + }), + fillSelected: new MeshBasicNodeMaterial({ + color: COLOR, + depthTest: false, + depthWrite: false, + opacity: 0.28, + side: DoubleSide, + transparent: true, + }), + }), + [], + ) + useEffect( + () => () => { + materials.line.dispose() + materials.fill.dispose() + materials.fillSelected.dispose() + }, + [materials], + ) + useFrame(() => { + const level = levelId ? sceneRegistry.nodes.get(levelId) : null + if (!root.current) return + root.current.visible = !!level + if (level) { + level.updateWorldMatrix(true, false) + root.current.matrix.copy(level.matrixWorld) + } + }) + if (!levelId || openings.length === 0) return null + const selected = openings.find((opening) => opening.id === selectedId) ?? null + return ( + <> + + {openings.map((opening) => ( + + ))} + + {selected && !readOnly && selected.source !== 'stair' && selected.source !== 'elevator' && ( + useScene.getState().updateNode(selected.id, { polygon })} + polygon={selected.polygon} + surfaceHeight={openingElevation(nodes, selected)} + /> + )} + + ) +} diff --git a/packages/editor/src/components/editor/floor-region-controls.tsx b/packages/editor/src/components/editor/floor-region-controls.tsx new file mode 100644 index 0000000000..51ef606c3f --- /dev/null +++ b/packages/editor/src/components/editor/floor-region-controls.tsx @@ -0,0 +1,846 @@ +'use client' + +import { + containsPoint, + emitter, + type MultiPolygon, + resolveCeilingHeight, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { getSceneTheme, setSurfaceRaycastLayers, useViewer } from '@pascal-app/viewer' +import { useFrame, useThree } from '@react-three/fiber' +import { Pentagon, Square } from 'lucide-react' +import { useEffect, useMemo, useRef } from 'react' +import { + BufferGeometry, + type Camera, + DoubleSide, + Float32BufferAttribute, + type Group, + Matrix4, + type Object3D, + type OrthographicCamera, + type PerspectiveCamera, + Plane, + Raycaster, + ShapeUtils, + Vector2, + Vector3, +} from 'three' +import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' +import { markToolCancelConsumed } from '../../hooks/use-keyboard' +import { getRoomSelectionIndex } from '../../hooks/use-selected-room' +import { EDITOR_LAYER } from '../../lib/constants' +import { + cancelOpeningDraft, + openingDraftActive, + useOpeningDraft, +} from '../../lib/floor-opening-draft' +import { clipFloorRegion, floorRegionRoomAt } from '../../lib/floor-region-geometry' +import { + cancelFloorRegion, + currentFloorRegionSnap, + describeCeilingRegionRoom, + describeFloorRegionRoom, + dropFloorRegionDraft, + type FloorRegionDraft, + type FloorRegionRoom, + finishFloorRegion, + floorRegionDraftMessage, + floorRegionDraftOutline, + floorRegionEditable, + floorRegionGesture, + moveFloorRegion, + pressFloorRegion, + releaseFloorRegion, + removeLastFloorRegionPoint, + setFloorRegionHover, + useFloorRegionDraft, +} from '../../lib/floor-region-session' +import { type FloorRegionPoint, snapFloorRegionPoint } from '../../lib/floor-region-snap' +import { clientToPlan } from '../../lib/floorplan/plan-coords' +import { formatAreaLabel } from '../../lib/measurements' +import { + cancelMezzanineDraft, + mezzanineDraftActive, + useMezzanineDraft, +} from '../../lib/mezzanine-draft' +import { usePaintRegionMode } from '../../lib/paint-region-mode' +import { roomFloorElevation } from '../../lib/room-handle-drag' +import { + cancelTerraceDraft, + terraceDraftActive, + toggleTerraceShape, + useTerraceDraft, +} from '../../lib/terrace-draft' +import { isTypingTarget } from '../../lib/typing-target' +import useEditor from '../../store/use-editor' +import { useFloorplanRender } from '../editor-2d/floorplan-render-context' +import { usePaintTint } from '../tools/paint-region/use-paint-tint' +import { CursorSphere } from '../tools/shared/cursor-sphere' +import { + DRAFT_LABEL_Y_OFFSET, + DraftMeasurementLabel, +} from '../tools/shared/draft-measurement-label' +import { swallowNextClick } from './handles/use-handle-drag' +import { RoomFloorHighlight3D } from './room-floor-highlight' + +// An outline on a room's floor, in 3D and on the plan: the paint tool's +// rectangle and polygon sub-modes ("Paint part of the floor"), and the armed +// "Add mezzanine" tool, which draws in its host room on the mezzanine's plane. +// The session (`floor-region-session`) owns the draft; this file turns +// pointers into plan points on a room's floor and draws the draft in the wall +// draft's colours. + +const DRAFT_COLOR = '#818cf8' +const DRAFT_COLOR_LIGHT_PLAN = '#6366f1' +const INVALID_COLOR = '#ef4444' +/** How close (screen pixels) a click lands to the first point to close the polygon, in 3D and on the plan. */ +const CLOSE_RADIUS_PX = 10 +/** The 3D close radius (m) when the camera cannot say how big a pixel is. */ +const CLOSE_RADIUS_3D_FALLBACK = 0.2 +const PREVIEW_LIFT = 0.012 + +type FloorRegionMode = 'rectangle' | 'polygon' +type FloorRegionHit = { room: FloorRegionRoom; point: FloorRegionPoint } + +function activeMode(): FloorRegionMode | null { + if (!floorRegionEditable()) return null + const opening = useOpeningDraft.getState() + if (opening.host) return opening.shape + const mezzanine = useMezzanineDraft.getState() + if (mezzanine.host) return mezzanine.shape + const terrace = useTerraceDraft.getState() + if (terrace.host) return terrace.shape + if (useEditor.getState().mode !== 'material-paint') return null + const mode = usePaintRegionMode.getState().mode + return mode === 'rectangle' || mode === 'polygon' ? mode : null +} + +function useFloorRegionMode(): FloorRegionMode | null { + const editorMode = useEditor((s) => s.mode) + const regionMode = usePaintRegionMode((s) => s.mode) + const mezzanine = useMezzanineDraft((s) => (s.host ? s.shape : null)) + const terrace = useTerraceDraft((s) => (s.host ? s.shape : null)) + const opening = useOpeningDraft((s) => (s.host ? s.shape : null)) + const readOnly = useScene((s) => s.readOnly) + if (readOnly) return null + if (opening) return opening + if (mezzanine) return mezzanine + if (terrace) return terrace + if (editorMode !== 'material-paint') return null + return regionMode === 'rectangle' || regionMode === 'polygon' ? regionMode : null +} + +function useSceneIsDark() { + return useViewer((s) => getSceneTheme(s.sceneTheme).appearance === 'dark') +} + +// The mezzanine tool owns Escape, Backspace, Enter (and the terrace tool T) while +// armed, draft or not, so none of them reaches the selected room (Backspace +// would delete it). +function floorRegionKey(event: KeyboardEvent) { + const draft = useFloorRegionDraft.getState().draft + const terrace = terraceDraftActive() + const opening = openingDraftActive() + const mezzanine = mezzanineDraftActive() || terrace || opening + if (!(draft || mezzanine) || event.defaultPrevented || isTypingTarget(event.target)) return + if (event.key === 'Escape') { + if (opening) cancelOpeningDraft() + else if (terrace) cancelTerraceDraft() + else if (mezzanine) cancelMezzanineDraft() + else cancelFloorRegion() + } else if (event.key === 'Backspace') { + if (!(removeLastFloorRegionPoint() || mezzanine)) return + } else if (event.key === 'Enter') { + if (!(finishFloorRegion() || mezzanine)) return + } else if ( + terrace && + (event.key === 't' || event.key === 'T') && + !(event.metaKey || event.ctrlKey || event.altKey) + ) + toggleTerraceShape() + else return + event.preventDefault() + event.stopPropagation() +} + +// One keyboard listener per target however many surfaces bind to it (split +// view mounts the plan and the 3D controller together). +const keyboardOwners = new WeakMap() +function acquireKeyboard(target: EventTarget) { + const owners = keyboardOwners.get(target) ?? 0 + if (owners === 0) target.addEventListener('keydown', floorRegionKey as EventListener, true) + keyboardOwners.set(target, owners + 1) + let released = false + return () => { + if (released) return + released = true + const left = (keyboardOwners.get(target) ?? 1) - 1 + keyboardOwners.set(target, left) + if (left === 0) target.removeEventListener('keydown', floorRegionKey as EventListener, true) + } +} + +/** + * Binds a surface to the floor region draft. `resolve` answers where the + * pointer is on a room floor: while a draft is open, on that draft's floor; + * otherwise the room under the pointer, or null when the floor is not what + * the pointer is on (another agent's surface keeps the event). + */ +export function bindFloorRegionPointer( + surface: EventTarget, + resolve: (event: PointerEvent) => FloorRegionHit | null, + closeRadius: () => number, + keyboard: EventTarget = window, +) { + let pressed: number | null = null + const capture = surface as Element + // Moves are coalesced to one update per animation frame; a press drops the + // pending move and acts on its own position at once. + let frame = 0 + let pending: PointerEvent | null = null + const flush = () => { + frame = 0 + const event = pending + pending = null + if (!(event && activeMode())) return + const hit = resolve(event) + const settings = currentFloorRegionSnap(event.altKey) + const draft = useFloorRegionDraft.getState().draft + // A refused box stays put until the next press; the marker shows meanwhile. + if (draft && !(draft.kind === 'rectangle' && draft.refusal)) { + setFloorRegionHover(null) + if (hit) moveFloorRegion(hit.point, settings, closeRadius()) + return + } + setFloorRegionHover( + hit + ? { + levelId: hit.room.levelId, + elevation: hit.room.elevation, + point: snapFloorRegionPoint(hit.point, settings, hit.room.targets).point, + ...(hit.room.ceilingId ? { ceiling: true } : {}), + } + : null, + ) + } + const dropPending = () => { + if (frame) cancelAnimationFrame(frame) + frame = 0 + pending = null + } + const move = (event: PointerEvent) => { + if (!activeMode()) return + pending = event + if (!frame) frame = requestAnimationFrame(flush) || 0 + } + const down = (event: PointerEvent) => { + const mode = activeMode() + if (event.button !== 0 || !mode || useViewer.getState().cameraDragging) return + const hit = resolve(event) + if (!hit) return + dropPending() + event.preventDefault() + event.stopPropagation() + setFloorRegionHover(null) + pressFloorRegion(mode, hit.room, hit.point, currentFloorRegionSnap(event.altKey), closeRadius()) + pressed = event.pointerId + // A box dragged off the surface keeps following the pointer. The capture is + // the gesture owner's: released on release, cancel or any lifecycle end. + if ('setPointerCapture' in capture) + floorRegionGesture()?.capturePointer(capture, event.pointerId) + } + const up = (event: PointerEvent) => { + if (pressed !== event.pointerId) return + pressed = null + floorRegionGesture()?.releasePointer(event.pointerId) + // The last move lands before the release, so the box ends where the pointer let go. + if (frame) cancelAnimationFrame(frame) + flush() + event.preventDefault() + event.stopPropagation() + // The click the browser synthesizes from this release belongs to the draft: + // it must not deselect what the commit just selected. + swallowNextClick() + useViewer.getState().setInputDragging(true) + releaseFloorRegion(closeRadius()) + setTimeout(() => useViewer.getState().setInputDragging(false), 0) + } + // The system took the pointer (a touch turned into a scroll, a lost window): + // a box ends uncommitted; a polygon keeps its placed points. + const cancel = (event: PointerEvent) => { + if (pressed !== event.pointerId) return + pressed = null + dropPending() + floorRegionGesture()?.releasePointer(event.pointerId) + if (useFloorRegionDraft.getState().draft?.kind === 'rectangle') dropFloorRegionDraft() + } + const leave = () => { + const draft = useFloorRegionDraft.getState().draft + if (!draft || (draft.kind === 'rectangle' && draft.refusal)) setFloorRegionHover(null) + } + const onMove = (event: Event) => move(event as PointerEvent) + const onDown = (event: Event) => down(event as PointerEvent) + surface.addEventListener('pointermove', onMove, true) + surface.addEventListener('pointerdown', onDown, true) + surface.addEventListener('pointerleave', leave) + keyboard.addEventListener('pointerup', up as EventListener, true) + keyboard.addEventListener('pointercancel', cancel as EventListener, true) + const releaseKeyboard = acquireKeyboard(keyboard) + return () => { + dropPending() + if (pressed !== null) floorRegionGesture()?.releasePointer(pressed) + surface.removeEventListener('pointermove', onMove, true) + surface.removeEventListener('pointerdown', onDown, true) + surface.removeEventListener('pointerleave', leave) + keyboard.removeEventListener('pointerup', up as EventListener, true) + keyboard.removeEventListener('pointercancel', cancel as EventListener, true) + releaseKeyboard() + } +} + +/** + * The draft's own lifetime lives with the gesture lifecycle owner (sub-mode, + * mode, level or selection change, its room gone, its scope replaced, any + * history command). Here: Escape (`tool:cancel`, consumed so the paint mode + * stays), the hover marker on a level switch, and the surface unmounting. + */ +function useFloorRegionLifetime(mode: FloorRegionMode | null) { + useEffect(() => { + if (!mode) setFloorRegionHover(null) + }, [mode]) + useEffect(() => { + const stopViewer = useViewer.subscribe((state, previous) => { + if (state.selection.levelId !== previous.selection.levelId) setFloorRegionHover(null) + }) + const onToolCancel = () => { + if (terraceDraftActive()) cancelTerraceDraft() + else if (mezzanineDraftActive()) cancelMezzanineDraft() + else if (useFloorRegionDraft.getState().draft) cancelFloorRegion() + else return + markToolCancelConsumed() + } + emitter.on('tool:cancel', onToolCancel) + editingSurfaces++ + return () => { + stopViewer() + emitter.off('tool:cancel', onToolCancel) + cancelFloorRegion() + setFloorRegionHover(null) + editingSurfaces-- + // Before its first press the mezzanine tool owns no draft, only its armed + // state and scope; the last surface going away (capture mode, the editor + // closing) must not leave them behind. + if (editingSurfaces === 0 && mezzanineDraftActive()) cancelMezzanineDraft() + if (editingSurfaces === 0 && terraceDraftActive()) cancelTerraceDraft() + } + }, []) +} + +/** The mounted 3D / 2D drawing surfaces; the mezzanine tool lives only while one is. */ +let editingSurfaces = 0 + +/** The room whose clear floor holds `point` on `levelId`, as a draft room. */ +export function resolveFloorRegionRoom(levelId: string, point: FloorRegionPoint) { + const nodes = useScene.getState().nodes + const record = floorRegionRoomAt(getRoomSelectionIndex(levelId).update(nodes), point, (room) => + roomFloorElevation(nodes, room.zoneId), + ) + return record ? describeFloorRegionRoom(nodes, record) : null +} + +// A cutaway hides walls without unregistering them, and an invisible wall must +// not answer a ray the user aimed at the floor behind it. +function visibleSurface(object: Object3D) { + for (let node: Object3D | null = object; node; node = node.parent) + if (!node.visible || node.userData.wallHidden === true) return false + return true +} + +/** Distance (level space) from `origin` to the nearest visible wall of the level along the ray. */ +function nearestWallDistance( + raycaster: Raycaster, + level: Object3D, + levelId: string, + origin: Vector3, +) { + const nodes = useScene.getState().nodes + let nearest = Number.POSITIVE_INFINITY + for (const id of sceneRegistry.byType.wall ?? []) { + if (nodes[id as keyof typeof nodes]?.parentId !== levelId) continue + const object = sceneRegistry.nodes.get(id) + const hit = object + ? raycaster + .intersectObject(object, true) + .find((candidate) => visibleSurface(candidate.object)) + : undefined + if (!hit) continue + nearest = Math.min(nearest, origin.distanceTo(level.worldToLocal(hit.point.clone()))) + } + return nearest +} + +const UP = new Vector3(0, 1, 0) + +/** + * The 3D pointer on a room floor. With a draft open (or the mezzanine tool + * armed), the ray meets that room's plane whatever stands in front of it. + * Otherwise it meets each room's floor plane (at its own elevation); the + * nearest landing inside a room's clear floor wins, unless a visible wall of + * the level is nearer along the ray — then the wall's paint gesture owns the + * press. + */ +function resolveFloorRegion3D( + event: PointerEvent, + element: HTMLElement, + camera: Camera, +): FloorRegionHit | null { + const draft = useFloorRegionDraft.getState().draft + const fixed = + draft?.room ?? + useOpeningDraft.getState().host ?? + useMezzanineDraft.getState().host ?? + useTerraceDraft.getState().host + const levelId = fixed?.levelId ?? useViewer.getState().selection.levelId + const level = levelId ? sceneRegistry.nodes.get(levelId) : null + if (!(levelId && level)) return null + level.updateWorldMatrix(true, false) + const bounds = element.getBoundingClientRect() + const raycaster = new Raycaster() + raycaster.setFromCamera( + new Vector2( + ((event.clientX - bounds.left) / bounds.width) * 2 - 1, + 1 - ((event.clientY - bounds.top) / bounds.height) * 2, + ), + camera, + ) + setSurfaceRaycastLayers(raycaster.layers) + const ray = raycaster.ray.clone().applyMatrix4(new Matrix4().copy(level.matrixWorld).invert()) + const onFloor = (elevation: number) => + ray.intersectPlane(new Plane(UP, -elevation), new Vector3()) + if (fixed) { + const hit = onFloor(fixed.elevation) + return hit ? { room: fixed, point: [hit.x, hit.z] } : null + } + const nodes = useScene.getState().nodes + let best: { + room: () => FloorRegionRoom + point: FloorRegionPoint + distance: number + } | null = null + for (const record of getRoomSelectionIndex(levelId).update(nodes)) { + const hit = onFloor(roomFloorElevation(nodes, record.zoneId)) + if (!hit) continue + const point: FloorRegionPoint = [hit.x, hit.z] + if (!containsPoint(record.clearPolygon, point)) continue + const distance = ray.origin.distanceTo(hit) + if (!best || distance < best.distance) + best = { room: () => describeFloorRegionRoom(nodes, record), point, distance } + } + // Painting also draws on a ceiling seen from below: its underside, where it draws. + if (useEditor.getState().mode === 'material-paint' && ray.direction.y > 1e-6) + for (const id of sceneRegistry.byType.ceiling ?? []) { + const ceiling = nodes[id as keyof typeof nodes] + if (ceiling?.type !== 'ceiling' || ceiling.parentId !== levelId) continue + const object = sceneRegistry.nodes.get(id) + if (!(object && visibleSurface(object))) continue + const hit = onFloor(resolveCeilingHeight(ceiling, nodes) - 0.01) + if (!hit) continue + const point: FloorRegionPoint = [hit.x, hit.z] + if (!containsPoint([{ outer: ceiling.polygon, holes: ceiling.holes }], point)) continue + const distance = ray.origin.distanceTo(hit) + if (!best || distance < best.distance) + best = { room: () => describeCeilingRegionRoom(nodes, ceiling), point, distance } + } + if (!best || nearestWallDistance(raycaster, level, levelId, ray.origin) < best.distance) + return null + return { room: best.room(), point: best.point } +} + +function ringPairs(ring: readonly FloorRegionPoint[], closed: boolean, y: number) { + const out: number[] = [] + const count = closed ? ring.length : ring.length - 1 + for (let i = 0; i < count; i++) { + const a = ring[i]! + const b = ring[(i + 1) % ring.length]! + out.push(a[0], y, a[1], b[0], y, b[1]) + } + return out +} + +function fillPositions(pieces: MultiPolygon, y: number) { + const out: number[] = [] + for (const { outer, holes } of pieces) { + const contour = outer.map(([x, z]) => new Vector2(x, z)) + const holeRings = holes.map((hole) => hole.map(([x, z]) => new Vector2(x, z))) + const all = [...contour, ...holeRings.flat()] + for (const triangle of ShapeUtils.triangulateShape(contour, holeRings)) + for (const index of triangle) out.push(all[index]!.x, y, all[index]!.y) + } + return out +} + +function geometryOf(positions: number[]) { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(positions, 3)) + return geometry +} + +const noRaycast = () => {} + +/** What the draft shows: its outline, the clipped pieces, the label and its colour. */ +function useDraftView(draft: FloorRegionDraft | null) { + const unit = useViewer((s) => s.unit) + return useMemo(() => { + if (!draft) return null + const outline = floorRegionDraftOutline(draft) + const clip = outline.length >= 3 ? clipFloorRegion(outline, draft.room.clear) : null + const message = floorRegionDraftMessage(draft) + const xs = outline.map((point) => point[0]) + const zs = outline.map((point) => point[1]) + const anchor: FloorRegionPoint | null = outline.length + ? [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...zs) + Math.max(...zs)) / 2] + : null + return { + outline, + closed: draft.kind === 'rectangle' || outline.length >= 3, + clip, + message, + label: message ?? (clip ? formatAreaLabel(clip.area, unit) : null), + anchor: message && draft.kind === 'polygon' ? (draft.cursor ?? anchor) : anchor, + points: draft.kind === 'polygon' ? draft.points : [], + cursor: draft.kind === 'polygon' ? draft.cursor : draft.end, + fill: draft.room.purpose?.fill ?? null, + } + }, [draft, unit]) +} + +function FloorRegionPreview3D({ mode }: { mode: FloorRegionMode }) { + const draft = useFloorRegionDraft((s) => s.draft) + const hover = useFloorRegionDraft((s) => s.hover) + const mezzanineHost = useMezzanineDraft((s) => s.host) + const openingHost = useOpeningDraft((s) => s.host) + const host = openingHost ?? mezzanineHost + const view = useDraftView(draft) + const isDark = useSceneIsDark() + const tint = usePaintTint(DRAFT_COLOR) + const color = view?.fill ?? tint + const levelId = draft?.room.levelId ?? hover?.levelId ?? host?.levelId ?? null + const elevation = draft?.room.elevation ?? hover?.elevation ?? host?.elevation ?? 0 + // A ceiling's outline hangs just under it, a floor's just over it. + const onCeiling = !!(draft?.room.ceilingId ?? hover?.ceiling) + const lift = elevation + (onCeiling ? -PREVIEW_LIFT : PREVIEW_LIFT) + const root = useRef(null) + const materials = useMemo( + () => ({ + fill: new MeshBasicNodeMaterial({ + depthTest: false, + depthWrite: false, + opacity: 0.3, + side: DoubleSide, + transparent: true, + }), + line: new LineBasicNodeMaterial({ depthTest: false, depthWrite: false }), + }), + [], + ) + useEffect( + () => () => { + materials.fill.dispose() + materials.line.dispose() + }, + [materials], + ) + const invalid = !!view?.message + useEffect(() => { + materials.fill.color.set(color) + materials.line.color.set(invalid ? INVALID_COLOR : DRAFT_COLOR) + }, [materials, color, invalid]) + const geometry = useMemo( + () => + view + ? { + fill: view.clip ? geometryOf(fillPositions(view.clip.pieces, lift)) : null, + line: geometryOf(ringPairs(view.outline, view.closed, lift)), + } + : null, + [view, lift], + ) + useEffect( + () => () => { + geometry?.fill?.dispose() + geometry?.line.dispose() + }, + [geometry], + ) + useFrame(() => { + const level = levelId ? sceneRegistry.nodes.get(levelId) : null + if (!root.current) return + root.current.visible = !!level + if (level) { + level.updateWorldMatrix(true, false) + root.current.matrix.copy(level.matrixWorld) + } + }) + if (!levelId) return null + const Icon = mode === 'polygon' ? Pentagon : Square + const cursor = view?.cursor ?? (draft ? null : (hover?.point ?? null)) + return ( + + {/* Where a mezzanine can go: the host's clear floor on the mezzanine's + plane, drawn over its walls like Divide's room, under the draft. */} + {host && ( + + )} + {geometry?.fill && ( + + )} + {geometry && ( + + )} + {view?.points.map((point, index) => ( + + ))} + {cursor && ( + } + /> + )} + {view?.label && view.anchor && ( + + )} + + ) +} + +/** + * The 3D close radius: CLOSE_RADIUS_PX at the polygon's first point's depth, + * so closing feels the same zoomed in or out. + */ +export function floorRegionCloseRadius3D( + camera: Camera, + viewportHeight: number, + pointWorld: Vector3 | null, +): number { + if (!(pointWorld && viewportHeight > 0)) return CLOSE_RADIUS_3D_FALLBACK + let perPixel: number + if ((camera as OrthographicCamera).isOrthographicCamera) { + const ortho = camera as OrthographicCamera + perPixel = (ortho.top - ortho.bottom) / ortho.zoom / viewportHeight + } else { + const perspective = camera as PerspectiveCamera + const distance = perspective.getWorldPosition(new Vector3()).distanceTo(pointWorld) + perPixel = (2 * distance * Math.tan((perspective.fov * Math.PI) / 360)) / viewportHeight + } + return Number.isFinite(perPixel) && perPixel > 0 + ? CLOSE_RADIUS_PX * perPixel + : CLOSE_RADIUS_3D_FALLBACK +} + +function firstPointWorld(): Vector3 | null { + const draft = useFloorRegionDraft.getState().draft + const first = draft?.kind === 'polygon' ? draft.points[0] : undefined + const level = draft ? sceneRegistry.nodes.get(draft.room.levelId) : undefined + if (!(draft && first && level)) return null + level.updateWorldMatrix(true, false) + return level.localToWorld(new Vector3(first[0], draft.room.elevation, first[1])) +} + +export function FloorRegionControls3D() { + const mode = useFloorRegionMode() + const { gl, camera } = useThree() + useFloorRegionLifetime(mode) + useEffect(() => { + if (!mode) return + return bindFloorRegionPointer( + gl.domElement, + (event) => + event.target === gl.domElement ? resolveFloorRegion3D(event, gl.domElement, camera) : null, + () => + floorRegionCloseRadius3D( + camera, + gl.domElement.getBoundingClientRect().height, + firstPointWorld(), + ), + ) + }, [gl, camera, mode]) + return mode ? : null +} + +/** + * The plan pointer on a room floor of `levelId` (the draft's floor while one + * is open, the host room while the mezzanine tool is armed). + */ +export function resolveFloorRegionPlanPoint( + levelId: string | null, + clientX: number, + clientY: number, +): FloorRegionHit | null { + const point = clientToPlan(clientX, clientY) + if (!(point && levelId)) return null + const plan: FloorRegionPoint = [point[0], point[1]] + const fixed = + useFloorRegionDraft.getState().draft?.room ?? + useOpeningDraft.getState().host ?? + useMezzanineDraft.getState().host ?? + useTerraceDraft.getState().host + if (fixed) return fixed.levelId === levelId ? { room: fixed, point: plan } : null + const room = resolveFloorRegionRoom(levelId, plan) + return room ? { room, point: plan } : null +} + +const MARKER_GLOW_PX = 10 +const MARKER_CORE_PX = 3 + +function PlanMarker({ at, color, upp }: { at: FloorRegionPoint; color: string; upp: number }) { + return ( + <> + + + + ) +} + +function ringsPath(pieces: MultiPolygon) { + return pieces + .flatMap(({ outer, holes }) => [outer, ...holes]) + .map((ring) => `M ${ring.map((point) => point.join(' ')).join(' L ')} Z`) + .join(' ') +} + +function FloorRegionPreview2D({ levelId }: { levelId: string | null }) { + const context = useFloorplanRender() + const draft = useFloorRegionDraft((s) => s.draft) + const hover = useFloorRegionDraft((s) => s.hover) + const view = useDraftView(draft && draft.room.levelId === levelId ? draft : null) + const isDark = useSceneIsDark() + const upp = context?.unitsPerPixel ?? 0.01 + const outline = isDark ? DRAFT_COLOR : DRAFT_COLOR_LIGHT_PLAN + const tint = usePaintTint(outline) + const fill = view?.fill ?? tint + const mezzanineHost = useMezzanineDraft((s) => (s.host?.levelId === levelId ? s.host : null)) + const openingHost = useOpeningDraft((s) => (s.host?.levelId === levelId ? s.host : null)) + const host = openingHost ?? mezzanineHost + const hostArea = host && ( + + ) + if (!view) { + if (draft || !(hostArea || (hover && hover.levelId === levelId))) return null + return ( + + {hostArea} + {hover && hover.levelId === levelId && ( + + )} + + ) + } + const stroke = view.message ? INVALID_COLOR : outline + const path = `M ${view.outline.map((point) => point.join(' ')).join(' L ')}${view.closed ? ' Z' : ''}` + return ( + + {hostArea} + {view.clip && ( + + )} + {view.outline.length > 1 && ( + + )} + {view.points.map((point, index) => ( + + ))} + {view.cursor && } + {view.label && view.anchor && ( + + + {view.label} + + + )} + + ) +} + +export function FloorRegionControls2D({ levelId }: { levelId: string | null }) { + const mode = useFloorRegionMode() + const context = useFloorplanRender() + const ref = useRef(null) + const upp = useRef(context?.unitsPerPixel ?? 0.01) + upp.current = context?.unitsPerPixel ?? 0.01 + useFloorRegionLifetime(mode) + useEffect(() => { + const svg = ref.current?.ownerSVGElement + if (!(svg && mode)) return + return bindFloorRegionPointer( + svg, + (event) => { + if (!(event.target instanceof Element) || event.target.closest('foreignObject')) return null + return resolveFloorRegionPlanPoint(levelId, event.clientX, event.clientY) + }, + () => CLOSE_RADIUS_PX * upp.current, + ) + }, [levelId, mode]) + return {mode && } +} diff --git a/packages/editor/src/components/editor/floor-region-webgpu-materials.test.ts b/packages/editor/src/components/editor/floor-region-webgpu-materials.test.ts new file mode 100644 index 0000000000..c2112366c7 --- /dev/null +++ b/packages/editor/src/components/editor/floor-region-webgpu-materials.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' + +test('the floor region preview draws with WebGPU node materials, not drei fat lines', () => { + const source = readFileSync(new URL('./floor-region-controls.tsx', import.meta.url), 'utf8') + expect(source).not.toMatch(/@react-three\/drei/) + expect(source).not.toMatch(/ s.roofDraftEnd) const roofDraftQuarterTurn = useFloorplanDraftPreview((s) => s.roofDraftQuarterTurn) const wallRectangleDraftStart = useFloorplanDraftPreview((s) => s.wallRectangleDraftStart) + const wallPolygonDraftPoints = useFloorplanDraftPreview((s) => s.wallPolygonDraftPoints) // The live cursor is the rectangle's opposite corner; select it only while a // rectangle draft is open so idle moves don't re-render this layer. const wallRectangleDraftEnd = useFloorplanDraftPreview((s) => @@ -4607,6 +4627,20 @@ function FloorplanLinearDraftLayer({ wallRectangleDraftStart, ]) + // An open Polygon room's placed sides — draft state, drawn like the + // rectangle draft (mitered together) until the polygon is written. + const polygonRoomDraft = useMemo(() => { + if (!(levelId && isWallBuildActive && wallPolygonDraftPoints.length >= 2)) return null + const draftWalls = wallPolygonDraftPoints.slice(1).map((end, index) => + getSharedFloorplanWall({ + ...buildDraftWall(levelId, wallPolygonDraftPoints[index]!, end), + id: `wall_polygon_draft_${index}` as WallNode['id'], + }), + ) + const miterData = calculateLevelMiters(draftWalls) + return draftWalls.map((wall) => formatPolygonPoints(getWallPlanFootprint(wall, miterData))) + }, [isWallBuildActive, levelId, wallPolygonDraftPoints]) + const draftPolygonPoints = useMemo(() => { if (isRoofBuildActive && roofDraftStart && roofDraftEnd) { const minX = Math.min(roofDraftStart[0], roofDraftEnd[0]) @@ -4849,6 +4883,22 @@ function FloorplanLinearDraftLayer({ /> )} + {polygonRoomDraft?.map((points, index) => ( + + ))} + {rectangleDraft?.polygons.map((points, index) => ( (null) - useEffect(() => { - if (structureLayer === 'zones' && floorplanSelectionTool === 'marquee') { - setFloorplanSelectionTool('click') - } - }, [floorplanSelectionTool, setFloorplanSelectionTool, structureLayer]) - useEffect(() => { setIsMacPlatform(navigator.platform.toUpperCase().includes('MAC')) }, []) @@ -5946,8 +5990,7 @@ export function FloorplanPanel({ mode === 'select' && floorplanSelectionTool === 'marquee' && !movingNode && - !isFenceEndpointMoveActive && - structureLayer !== 'zones' + !isFenceEndpointMoveActive const isScreenSelectionToolActive = mode === 'select' && floorplanSelectionTool === 'click' && @@ -5961,8 +6004,7 @@ export function FloorplanPanel({ mode === 'select' && floorplanSelectionTool === 'click' && !movingNode && - !isFenceEndpointMoveActive && - structureLayer !== 'zones' + !isFenceEndpointMoveActive const canInteractElementFloorplanGeometry = isDeleteMode || canSelectElementFloorplanGeometry const canInteractFloorplanSlabs = isDeleteMode || canSelectElementFloorplanGeometry const canInteractWithGuides = @@ -5977,7 +6019,7 @@ export function FloorplanPanel({ !isFenceEndpointMoveActive && structureLayer === 'zones' const canInteractFloorplanZones = isDeleteMode || canSelectFloorplanZones - const isFloorplanStructureContextActive = phase === 'structure' && structureLayer !== 'zones' + const isFloorplanStructureContextActive = phase === 'structure' const isFloorplanFurnishContextActive = phase === 'furnish' const isFloorplanItemContextActive = isFloorplanFurnishContextActive || isFloorplanStructureContextActive @@ -7894,7 +7936,10 @@ export function FloorplanPanel({ } }, [isFloorplanOpen, stopFloorplanViewAnimation]) + // Clearing an open wall draft drops a Polygon room in progress (nothing of + // it was written); paths that keep it commit first. const clearWallPlacementDraft = useCallback(() => { + discardWallPolygonDraft() setDraftStart(null) setWallChainFirstVertex(null) wallConstructionOptionsRef.current = undefined @@ -8019,7 +8064,7 @@ export function FloorplanPanel({ const zoneCount = Object.values(nodes).filter((node) => node.type === 'zone').length const zone = ZoneNodeSchema.parse({ color: PALETTE_COLORS[zoneCount % PALETTE_COLORS.length], - name: `Zone ${zoneCount + 1}`, + name: nextZoneName(nodes), polygon: points.map(([x, z]) => [x, z] as [number, number]), }) @@ -9556,7 +9601,7 @@ export function FloorplanPanel({ const wallAngleSnap = draftStart !== null && isAngleSnapActive() const wallSnap = snapWallDraftPointDetailed({ point: planPoint, - walls, + walls: [...walls, ...wallPolygonDraftWalls()], start: draftStart ?? undefined, angleSnap: wallAngleSnap, magnetic: isMagneticSnapActive(), @@ -9829,6 +9874,14 @@ export function FloorplanPanel({ useEditor.getState().toolDefaults.wall, ) : undefined + // 2D-only owns a Polygon room's draft; split view leaves it to the 3D tool. + if ( + levelId && + useEditor.getState().viewMode === '2d' && + getWallDrawVariant() === 'polygon' + ) { + startWallPolygonDraft(levelId as AnyNodeId, point, wallConstructionOptionsRef.current) + } setDraftStart(point) setWallChainFirstVertex(point) setDraftEnd(point) @@ -9856,6 +9909,20 @@ export function FloorplanPanel({ // view, so split / 3D keep their single-owner tool commit. const viewIs2DOnly = useEditor.getState().viewMode === '2d' let createdWall: WallNode | null = null + // 2D-only Polygon room: the corner joins the draft; nothing is written + // until it closes, seals or tees (then every wall at once). + if (viewIs2DOnly && getWallDrawVariant() === 'polygon') { + if (addWallPolygonDraftCorner(point) !== 'open') { + commitWallPolygonDraft() + clearWallPlacementDraft() + setCursorPoint(null) + return + } + setDraftStart(point) + setDraftEnd(point) + setCursorPoint(point) + return + } if (viewIs2DOnly) { createdWall = createWallOnCurrentLevel( draftStart, @@ -10059,14 +10126,21 @@ export function FloorplanPanel({ return } + if (useInteractionScope.getState().scope.kind !== 'idle') return const modifierKeys = getSelectionModifierKeys(event) + if (roomPickingEnabled()) { + const hitId = getFloorplanHitIdAtPoint(planPoint) + if (selectRoomFromHit(resolvePlanRoomHit(hitId, planPoint), modifierKeys, hitId)) return + } const backgroundSelection = resolveFloorplanBackgroundSelection({ canSelectElementFloorplanGeometry, - canSelectFloorplanZones, + canSelectFloorplanZones: canSelectFloorplanZones && !!useViewer.getState().focusedUnitId, currentSelectedIds: useViewer.getState().selection.selectedIds, expandIdsForNode: expandSessionSelectionForNode, - getFloorplanHitIdAtPoint, + getFloorplanHitIdAtPoint: useViewer.getState().focusedUnitId + ? (point) => zoneAtLevelPoint(point[0], point[1])?.id ?? null + : getFloorplanHitIdAtPoint, isWallBuildActive, modifierKeys, planPoint, @@ -10118,15 +10192,14 @@ export function FloorplanPanel({ } if (backgroundSelection.kind === 'clear-zones') { - setSelection({ zoneId: null }) - // Return to structure select (same as 3D grid click) - useEditor.getState().setStructureLayer('elements') - useEditor.getState().setMode('select') + useEditor.getState().clearRoom() + setSelection({ selectedIds: [], zoneId: null }) return } if (!backgroundSelection.preserveSelection) { - setSelection({ selectedIds: [] }) + useEditor.getState().clearRoom() + setSelection({ selectedIds: [], zoneId: null }) } return } @@ -10314,28 +10387,18 @@ export function FloorplanPanel({ if (floorplanScreenSelectionOwnsInputDraggingRef.current) { useViewer.getState().setInputDragging(false) floorplanScreenSelectionOwnsInputDraggingRef.current = false + useInteractionScope.getState().endIf((scope) => scope.kind === 'box-select') } }, [syncPreviewSelectedIds]) const commitFloorplanScreenSelection = useCallback( (nextSelectedIds: string[], event: PointerEvent) => { const modifierKeys = getSelectionModifierKeys(event) - const shouldAppend = modifierKeys.meta || modifierKeys.ctrl || modifierKeys.shift - setSelectedReferenceId(null) - if (phase === 'structure' && structureLayer === 'zones') { - if (nextSelectedIds.length > 0) { - setSelection({ zoneId: nextSelectedIds[0] as ZoneNodeType['id'] }) - } else if (!shouldAppend) { - setSelection({ zoneId: null }) - } - return - } - addFloorplanSelection(nextSelectedIds, modifierKeys) }, - [addFloorplanSelection, phase, setSelectedReferenceId, setSelection, structureLayer], + [addFloorplanSelection, setSelectedReferenceId], ) useEffect(() => { @@ -10385,6 +10448,7 @@ export function FloorplanPanel({ if (!state.isDragging && dragDistance >= SCREEN_RECTANGLE_SELECTION_DRAG_THRESHOLD_PX) { state.isDragging = true floorplanScreenSelectionOwnsInputDraggingRef.current = true + useInteractionScope.getState().begin({ kind: 'box-select' }) useViewer.getState().setInputDragging(true) markBoxSelectHandled() @@ -10789,11 +10853,16 @@ export function FloorplanPanel({ const hasFloorplanCursorIndicator = Boolean(movingOpeningType) || (mode === 'build' && tool !== null) || - (mode === 'select' && floorplanSelectionTool === 'marquee' && structureLayer !== 'zones') || + (mode === 'select' && floorplanSelectionTool === 'marquee') || mode === 'delete' const handleSvgPointerMove = useCallback( (event: ReactPointerEvent) => { + if (roomPickingEnabled() && !(event.target as Element).closest('.floorplan-registry-entry')) { + const point = getPlanPointFromClientPoint(event.clientX, event.clientY) + if (point) + hoverRoomFromHit(resolvePlanRoomHit(null, point), getSelectionModifierKeys(event), null) + } if ( hasFloorplanCursorIndicator && !isSpacePanPressed && @@ -10826,6 +10895,7 @@ export function FloorplanPanel({ [ handlePointerMove, hasFloorplanCursorIndicator, + getPlanPointFromClientPoint, isSpacePanPressed, siteVertexDragState, setFloorplanCursorPosition, @@ -10833,6 +10903,7 @@ export function FloorplanPanel({ ) const handleSvgPointerLeave = useCallback(() => { + useEditor.getState().setHoveredRoom(null) setFloorplanCursorPosition(null) setHoveredGuideCorner(null) handlePointerLeave() diff --git a/packages/editor/src/components/editor/footprint-height-handle.tsx b/packages/editor/src/components/editor/footprint-height-handle.tsx new file mode 100644 index 0000000000..25019e894f --- /dev/null +++ b/packages/editor/src/components/editor/footprint-height-handle.tsx @@ -0,0 +1,204 @@ +'use client' + +import { + type AnyNodeId, + getStoredLevelHeight, + type Point, + type SlabNode, + sceneRegistry, + upperFloorHeightControl, + useScene, +} from '@pascal-app/core' +import { useViewer } from '@pascal-app/viewer' +import { Html } from '@react-three/drei' +import { type ThreeEvent, useFrame, useThree } from '@react-three/fiber' +import { useRef, useState } from 'react' +import { type Group, Plane, Vector2, Vector3 } from 'three' +import { + beginFootprintHeightPreview, + footprintHeightMinimum, + footprintHeightValue, + THICK_FLOOR_HINT, + thickFloorAdvice, +} from '../../lib/floor-footprints' +import { formatLinearMeasurement } from '../../lib/measurements' +import { runRoomHandleDrag } from '../../lib/room-handle-drag' +import useEditor, { isGridSnapActive } from '../../store/use-editor' +import useInteractionScope from '../../store/use-interaction-scope' +import { suppressBoxSelectForPointer } from '../tools/select/box-select-state' +import { ElevationArrows, outlineCentroid, useHandleScale } from './room-handles' + +export const FOOTPRINT_HEIGHT_DRAG_LABEL = 'footprint-height' + +const PILL = + 'pointer-events-none flex items-center gap-2 whitespace-nowrap rounded-full border border-border/60 bg-background/90 px-4 py-1.5 text-xs tabular-nums shadow-sm backdrop-blur' +const NOTICE = + 'pointer-events-none max-w-72 rounded-full border border-border/60 bg-background/95 px-3 py-1 text-center text-muted-foreground text-xs shadow-md backdrop-blur-md' + +/** The selected footprint floor (base plate), when it is the one selection in select mode. */ +function useSelectedFootprint(): SlabNode | null { + const selectedId = useViewer((s) => + s.selection.selectedIds.length === 1 ? s.selection.selectedIds[0] : null, + ) + const enabled = useEditor((s) => s.mode === 'select') + const idle = useInteractionScope( + (s) => + s.scope.kind === 'idle' || + (s.scope.kind === 'handle-drag' && s.scope.handle === FOOTPRINT_HEIGHT_DRAG_LABEL), + ) + const plate = useScene((s) => { + const node = selectedId ? s.nodes[selectedId as AnyNodeId] : undefined + return node?.type === 'slab' && node.plateRole === 'base' ? node : null + }) + return enabled && idle ? plate : null +} + +/** + * A selected footprint floor's one control in 3D: the rooms' arrow–cube–arrow + * at the middle of the footprint, dragging its height above the ground. The + * building follows live; the release lands as one undo step. Refused heights + * (core's conflict, e.g. an upper floor over another footprint) show beside it. + */ +export function FootprintHeightHandle() { + const plate = useSelectedFootprint() + const root = useRef(null) + useFrame(() => { + const level = plate?.parentId ? sceneRegistry.nodes.get(plate.parentId) : null + if (!root.current) return + root.current.visible = !!level + if (level) { + level.updateWorldMatrix(true, false) + root.current.matrix.copy(level.matrixWorld) + } + }) + if (!plate) return null + return ( + + + + ) +} + +function FootprintHeightArrows({ plate }: { plate: SlabNode }) { + const { camera, raycaster, gl } = useThree() + const zoom = useHandleScale() + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + const [hover, setHover] = useState(false) + const [dragValue, setDragValue] = useState(null) + const [notice, setNotice] = useState(null) + const [hint, setHint] = useState(null) + const upper = useScene((s) => upperFloorHeightControl(s.nodes, plate) !== null) + const anchor: Point = outlineCentroid([plate.polygon as Point[], ...(plate.holes as Point[][])]) + const elevation = plate.elevation + + const onPointerDown = (event: ThreeEvent) => { + if (event.button !== 0) return + event.stopPropagation() + suppressBoxSelectForPointer(event) + const levelId = plate.parentId + const level = levelId ? sceneRegistry.nodes.get(levelId) : null + if (!(levelId && level)) return + level.updateWorldMatrix(true, false) + const toLocal = level.matrixWorld.clone().invert() + const world = new Vector3(anchor[0], elevation, anchor[1]).applyMatrix4(level.matrixWorld) + const normal = camera.getWorldPosition(new Vector3()).sub(world).setY(0) + if (normal.lengthSq() === 0) return + const plane = new Plane().setFromNormalAndCoplanarPoint(normal.normalize(), world) + const localY = (clientX: number, clientY: number) => { + const rect = gl.domElement.getBoundingClientRect() + raycaster.setFromCamera( + new Vector2( + ((clientX - rect.left) / rect.width) * 2 - 1, + -((clientY - rect.top) / rect.height) * 2 + 1, + ), + camera, + ) + const hit = raycaster.ray.intersectPlane(plane, new Vector3()) + return hit ? hit.applyMatrix4(toLocal).y : null + } + const startY = localY(event.nativeEvent.clientX, event.nativeEvent.clientY) + if (startY === null) return + const nodes = () => useScene.getState().nodes + // Heights are read against the plate as the drag found it (the preview moves it). + const startNodes = nodes() + const start = footprintHeightValue(startNodes, plate) + const min = footprintHeightMinimum(startNodes, plate) + const levelNode = nodes()[levelId as AnyNodeId] + const max = levelNode?.type === 'level' ? getStoredLevelHeight(levelNode) - 0.5 : 3 + const step = isGridSnapActive() ? 0.05 : 0.01 + let value = start + const preview = beginFootprintHeightPreview(plate.id) + setNotice(null) + setDragValue(start) + runRoomHandleDrag({ + label: FOOTPRINT_HEIGHT_DRAG_LABEL, + nodeId: plate.id, + levelId, + requires: [plate.id], + sample: (x, y) => { + const pointerY = localY(x, y) + if (pointerY === null) return null + const raw = start + pointerY - startY + return Math.max(min, Math.min(max, Math.round(raw / step) * step)) + }, + onValue: (next) => { + if (Math.abs(next - value) < 1e-6) return + // Live: the building follows, outside history until the release. + const refused = preview.preview(next) + setNotice(refused) + setHint(thickFloorAdvice(startNodes, plate, next) ? THICK_FLOOR_HINT : null) + if (!refused) value = next + setDragValue(next) + }, + onCommit: () => { + setNotice(preview.commit(value)) + setDragValue(null) + setHint(null) + }, + onCancel: () => { + preview.cancel() + setDragValue(null) + setHint(null) + }, + }) + } + + const shown = dragValue ?? null + return ( + + + {(shown !== null || notice || hint) && ( + +
+ {shown !== null && ( +
+ + {upper ? 'Floor top' : 'Foundation'} + + + {formatLinearMeasurement(shown, unit, metricNotation)} + +
+ )} + {(notice ?? hint) && ( +
+ {notice ?? hint} +
+ )} +
+ + )} +
+ ) +} diff --git a/packages/editor/src/components/editor/group-actions.ts b/packages/editor/src/components/editor/group-actions.ts index f41db4cb8c..ce61d51362 100644 --- a/packages/editor/src/components/editor/group-actions.ts +++ b/packages/editor/src/components/editor/group-actions.ts @@ -18,6 +18,8 @@ import { markPerfAction, useViewer } from '@pascal-app/viewer' import { Plane, Vector2, Vector3 } from 'three' import { GROUP_MOVE_DRAG_LABEL } from '../../lib/contextual-help' import { clientToPlan } from '../../lib/floorplan/plan-coords' +import { deleteSelectedSeparator, requestRoomDeletion } from '../../lib/room-structure-commands' +import { captureElementActionOrigin, completeElementAction } from '../../lib/room-zone-routing' import { copySelectedNodesToEditorClipboard, duplicateNodesToLevel, @@ -547,7 +549,16 @@ export function cutSelectionToEditorClipboard(): boolean { */ export function deleteSelection(): boolean { const selectedIds = useViewer.getState().selection.selectedIds as AnyNodeId[] - if (selectedIds.length === 0) return false + if (selectedIds.length === 0) { + const room = useEditor.getState().room + if (!room) return false + requestRoomDeletion(room.zoneId) + return true + } + // A drilled piece of a room (a wall, a separator, its ceiling) deleted: back to the room. + const origin = captureElementActionOrigin(selectedIds) + if (selectedIds.length === 1 && useScene.getState().nodes[selectedIds[0]!]?.type === 'separator') + return deleteSelectedSeparator(selectedIds[0]!, origin) const commitDelete = () => { const detail = @@ -562,6 +573,7 @@ export function deleteSelection(): boolean { } useScene.getState().deleteNodes(selectedIds) useViewer.getState().setSelection({ selectedIds: [] }) + completeElementAction(origin) } if (selectedIds.length >= BULK_DELETE_THRESHOLD) { diff --git a/packages/editor/src/components/editor/handles/handle-hit-priority.test.tsx b/packages/editor/src/components/editor/handles/handle-hit-priority.test.tsx new file mode 100644 index 0000000000..b505b82c70 --- /dev/null +++ b/packages/editor/src/components/editor/handles/handle-hit-priority.test.tsx @@ -0,0 +1,63 @@ +import { expect, test } from 'bun:test' +import { type RootState, useThree } from '@react-three/fiber' +import { create } from '@react-three/test-renderer' +import { useLayoutEffect } from 'react' +import { type Intersection, Object3D } from 'three' +import { EDITOR_HANDLE_HIT_AREA_USER_DATA_KEY } from '../../../lib/direct-manipulation' +import { EditorHandleHitPriority, prioritizeEditorHandleHits } from './handle-hit-priority' + +function hit(name: string, distance: number, handle = false): Intersection { + const object = new Object3D() + object.name = name + if (handle) object.userData[EDITOR_HANDLE_HIT_AREA_USER_DATA_KEY] = true + return { object, distance, point: undefined as never } +} +const names = (hits: Intersection[]) => hits.map((entry) => entry.object.name) + +test('a handle behind a wall comes first, so the hover goes where the press goes', () => { + const hits = [hit('wall', 3), hit('floor', 5), hit('up', 6, true), hit('cube', 6.2, true)] + expect(names(prioritizeEditorHandleHits(hits))).toEqual(['up', 'cube', 'wall', 'floor']) +}) + +test('without a handle on the ray the order is untouched', () => { + const hits = [hit('wall', 3), hit('floor', 5)] + expect(prioritizeEditorHandleHits(hits)).toBe(hits) +}) + +test('mounted, it is the canvas event filter; unmounted, the previous one comes back', async () => { + let state: RootState | null = null + const Probe = () => { + state = useThree((root) => root) + return null + } + const previous = (hits: Intersection[]) => hits.filter((entry) => entry.object.name !== 'grid') + const Previous = () => { + const setEvents = useThree((root) => root.setEvents) + useLayoutEffect(() => setEvents({ filter: previous }), [setEvents]) + return null + } + const before = await create( + <> + + + , + ) + await before.update( + <> + + + + , + ) + const hits = [hit('grid', 1), hit('wall', 3), hit('cube', 6, true)] + const filter = (state as RootState | null)?.events.filter + expect(names(filter!(hits, state!))).toEqual(['cube', 'wall']) + await before.update( + <> + + + , + ) + expect((state as RootState | null)?.events.filter).toBe(previous) + await before.unmount() +}) diff --git a/packages/editor/src/components/editor/handles/handle-hit-priority.tsx b/packages/editor/src/components/editor/handles/handle-hit-priority.tsx new file mode 100644 index 0000000000..b911dadffa --- /dev/null +++ b/packages/editor/src/components/editor/handles/handle-hit-priority.tsx @@ -0,0 +1,37 @@ +'use client' + +import { useThree } from '@react-three/fiber' +import { useEffect } from 'react' +import type { Intersection, Object3D } from 'three' +import { EDITOR_HANDLE_HIT_AREA_USER_DATA_KEY } from '../../../lib/direct-manipulation' + +const isHandleHit = (hit: { object: Object3D }) => + hit.object.userData?.[EDITOR_HANDLE_HIT_AREA_USER_DATA_KEY] === true + +/** + * Editor handles first, everything else after, each in distance order. Handles + * draw on top of walls and a handle anywhere along the ray already owns the + * press; ordering them first gives them the hover too. Distance order alone + * lets a wall in front win the hover for good: once its enter stops + * propagation, R3F keeps stopping every later move at it, so a handle behind + * it never hears its enter however the pointer reaches it. + */ +export function prioritizeEditorHandleHits(hits: T[]): T[] { + if (!hits.some(isHandleHit)) return hits + return [...hits.filter(isHandleHit), ...hits.filter((hit) => !isHandleHit(hit))] +} + +/** Installs `prioritizeEditorHandleHits` as the canvas's pointer-event filter while mounted. */ +export function EditorHandleHitPriority() { + const get = useThree((state) => state.get) + const setEvents = useThree((state) => state.setEvents) + useEffect(() => { + const previous = get().events.filter + setEvents({ + filter: (hits: Intersection[], state) => + prioritizeEditorHandleHits(previous ? previous(hits, state) : hits), + }) + return () => setEvents({ filter: previous }) + }, [get, setEvents]) + return null +} diff --git a/packages/editor/src/components/editor/handles/use-handle-drag.ts b/packages/editor/src/components/editor/handles/use-handle-drag.ts index 0f5442f759..0e1995e198 100644 --- a/packages/editor/src/components/editor/handles/use-handle-drag.ts +++ b/packages/editor/src/components/editor/handles/use-handle-drag.ts @@ -14,11 +14,22 @@ import { import { useViewer } from '@pascal-app/viewer' import { type ThreeEvent, useThree } from '@react-three/fiber' import { useEffect, useRef } from 'react' -import { type Camera, type Object3D, type Plane, type Ray, Vector2, type Vector3 } from 'three' +import { + type Camera, + type Object3D, + type Plane, + type Ray, + type Raycaster, + Vector2, + type Vector3, +} from 'three' +import { beginGesture, scopeMatcher } from '../../../lib/gesture-lifecycle' import { isHistoryShortcut } from '../../../lib/history' import { sfxEmitter } from '../../../lib/sfx-bus' import { intersectSpatialDragPlane } from '../../../lib/spatial-drag-plane' import { getSpatialPointerId, spatialPointerInput } from '../../../lib/spatial-pointer-input' +import { isTypingTarget } from '../../../lib/typing-target' +import useInteractionScope from '../../../store/use-interaction-scope' import { suppressBoxSelectForPointer } from '../../tools/select/box-select-state' import { commitHandleDragPatch } from './handle-drag-history' @@ -82,14 +93,14 @@ type UseHandleDragArgs = } export function swallowNextClick() { - const target = window + const clickWindow = window const swallow = (clickEvent: Event) => { clickEvent.stopPropagation() clickEvent.preventDefault() } - target.addEventListener('click', swallow, { capture: true, once: true }) + clickWindow.addEventListener('click', swallow, { capture: true, once: true }) setTimeout(() => { - target.removeEventListener('click', swallow, { capture: true }) + clickWindow.removeEventListener('click', swallow, { capture: true }) }, 300) } @@ -120,137 +131,168 @@ export function useHandleDrag(args: UseHandleDragArgs) { useEffect(() => () => dragCleanupRef.current?.(), []) - return (event: ThreeEvent) => { - // Only the primary button starts a handle gesture — right/middle-drag - // belongs to the camera, so let it propagate untouched. - if (event.button !== 0) return - event.stopPropagation() - suppressBoxSelectForPointer(event) - const spatialPointerId = getSpatialPointerId(event.nativeEvent) - - if (args.kind === 'tap') { - const restoreInputDragging = suppressInputDraggingUntilPointerRelease(event.pointerId) - if (spatialPointerId) { - spatialPointerInput.capture(spatialPointerId, { - onMove: () => undefined, - onRelease: restoreInputDragging, - onCancel: restoreInputDragging, - }) - } - swallowNextClick() - sfxEmitter.emit('sfx:item-pick') - document.body.style.cursor = '' - args.onTap(event) - return - } + return (event: ThreeEvent) => + startHandleDrag(args, event, { camera, raycaster, gl }, dragCleanupRef) +} - const { cursor, dragControls, handleIndex, node, rideObject, setIsDragging } = args - rideObject.updateMatrixWorld() - const spatialRay = spatialPointerId ? event.ray.clone() : null - - const ndc = new Vector2() - const setPointerRay = (clientX: number, clientY: number) => { - const rect = gl.domElement.getBoundingClientRect() - ndc.set( - ((clientX - rect.left) / rect.width) * 2 - 1, - -((clientY - rect.top) / rect.height) * 2 + 1, - ) - raycaster.setFromCamera(ndc, camera) - } - const getPointerRay: GetPointerRay = (clientX, clientY, target) => { - if (spatialRay) return target.copy(spatialRay) - setPointerRay(clientX, clientY) - return target.copy(raycaster.ray) - } - const intersectPlane: IntersectPlane = (clientX, clientY, plane, target) => { - if (spatialRay) return intersectSpatialDragPlane(spatialRay, plane, target) - setPointerRay(clientX, clientY) - return raycaster.ray.intersectPlane(plane, target) +type HandleDragThree = { + camera: Camera + raycaster: Raycaster + gl: { domElement: Pick } +} + +/** + * One press on a handle: a tap, or a drag registered with the gesture + * lifecycle owner (mode / level / selection change, its scope replaced, its + * node deleted, any history command, unmount → cancel). Release commits; the + * cleanup runs exactly once and in `finally`, so a throwing commit cannot + * leave the drag live. Exported for tests; components use `useHandleDrag`. + */ +export function startHandleDrag( + args: UseHandleDragArgs, + event: ThreeEvent, + { camera, raycaster, gl }: HandleDragThree, + dragCleanupRef: { current: (() => void) | null }, +) { + // Only the primary button starts a handle gesture — right/middle-drag + // belongs to the camera, so let it propagate untouched. + if (event.button !== 0) return + event.stopPropagation() + suppressBoxSelectForPointer(event) + const spatialPointerId = getSpatialPointerId(event.nativeEvent) + + if (args.kind === 'tap') { + const restoreInputDragging = suppressInputDraggingUntilPointerRelease(event.pointerId) + if (spatialPointerId) { + spatialPointerInput.capture(spatialPointerId, { + onMove: () => undefined, + onRelease: restoreInputDragging, + onCancel: restoreInputDragging, + }) } + swallowNextClick() + sfxEmitter.emit('sfx:item-pick') + document.body.style.cursor = '' + args.onTap(event) + return + } + + const { cursor, dragControls, handleIndex, node, rideObject, setIsDragging } = args + rideObject.updateMatrixWorld() + const spatialRay = spatialPointerId ? event.ray.clone() : null - const nodeId = node.id as AnyNodeId - const sceneApi = createSceneApi(useScene) - const initialNode = (sceneApi.get(nodeId) ?? node) as AnyNode - const session = args.onStart({ - event, - camera, + const ndc = new Vector2() + const setPointerRay = (clientX: number, clientY: number) => { + const rect = gl.domElement.getBoundingClientRect() + ndc.set( + ((clientX - rect.left) / rect.width) * 2 - 1, + -((clientY - rect.top) / rect.height) * 2 + 1, + ) + raycaster.setFromCamera(ndc, camera) + } + const getPointerRay: GetPointerRay = (clientX, clientY, target) => { + if (spatialRay) return target.copy(spatialRay) + setPointerRay(clientX, clientY) + return target.copy(raycaster.ray) + } + const intersectPlane: IntersectPlane = (clientX, clientY, plane, target) => { + if (spatialRay) return intersectSpatialDragPlane(spatialRay, plane, target) + setPointerRay(clientX, clientY) + return raycaster.ray.intersectPlane(plane, target) + } + + const nodeId = node.id as AnyNodeId + const sceneApi = createSceneApi(useScene) + const initialNode = (sceneApi.get(nodeId) ?? node) as AnyNode + const session = args.onStart({ + event, + camera, + getPointerRay, + intersectPlane, + initialNode, + node, + nodeId, + rideObject, + sceneApi, + }) + if (!session) return + + const overrideId = session.overrideId ?? nodeId + const markDirty = session.markDirty !== false + const scopeBefore = useInteractionScope.getState().scope + document.body.style.cursor = cursor + sfxEmitter.emit('sfx:item-pick') + useViewer.getState().setInputDragging(true) + useScene.temporal.getState().pause() + setIsDragging(true) + dragControls.onStart(handleIndex, initialNode) + session.onBegin?.() + // The scope the handle's own callbacks began is the one whose loss cancels. + const scopeAfter = useInteractionScope.getState().scope + const nodeInScene = !!useScene.getState().nodes[nodeId] + + let lastPatch: Partial | null = null + let historyPaused = true + let releaseSpatialCapture: (() => void) | null = null + let altKey = event.nativeEvent.altKey + let shiftKey = event.nativeEvent.shiftKey + let pendingMoveEvent: PointerEvent | null = null + let moveFrame = 0 + + const resumeHistory = () => { + if (!historyPaused) return + historyPaused = false + useScene.temporal.getState().resume() + } + + const processMove = (moveEvent: PointerEvent) => { + const patch = session.move({ + event: moveEvent, + modifiers: { altKey, shiftKey }, getPointerRay, intersectPlane, - initialNode, - node, - nodeId, - rideObject, - sceneApi, }) - if (!session) return - - const overrideId = session.overrideId ?? nodeId - const markDirty = session.markDirty !== false - document.body.style.cursor = cursor - sfxEmitter.emit('sfx:item-pick') - useViewer.getState().setInputDragging(true) - useScene.temporal.getState().pause() - setIsDragging(true) - dragControls.onStart(handleIndex, initialNode) - session.onBegin?.() - - let lastPatch: Partial | null = null - let historyPaused = true - let releaseSpatialCapture: (() => void) | null = null - let altKey = event.nativeEvent.altKey - let shiftKey = event.nativeEvent.shiftKey - let pendingMoveEvent: PointerEvent | null = null - let moveFrame = 0 - - const resumeHistory = () => { - if (!historyPaused) return - historyPaused = false - useScene.temporal.getState().resume() - } - - const processMove = (moveEvent: PointerEvent) => { - const patch = session.move({ - event: moveEvent, - modifiers: { altKey, shiftKey }, - getPointerRay, - intersectPlane, - }) - if (!patch) return - lastPatch = patch - useLiveNodeOverrides.getState().set(overrideId, patch as Record) - if (markDirty) { - for (const id of cascadeDirty(overrideId, { scene: createSceneApi(useScene) })) - useScene.getState().markDirty(id) - } + if (!patch) return + lastPatch = patch + useLiveNodeOverrides.getState().set(overrideId, patch as Record) + if (markDirty) { + for (const id of cascadeDirty(overrideId, { scene: createSceneApi(useScene) })) + useScene.getState().markDirty(id) } + } - // Coalesce high-frequency pointer events so live React/store updates happen - // at most once per animation frame while retaining the newest position. - const flushMove = () => { - moveFrame = 0 - const moveEvent = pendingMoveEvent - pendingMoveEvent = null - if (moveEvent) processMove(moveEvent) - } - const onMove = (moveEvent: PointerEvent) => { - pendingMoveEvent = moveEvent - if (moveFrame !== 0) return - if (typeof window.requestAnimationFrame === 'function') { - moveFrame = window.requestAnimationFrame(flushMove) - } else { - flushMove() - } + // Coalesce high-frequency pointer events so live React/store updates happen + // at most once per animation frame while retaining the newest position. + const flushMove = () => { + moveFrame = 0 + const moveEvent = pendingMoveEvent + pendingMoveEvent = null + if (moveEvent) processMove(moveEvent) + } + const onMove = (moveEvent: PointerEvent) => { + pendingMoveEvent = moveEvent + if (moveFrame !== 0) return + if (typeof window.requestAnimationFrame === 'function') { + moveFrame = window.requestAnimationFrame(flushMove) + } else { + flushMove() } + } - const cleanup = () => { - if (moveFrame !== 0) window.cancelAnimationFrame?.(moveFrame) - moveFrame = 0 - pendingMoveEvent = null - window.removeEventListener('pointermove', onMove) - window.removeEventListener('pointerup', onUp) - window.removeEventListener('pointercancel', onCancel) - window.removeEventListener('keydown', onKeyDown, true) - window.removeEventListener('keyup', onKeyUp, true) + let done = false + const cleanup = () => { + if (done) return + done = true + if (moveFrame !== 0) window.cancelAnimationFrame?.(moveFrame) + moveFrame = 0 + pendingMoveEvent = null + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', onUp) + window.removeEventListener('pointercancel', onCancel) + window.removeEventListener('keydown', onKeyDown, true) + window.removeEventListener('keyup', onKeyUp, true) + dragCleanupRef.current = null + try { releaseSpatialCapture?.() releaseSpatialCapture = null if (document.body.style.cursor === cursor) { @@ -259,88 +301,117 @@ export function useHandleDrag(args: UseHandleDragArgs) { resumeHistory() useViewer.getState().setInputDragging(false) setIsDragging(false) - session.onEnd?.() - dragControls.onEnd() - dragCleanupRef.current = null - } - - const clearOverride = () => { - useLiveNodeOverrides.getState().clear(overrideId) - if (markDirty) { - for (const id of cascadeDirty(overrideId, { scene: createSceneApi(useScene) })) - useScene.getState().markDirty(id) + } finally { + try { + session.onEnd?.() + } finally { + dragControls.onEnd() } } + } - const onUp = () => { - if (moveFrame !== 0) window.cancelAnimationFrame?.(moveFrame) - flushMove() - swallowNextClick() - sfxEmitter.emit('sfx:item-place') - if (lastPatch) { - commitHandleDragPatch({ - patch: lastPatch, - resumeHistory, - runAsSingleHistoryStep: (run) => runAsSingleSceneHistoryStep(useScene, run), - commit: session.commit ?? ((patch) => sceneApi.update(overrideId, patch)), - }) - } - clearOverride() - cleanup() - } - - const onCancel = () => { - session.onCancel?.() - clearOverride() - cleanup() + const clearOverride = () => { + useLiveNodeOverrides.getState().clear(overrideId) + if (markDirty) { + for (const id of cascadeDirty(overrideId, { scene: createSceneApi(useScene) })) + useScene.getState().markDirty(id) } + } - // Escape / ⌘Z abort the drag — capture phase so they win over the global - // use-keyboard arms (⌘Z must never history-jump under a live pointer). - const onKeyDown = (e: KeyboardEvent) => { - if (e.key === 'Alt') { - altKey = true - return + const gesture = beginGesture({ + kind: 'handle-drag', + onCancel: () => { + try { + session.onCancel?.() + } finally { + try { + clearOverride() + } finally { + cleanup() + } } - if (e.key === 'Shift') { - shiftKey = true - return + }, + ownsScope: + scopeAfter !== scopeBefore && scopeAfter.kind !== 'idle' + ? scopeMatcher(scopeAfter) + : undefined, + // A draft handle's node is not in the scene yet; only a real node can go stale. + stale: nodeInScene ? () => !useScene.getState().nodes[nodeId] : undefined, + }) + + const onUp = () => { + if (moveFrame !== 0) window.cancelAnimationFrame?.(moveFrame) + flushMove() + swallowNextClick() + sfxEmitter.emit('sfx:item-place') + gesture.finish(() => { + try { + if (lastPatch) { + commitHandleDragPatch({ + patch: lastPatch, + resumeHistory, + runAsSingleHistoryStep: (run) => runAsSingleSceneHistoryStep(useScene, run), + commit: session.commit ?? ((patch) => sceneApi.update(overrideId, patch)), + }) + } + } finally { + try { + clearOverride() + } finally { + cleanup() + } } - if (e.key !== 'Escape' && !isHistoryShortcut(e)) return - e.preventDefault() - e.stopPropagation() - swallowNextClick() - onCancel() + }) + } + + const onCancel = () => gesture.cancel('cancel') + + // Escape / ⌘Z abort the drag — capture phase so they win over the global + // use-keyboard arms (⌘Z must never history-jump under a live pointer). + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Alt') { + altKey = true + return } - const onKeyUp = (e: KeyboardEvent) => { - if (e.key === 'Alt') altKey = false - if (e.key === 'Shift') shiftKey = false + if (e.key === 'Shift') { + shiftKey = true + return } + if (e.key !== 'Escape' && !isHistoryShortcut(e)) return + if (isTypingTarget(e.target)) return + e.preventDefault() + e.stopPropagation() + swallowNextClick() + onCancel() + } + const onKeyUp = (e: KeyboardEvent) => { + if (e.key === 'Alt') altKey = false + if (e.key === 'Shift') shiftKey = false + } - dragCleanupRef.current = onCancel - if (spatialPointerId && spatialRay) { - releaseSpatialCapture = spatialPointerInput.capture(spatialPointerId, { - onMove: (ray) => { - spatialRay.copy(ray) - processMove( - new PointerEvent('pointermove', { - button: 0, - buttons: 1, - altKey, - pointerId: event.pointerId, - pointerType: 'xr', - }), - ) - }, - onRelease: onUp, - onCancel, - }) - } else { - window.addEventListener('pointermove', onMove) - window.addEventListener('pointerup', onUp) - window.addEventListener('pointercancel', onCancel) - } - window.addEventListener('keydown', onKeyDown, true) - window.addEventListener('keyup', onKeyUp, true) + dragCleanupRef.current = onCancel + if (spatialPointerId && spatialRay) { + releaseSpatialCapture = spatialPointerInput.capture(spatialPointerId, { + onMove: (ray) => { + spatialRay.copy(ray) + processMove( + new PointerEvent('pointermove', { + button: 0, + buttons: 1, + altKey, + pointerId: event.pointerId, + pointerType: 'xr', + }), + ) + }, + onRelease: onUp, + onCancel, + }) + } else { + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', onUp) + window.addEventListener('pointercancel', onCancel) } + window.addEventListener('keydown', onKeyDown, true) + window.addEventListener('keyup', onKeyUp, true) } diff --git a/packages/editor/src/components/editor/index.tsx b/packages/editor/src/components/editor/index.tsx index f80ad8352c..89e72cec88 100644 --- a/packages/editor/src/components/editor/index.tsx +++ b/packages/editor/src/components/editor/index.tsx @@ -38,11 +38,16 @@ import { ViewerZoneSystem } from '../../components/viewer-zone-system' import { type SaveStatus, useAutoSave } from '../../hooks/use-auto-save' import { useKeyboard } from '../../hooks/use-keyboard' import { useSaveShortcut } from '../../hooks/use-save-shortcut' +import { useCeilingEditSessionOwner } from '../../lib/ceiling-edit-session' +import { showsWholeBuilding, useEditorLevelDisplay } from '../../lib/editor-level-display' +import { useGestureLifecycleOwner } from '../../lib/gesture-lifecycle' import { createLocalProjectPresentationPersistence, type LocalProjectPresentationPersistence, } from '../../lib/local-project-presentation-persistence' import { type ActivePaintMaterial, hasActivePaintMaterial } from '../../lib/material-paint' +import { usePaintRegionHovering } from '../../lib/paint-region-hover' +import { resetPaintMode, usePaintRegionMode } from '../../lib/paint-region-mode' import { applySceneGraphToEditor, loadSceneFromLocalStorage, @@ -73,6 +78,7 @@ import { PanelManager } from '../ui/panels/panel-manager' import { ErrorBoundary } from '../ui/primitives/error-boundary' import { useSidebarStore } from '../ui/primitives/sidebar' import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/primitives/tooltip' +import { RightStack } from '../ui/right-stack' import { SceneLoader, SceneLoadFailed } from '../ui/scene-loader' import { AppSidebar } from '../ui/sidebar/app-sidebar' import type { ExtraPanel } from '../ui/sidebar/icon-rail' @@ -93,10 +99,12 @@ import { FloatingActionMenu } from './floating-action-menu' import { FloatingBuildingActionMenu } from './floating-building-action-menu' import { FloorplanModeCoordinator } from './floorplan-mode-coordinator' import { FloorplanPanel } from './floorplan-panel' +import { FootprintHeightHandle } from './footprint-height-handle' import { Grid } from './grid' import { GroupFloatingActionMenu } from './group-floating-action-menu' import { GroupRotateHandle } from './group-rotate-handle' import { GroupSelectionBox3D } from './group-selection-box-3d' +import { EditorHandleHitPriority } from './handles/handle-hit-priority' import { NodeArrowHandles } from './node-arrow-handles' import { QuickMeasurementHud } from './quick-measurement-hud' import { RiserDiagramPanel } from './riser-diagram-panel' @@ -109,6 +117,7 @@ import { VectorEdgeExtractor } from './vector-edge-extractor' import { WallMeasurementLabel } from './wall-measurement-label' import { WallMoveSideHandles } from './wall-move-side-handles' import { WallOpeningHighlights } from './wall-opening-highlights' +import { WallRegionHandles } from './wall-region-handles' const CAMERA_CONTROLS_HINT_DISMISSED_STORAGE_KEY = 'editor-camera-controls-hint-dismissed:v1' const PREVIEW_STAGE_SWITCHER_POSITION = @@ -118,12 +127,16 @@ const DELETE_CURSOR_BADGE_OFFSET_X = 14 const DELETE_CURSOR_BADGE_OFFSET_Y = 14 const PAINT_CURSOR_BADGE_COLOR = '#818cf8' const PAINT_CURSOR_BADGE_DISABLED_COLOR = '#94a3b8' +// Neutral: erasing paints no colour. +const ERASE_CURSOR_BADGE_COLOR = '#e4e4e7' const PAINT_CURSOR_BADGE_OFFSET_X = 14 const PAINT_CURSOR_BADGE_OFFSET_Y = 14 const SCENE_READY_FALLBACK_MS = 8000 const PRESENTATION_PROJECT_NOT_RESTORED = Symbol('presentation-project-not-restored') const useClientLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect -type PaintCursorBadgeState = 'empty' | 'ready' | 'blocked' +// `aim`: a region sub-mode off what it draws on — the HUD says where to go; no +// forbidden sign, since nothing is refused. +type PaintCursorBadgeState = 'empty' | 'ready' | 'aim' | 'blocked' const recordEditorRender: ProfilerOnRenderCallback = (_id, _phase, actualDuration) => { if (PERF_OVERLAY_ENABLED) recordPerfSample('react-render', actualDuration) } @@ -131,6 +144,8 @@ const EDITOR_HOVER_STYLES: HoverStyles = { default: { visibleColor: 0x00_aa_ff, hiddenColor: 0xf3_ff_47, strength: 5, pulse: true }, delete: { visibleColor: 0xef_44_44, hiddenColor: 0x99_1b_1b, strength: 6, pulse: false }, 'paint-ready': { visibleColor: 0xf5_9e_0b, hiddenColor: 0xfd_e0_68, strength: 5, pulse: true }, + // Erasing paints nothing: a neutral outline, no paint colour. + 'erase-ready': { visibleColor: 0xe4_e4_e7, hiddenColor: 0xa1_a1_aa, strength: 5, pulse: false }, 'paint-disabled': { visibleColor: 0x94_a3_b8, hiddenColor: 0x47_55_69, @@ -681,26 +696,31 @@ function PaintCursorBadge({ swatchColor, swatchImageUrl, isEraser, + isPicker = false, }: { position: { x: number; y: number } state: PaintCursorBadgeState swatchColor: string swatchImageUrl?: string isEraser: boolean + /** The eyedropper: the swatch is what a click would take. */ + isPicker?: boolean }) { const accentColor = state === 'ready' ? isEraser - ? PAINT_CURSOR_BADGE_COLOR + ? ERASE_CURSOR_BADGE_COLOR : swatchColor : PAINT_CURSOR_BADGE_DISABLED_COLOR - const iconOpacity = state === 'ready' ? 1 : state === 'blocked' ? 0.62 : 0.42 + const iconOpacity = state === 'ready' ? 1 : state === 'blocked' || state === 'aim' ? 0.62 : 0.42 const lineHeight = 18 return ( )} - {!(isVersionPreviewMode || isCaptureMode || isStudioMode) && ( -
- -
- )} - {!isCaptureMode && ( -
- -
- )} + {/* The inspector and the shortcuts card share one right column. */} + } + inspector={ + isVersionPreviewMode || isCaptureMode || isStudioMode ? null : ( + + ) + } + /> {/* Capture mode drives walk / drone from its own overlay, which owns the framing chrome — the walkthrough HUD would both clutter the frame and offer a second, conflicting exit. */} @@ -1731,12 +1792,7 @@ function EditorContent({
-
- -
-
- -
+ } inspector={} /> {isFirstPersonMode && ( useEditor.getState().setFirstPersonMode(false)} /> diff --git a/packages/editor/src/components/editor/node-action-menu.tsx b/packages/editor/src/components/editor/node-action-menu.tsx index 8c8eea59f1..72c1497e76 100644 --- a/packages/editor/src/components/editor/node-action-menu.tsx +++ b/packages/editor/src/components/editor/node-action-menu.tsx @@ -1,10 +1,92 @@ 'use client' import { Icon } from '@iconify/react' -import { Copy, Group, Move, PencilRuler, Search, Spline, Trash2, Ungroup } from 'lucide-react' -import type { MouseEventHandler, PointerEventHandler } from 'react' +import { + Copy, + Group, + Move, + PencilRuler, + RotateCcw, + RotateCw, + Search, + Spline, + Trash2, + Ungroup, +} from 'lucide-react' +import type { MouseEventHandler, PointerEventHandler, ReactNode } from 'react' +import { cn } from '../../lib/utils' +import { shortcutDisplayValue } from '../ui/primitives/shortcut-token' +import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/primitives/tooltip' import { RegistryActionContributions } from './registry-action-contributions' +const BUTTON = + 'rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground' +const DESTRUCTIVE = 'hover:bg-destructive/10 hover:text-destructive' +const DISABLED = 'cursor-not-allowed opacity-40 hover:bg-transparent hover:text-muted-foreground' + +/** + * One button of an action pill, with the editor's tooltip: its name, and the + * keys that do the same where there are any. A disabled button still shows + * its tooltip (it stays hoverable) so it can say why it is off. + */ +export function ActionMenuButton({ + label, + keys, + onClick, + destructive = false, + disabled = false, + disabledReason, + children, +}: { + label: string + /** Keys pressed together, as `ShortcutToken` names them (`Cmd/Ctrl`, `G`). */ + keys?: string[] + onClick?: MouseEventHandler + destructive?: boolean + disabled?: boolean + /** The tooltip while disabled; the label otherwise. */ + disabledReason?: string + children: ReactNode +}) { + return ( + + + + + + {disabled && disabledReason ? disabledReason : label} + {!disabled && keys?.length ? ( + + {keys.map((key) => ( + + {shortcutDisplayValue(key)} + + ))} + + ) : null} + + + ) +} + type NodeActionMenuProps = { onFind?: MouseEventHandler onAddHole?: MouseEventHandler @@ -13,6 +95,9 @@ type NodeActionMenuProps = { onMove?: MouseEventHandler onEditMesh?: MouseEventHandler onCurve?: MouseEventHandler + /** Quarter turns (a room); sit in the Curve slot (a room has no curve). */ + onRotateLeft?: MouseEventHandler + onRotateRight?: MouseEventHandler /** Session group (Ctrl/Cmd+G) — multi-selection floating pill. */ onGroup?: MouseEventHandler /** Dissolve session group (Ctrl/Cmd+Shift+G). */ @@ -21,6 +106,16 @@ type NodeActionMenuProps = { onPointerUp?: PointerEventHandler onPointerEnter?: PointerEventHandler onPointerLeave?: PointerEventHandler + /** + * Buttons a caller contributes next to the registry contributions — for a + * selection that is not a scene-node selection (the room), whose actions the + * registry cannot find. + */ + children?: ReactNode + /** Tooltip / accessible name of the delete button. */ + deleteLabel?: string + /** Shows the delete button greyed out, its tooltip saying why. */ + deleteDisabledReason?: string } export function NodeActionMenu({ @@ -31,12 +126,17 @@ export function NodeActionMenu({ onMove, onEditMesh, onCurve, + onRotateLeft, + onRotateRight, onGroup, onUngroup, onPointerDown, onPointerUp, onPointerEnter, onPointerLeave, + children, + deleteLabel = 'Delete', + deleteDisabledReason, }: NodeActionMenuProps) { return (
{onFind && ( - + )} {onMove && ( - + )} {onEditMesh && ( - + )} {onGroup && ( - + )} {onUngroup && ( - + )} {onCurve && ( - + + )} + {onRotateLeft && ( + + + + )} + {onRotateRight && ( + + + )} + {children} {onDuplicate && ( - + )} {onAddHole && ( - + )} {onDelete && ( - + )}
) diff --git a/packages/editor/src/components/editor/node-arrow-handles.tsx b/packages/editor/src/components/editor/node-arrow-handles.tsx index 1cbffbfe08..ef64befbbb 100644 --- a/packages/editor/src/components/editor/node-arrow-handles.tsx +++ b/packages/editor/src/components/editor/node-arrow-handles.tsx @@ -42,6 +42,7 @@ import { import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js' import { MeshBasicNodeMaterial } from 'three/webgpu' +import { useCeilingEditCeilingId } from '../../lib/ceiling-edit-session' import { EDITOR_LAYER } from '../../lib/constants' import { RESIZE_HANDLE_DRAG_LABEL, ROTATE_HANDLE_DRAG_LABEL } from '../../lib/contextual-help' import { createEditorApi } from '../../lib/editor-api' @@ -241,7 +242,12 @@ export function NodeArrowHandles() { const activeGroup = useHandleGroup((s) => s.active && s.active.nodeId === node?.id ? s.active.group : null, ) - const def = node ? nodeRegistry.get(node.type) : null + // A ceiling's handles belong to its Edit ceiling session; a plain selection shows none. + const editCeilingId = useCeilingEditCeilingId() + const def = + node && (node.type !== 'ceiling' || node.id === editCeilingId) + ? nodeRegistry.get(node.type) + : null const descriptorSceneApi = useMemo(() => createSceneApi(useScene), []) const descriptors = useMemo(() => { if (!(node && def?.handles)) return null diff --git a/packages/editor/src/components/editor/room-controls.tsx b/packages/editor/src/components/editor/room-controls.tsx new file mode 100644 index 0000000000..049b726919 --- /dev/null +++ b/packages/editor/src/components/editor/room-controls.tsx @@ -0,0 +1,846 @@ +'use client' + +import { + type AnyNode, + type AnyNodeId, + DEFAULT_LEVEL_HEIGHT, + deleteZone, + emitter, + type Point, + type StructureNodes, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { getSceneTheme, setSurfaceRaycastLayers, useViewer } from '@pascal-app/viewer' +import { Html } from '@react-three/drei' +import { useFrame, useThree } from '@react-three/fiber' +import { SquareSplitHorizontal } from 'lucide-react' +import Image from 'next/image' +import { type MouseEvent, type RefObject, useEffect, useMemo, useRef, useState } from 'react' +import { createPortal } from 'react-dom' +import { + type Camera, + DoubleSide, + type Group, + Matrix4, + type Mesh, + type Object3D, + type OrthographicCamera, + type PerspectiveCamera, + Raycaster, + Vector2, + Vector3, +} from 'three' +import { markToolCancelConsumed } from '../../hooks/use-keyboard' +import { getRoomSelectionIndex } from '../../hooks/use-selected-room' +import { EDITOR_LAYER } from '../../lib/constants' +import { getFloatingMenuScale } from '../../lib/floating-menu-scale' +import { clientToPlan } from '../../lib/floorplan/plan-coords' +import { formatLinearMeasurement } from '../../lib/measurements' +import { addMezzanineStairs } from '../../lib/mezzanine-stairs' +import { + cancelRoomDivide, + clickRoomDivide, + finishRoomDivide, + previewRoomDivide, + removeLastRoomDividePoint, + roomDivideContains, + startRoomDivide, +} from '../../lib/room-divide-session' +import { roomFloorElevation, useRoomHandleDrag } from '../../lib/room-handle-drag' +import type { RoomSelectionRecord } from '../../lib/room-selection' +import { requestRoomDeletion } from '../../lib/room-structure-commands' +import { + type RoomTransformKind, + rotateRoom, + showRoomNotice, + startRoomTransform, + useRoomTransform, +} from '../../lib/room-transform-session' +import { isTypingTarget } from '../../lib/typing-target' +import useEditor from '../../store/use-editor' +import useInteractionScope from '../../store/use-interaction-scope' +import { useFloorplanRender } from '../editor-2d/floorplan-render-context' +import { CursorSphere } from '../tools/shared/cursor-sphere' +import { + DRAFT_LABEL_Y_OFFSET, + DraftMeasurementLabel, +} from '../tools/shared/draft-measurement-label' +import { getMenuYOffset } from './floating-action-menu' +import { ActionMenuButton, NodeActionMenu } from './node-action-menu' +import { RoomFloorHighlight3D } from './room-floor-highlight' +import { RoomHandleDragPreview3D, RoomHandles3D } from './room-handles' +import { RoomFloorHeightStepper, useRoomControls } from './room-handles-2d' +import { RoomTransformGhost2D, RoomTransformGhost3D } from './room-transform-ghost' + +// The wall draft's colours: indigo while the draft is buildable, red when not. +const DRAFT_COLOR = '#818cf8' +const DRAFT_COLOR_LIGHT_PLAN = '#6366f1' +const INVALID_COLOR = '#ef4444' + +type RoomDivideScope = Extract< + ReturnType['scope'], + { kind: 'room-divide' } +> + +function useSceneIsDark() { + return useViewer((s) => getSceneTheme(s.sceneTheme).appearance === 'dark') +} + +const stopPointer = (event: { stopPropagation: () => void }) => event.stopPropagation() + +/** What a room pick-up carries: its outline and wall footprints, and its floor height. */ +export function roomTransformSource(room: RoomSelectionRecord) { + const walls = room.boundaryWallIds.flatMap((id) => { + const ring = room.context.wallFootprints.get(id) + return ring ? [ring.map(([x, z]) => [x, z] as Point)] : [] + }) + return { + zoneId: room.zoneId, + levelId: room.key.levelId, + outline: [room.polygon, ...room.holes].map((ring) => ring.map(([x, z]) => [x, z] as Point)), + walls, + floorY: roomFloorElevation(useScene.getState().nodes, room.zoneId), + } +} + +/** + * A room's zone picked on its own (its label, the zones layer) moves and + * duplicates as the room: the room pick-up with its real outline and walls, + * never a zone-only drag whose preview is the zone's bounding box. False when + * the zone bounds no room (a free-drawn zone keeps its own move). + */ +export function startZoneRoomTransform(node: AnyNode, kind: RoomTransformKind): boolean { + if (node.type !== 'zone' || !node.parentId) return false + const record = getRoomSelectionIndex(node.parentId) + .update(useScene.getState().nodes) + .find((room) => room.zoneId === node.id) + if (!record) return false + useEditor.getState().setStructureLayer('elements') + useViewer.getState().setSelection({ selectedIds: [], zoneId: null }) + useEditor.getState().selectRoom(record.key) + return startRoomTransform(kind, roomTransformSource(record)) +} + +/** + * Why the room's trash is off, or undefined when it can be deleted: a room + * inside walls other rooms share has nothing of its own to remove. + */ +export function roomDeleteBlockedReason(nodes: StructureNodes, zoneId: string) { + if (nodes[zoneId]?.type !== 'zone') return undefined + const plan = deleteZone(nodes, { zoneId, contents: 'keep' }) + return plan.payload.mode === 'blocked' ? plan.conflicts?.[0]?.message : undefined +} + +/** + * The selected room's action pill — the node action menu every selection + * gets, in a wall pill's order: Move, Rotate left / right (the Curve slot), the room's own + * contribution where a wall shows Split (Divide), Duplicate, + * Delete. + */ +export function RoomActionMenu({ room }: { room: RoomSelectionRecord }) { + const zoneId = room.zoneId + const levelId = room.key.levelId + const nodes = useScene((s) => s.nodes) + const deleteBlocked = useMemo(() => roomDeleteBlockedReason(nodes, zoneId), [nodes, zoneId]) + const pickUp = (kind: 'move' | 'duplicate') => (event: MouseEvent) => { + event.stopPropagation() + startRoomTransform(kind, roomTransformSource(room)) + } + // Alt-click slides a door or window the turn would cut through. + const turn = (direction: 'left' | 'right') => (event: MouseEvent) => { + event.stopPropagation() + rotateRoom(room.key, direction, { force: event.altKey }) + } + const notice = useRoomTransform((s) => (s.notice?.zoneId === zoneId ? s.notice.message : null)) + // A mezzanine moves, turns and copies inside its host (core refuses what + // leaves it); it has no walls to divide, and it gets its own stairs. + const mezzanine = !!room.mezzanine + const addStairs = (event: MouseEvent) => { + event.stopPropagation() + const result = addMezzanineStairs(zoneId) + if (!result.ok) showRoomNotice({ zoneId, message: result.message }) + } + return ( +
+ { + event.stopPropagation() + requestRoomDeletion(zoneId) + }} + onDuplicate={pickUp('duplicate')} + onMove={pickUp('move')} + onPointerDown={stopPointer} + onPointerUp={stopPointer} + onRotateLeft={turn('left')} + onRotateRight={turn('right')} + > + {mezzanine && ( + + + + + + )} + {!mezzanine && ( + ) => { + event.stopPropagation() + startRoomDivide(zoneId, levelId) + }} + > + + + )} + + {notice && ( +
+ {notice} +
+ )} +
+ ) +} + +/** Floats the pill above the room like `FloatingActionMenu` floats a node's. */ +function RoomFloatingMenu({ + room, + zone, + height, +}: { + room: RoomSelectionRecord + zone: AnyNode + height: number +}) { + const isFloorplanHovered = useEditor((s) => s.isFloorplanHovered) + const anchor = useRef(null) + const scale = useRef(null) + const world = useMemo(() => new Vector3(), []) + useFrame(({ camera }) => { + if (!(anchor.current && scale.current)) return + anchor.current.getWorldPosition(world) + scale.current.style.transform = `scale(${getFloatingMenuScale(camera, world)})` + }) + if (zone.type !== 'zone' || !zone.seed || isFloorplanHovered) return null + // A mezzanine's pill floats over its host's walls, not a storey above its own floor. + const elevation = zone.floor?.support === 'open' ? 0.05 : (zone.floor?.elevation ?? 0.05) + return ( + + +
+ +
+ +
+ ) +} + +/** + * The 2D pill: above the room's footprint, like a slab's on the plan, with the + * floor height stepper under it. Shown while the room is selected and the plan + * is on screen — not only while it is hovered, so split view does not flicker. + */ +function RoomFloorplanMenu({ + room, + plan, +}: { + room: RoomSelectionRecord + plan: RefObject +}) { + const planShown = useEditor((s) => s.viewMode !== '3d') + const [position, setPosition] = useState<{ left: number; top: number } | null>(null) + const rings = room.geometry.clearPolygon + useEffect(() => { + if (!planShown) { + setPosition(null) + return + } + let raf = 0 + const tick = () => { + raf = requestAnimationFrame(tick) + const group = plan.current + const svg = group?.ownerSVGElement + const ctm = group?.getScreenCTM() + if (!(svg && ctm)) return setPosition(null) + let minX = Number.POSITIVE_INFINITY + let maxX = Number.NEGATIVE_INFINITY + let top = Number.POSITIVE_INFINITY + const point = svg.createSVGPoint() + for (const { outer } of rings) + for (const [x, y] of outer) { + point.x = x + point.y = y + const screen = point.matrixTransform(ctm) + minX = Math.min(minX, screen.x) + maxX = Math.max(maxX, screen.x) + top = Math.min(top, screen.y) + } + const next = Number.isFinite(top) ? { left: (minX + maxX) / 2, top } : null + setPosition((prev) => + prev && next && Math.abs(prev.left - next.left) < 0.5 && Math.abs(prev.top - next.top) < 0.5 + ? prev + : next, + ) + } + raf = requestAnimationFrame(tick) + return () => cancelAnimationFrame(raf) + }, [planShown, plan, rings]) + if (!(planShown && position) || typeof document === 'undefined') return null + return createPortal( +
+
+ + +
+
, + document.body, + ) +} + +/** + * Where a divide pointer landed. `boundaryId` is set when the pointer resolved + * against a boundary's own surface rather than a free point on the floor. + */ +export type DividePointerTarget = { point: Point; boundaryId?: string } + +/** Keys typed into a field never reach the Divide draft. */ +export const isDivideTypingTarget = isTypingTarget + +function divideKey(event: KeyboardEvent) { + if (useInteractionScope.getState().scope.kind !== 'room-divide') return + if (event.defaultPrevented || isDivideTypingTarget(event.target)) return + if (event.key === 'Escape') cancelRoomDivide() + else if (event.key === 'Backspace') removeLastRoomDividePoint() + else if (event.key === 'Enter') finishRoomDivide() + else return + event.preventDefault() + event.stopPropagation() +} + +// One keyboard listener per target however many surfaces bind to it: split +// view mounts the 2D and 3D controls together, and each key must act once. +const keyboardOwners = new WeakMap() +function acquireDivideKeyboard(target: EventTarget) { + const owners = keyboardOwners.get(target) ?? 0 + if (owners === 0) target.addEventListener('keydown', divideKey as EventListener, true) + keyboardOwners.set(target, owners + 1) + let released = false + return () => { + if (released) return + released = true + const left = (keyboardOwners.get(target) ?? 1) - 1 + keyboardOwners.set(target, left) + if (left === 0) target.removeEventListener('keydown', divideKey as EventListener, true) + } +} + +export function bindDividePointer( + surface: EventTarget, + resolve: (event: PointerEvent) => DividePointerTarget | null, + keyboard: EventTarget = window, +) { + let pressed: number | null = null + // Pointer moves are coalesced to one preview per animation frame; a press + // drops the pending move and previews its own position at once. + let frame = 0 + let pending: PointerEvent | null = null + const flush = () => { + frame = 0 + const event = pending + pending = null + if (!event || useInteractionScope.getState().scope.kind !== 'room-divide') return + const target = resolve(event) + if (target) previewRoomDivide(target.point, target.boundaryId) + } + const dropPending = () => { + if (frame) cancelAnimationFrame(frame) + frame = 0 + pending = null + } + const move = (event: PointerEvent) => { + if (useInteractionScope.getState().scope.kind !== 'room-divide') return + pending = event + if (!frame) frame = requestAnimationFrame(flush) || 0 + } + const down = (event: PointerEvent) => { + if (event.button !== 0 || useInteractionScope.getState().scope.kind !== 'room-divide') return + const target = resolve(event) + if (!target) return + dropPending() + event.preventDefault() + event.stopPropagation() + previewRoomDivide(target.point, target.boundaryId) + pressed = event.pointerId + } + const up = (event: PointerEvent) => { + if (pressed !== event.pointerId) return + pressed = null + dropPending() + event.preventDefault() + event.stopPropagation() + useViewer.getState().setInputDragging(true) + clickRoomDivide() + setTimeout(() => useViewer.getState().setInputDragging(false), 0) + } + const onMove = (event: Event) => move(event as PointerEvent) + const onDown = (event: Event) => down(event as PointerEvent) + surface.addEventListener('pointermove', onMove, true) + surface.addEventListener('pointerdown', onDown, true) + keyboard.addEventListener('pointerup', up as EventListener, true) + const releaseKeyboard = acquireDivideKeyboard(keyboard) + return () => { + dropPending() + surface.removeEventListener('pointermove', onMove, true) + surface.removeEventListener('pointerdown', onDown, true) + keyboard.removeEventListener('pointerup', up as EventListener, true) + releaseKeyboard() + } +} + +/** + * Escape (`tool:cancel`) ends the draft and is consumed, so the tool stays; + * the surface unmounting ends it too. Everything else — leaving the structure + * select tool or the room, another level, a selection change, a boundary + * change under it, any history command — is the gesture lifecycle owner's + * (`startRoomDivide`). + */ +export function useDivideLifetime() { + useEffect(() => { + const onToolCancel = () => { + if (useInteractionScope.getState().scope.kind !== 'room-divide') return + cancelRoomDivide() + markToolCancelConsumed() + } + emitter.on('tool:cancel', onToolCancel) + return () => { + emitter.off('tool:cancel', onToolCancel) + cancelRoomDivide() + } + }, []) +} + +/** + * Where a Divide pointer lands in 3D: the ray (level space) meets the room's + * floor plane. Walls never answer — the room's floor is drawn on top of them + * for the session, so a point behind a near wall is placed where the user + * sees it; the session snaps onto the room's edges within its capture. + */ +export function divideFloorPoint( + origin: readonly [number, number, number], + direction: readonly [number, number, number], + elevation: number, +): Point | null { + if (Math.abs(direction[1]) < 1e-9) return null + const t = (elevation - origin[1]) / direction[1] + if (!(t > 0) || !Number.isFinite(t)) return null + return [origin[0] + direction[0] * t, origin[2] + direction[2] * t] +} + +/** The live segment: from the last placed point to the pointer's point. */ +function liveSegment(scope: RoomDivideScope): [Point, Point] | null { + const from = scope.points.at(-1) + return from && scope.end ? [from, scope.end] : null +} + +/** What the draft label reads: the live segment's length, or why it cannot be built. */ +function useDivideLabel(scope: RoomDivideScope) { + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + if (!scope.valid) return scope.message ?? null + const live = liveSegment(scope) + if (!live) return null + const length = Math.hypot(live[1][0] - live[0][0], live[1][1] - live[0][1]) + return length > 0.01 ? formatLinearMeasurement(length, unit, metricNotation) : null +} + +function labelPoint(scope: RoomDivideScope): Point | null { + const live = liveSegment(scope) + if (!scope.valid) return scope.end + return live ? [(live[0][0] + live[1][0]) / 2, (live[0][1] + live[1][1]) / 2] : null +} + +// The draft draws over the room's floor highlight (998 / 999), which draws +// over every wall, so the line and its points stay readable wherever they are. +const DRAFT_RENDER_ORDER = 1000 +const noRaycast = () => {} +/** The line's and a point's size on screen, however far the camera is. */ +const STRIP_WIDTH_PX = 3 +const VERTEX_RADIUS_PX = 7 +const STRIP_MIN_WIDTH = 0.06 +const VERTEX_MIN_RADIUS = 0.16 + +const scratch = new Vector3() +const cameraScratch = new Vector3() + +/** World metres one screen pixel spans at `object`'s origin. */ +function metresPerPixel(object: Object3D, camera: Camera, viewportHeight: number) { + if (viewportHeight <= 0) return 0 + if ((camera as OrthographicCamera).isOrthographicCamera) { + const ortho = camera as OrthographicCamera + return (ortho.top - ortho.bottom) / ortho.zoom / viewportHeight + } + const perspective = camera as PerspectiveCamera + const distance = perspective + .getWorldPosition(cameraScratch) + .distanceTo(object.getWorldPosition(scratch)) + return (2 * distance * Math.tan((perspective.fov * Math.PI) / 360)) / viewportHeight +} + +function DraftStrip({ + from, + to, + color, + elevation, +}: { + from: Point + to: Point + color: string + elevation: number +}) { + const ref = useRef(null) + useFrame(({ camera, size }) => { + const mesh = ref.current + if (!mesh) return + mesh.scale.z = Math.max( + STRIP_MIN_WIDTH, + STRIP_WIDTH_PX * metresPerPixel(mesh, camera, size.height), + ) + }) + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) + if (length < 0.01) return null + return ( + + + + + ) +} + +/** A placed point: a solid dot in a soft ring, flat on the floor, over the highlight. */ +function DraftVertex({ at, color, elevation }: { at: Point; color: string; elevation: number }) { + const ref = useRef(null) + useFrame(({ camera, size }) => { + const group = ref.current + if (!group) return + const radius = Math.max( + VERTEX_MIN_RADIUS, + VERTEX_RADIUS_PX * metresPerPixel(group, camera, size.height), + ) + group.scale.setScalar(radius) + }) + return ( + + + + + + + + + + + ) +} + +/** A pointer off the room reads grey (not the red of a refused cut). */ +const OUTSIDE_COLOR = '#94a3b8' + +/** Whether the live point sits off the room: not on its edge, not inside it. */ +export function divideEndOutside(scope: RoomDivideScope): boolean { + if (!scope.end || scope.endKind === 'edge' || scope.endKind === 'close') return false + if (scope.endKind === 'start' && scope.endBoundaryId) return false + return !roomDivideContains(scope.end) +} + +/** The divide draft in 3D, drawn like a wall draft: cursor beam, strips, length. */ +function RoomDividePreview3D({ + scope, + elevation, + height, +}: { + scope: RoomDivideScope + elevation: number + height: number +}) { + const isDark = useSceneIsDark() + const label = useDivideLabel(scope) + const liveColor = scope.valid ? DRAFT_COLOR : INVALID_COLOR + const outside = divideEndOutside(scope) + const live = liveSegment(scope) + const at = labelPoint(scope) + const { points, end } = scope + return ( + + {points.map((point, index) => ( + + ))} + {points.slice(1).map((point, index) => ( + + ))} + {live && } + {end && ( + } + /> + )} + {label && at && ( + + )} + + ) +} + +export function RoomControls3D() { + const room = useRoomControls() + const scope = useInteractionScope((s) => s.scope) + const active = scope.kind === 'room-divide' ? scope : null + const handleDrag = useRoomHandleDrag((s) => s.drag) + const isFloorplanHovered = useEditor((s) => s.isFloorplanHovered) + const levelId = active?.levelId ?? room?.key.levelId ?? handleDrag?.levelId + const zoneId = active?.nodeId ?? room?.zoneId + const zone = useScene((s) => (zoneId ? s.nodes[zoneId as AnyNodeId] : undefined)) + const levelHeight = useScene((s) => { + const level = levelId ? s.nodes[levelId as AnyNodeId] : undefined + return level?.type === 'level' ? (level.height ?? DEFAULT_LEVEL_HEIGHT) : DEFAULT_LEVEL_HEIGHT + }) + const elevation = zone?.type === 'zone' ? (zone.floor?.elevation ?? 0.05) : 0.05 + const root = useRef(null) + const { gl, camera, invalidate } = useThree() + useDivideLifetime() + useEffect( + () => + bindDividePointer(gl.domElement, (event) => { + const current = useInteractionScope.getState().scope + if (current.kind !== 'room-divide' || event.target !== gl.domElement) return null + const level = sceneRegistry.nodes.get(current.levelId) + if (!level) return null + level.updateWorldMatrix(true, false) + const inverse = new Matrix4().copy(level.matrixWorld).invert() + const bounds = gl.domElement.getBoundingClientRect() + const raycaster = new Raycaster() + raycaster.setFromCamera( + new Vector2( + ((event.clientX - bounds.left) / bounds.width) * 2 - 1, + 1 - ((event.clientY - bounds.top) / bounds.height) * 2, + ), + camera, + ) + setSurfaceRaycastLayers(raycaster.layers) + const ray = raycaster.ray.clone().applyMatrix4(inverse) + const point = divideFloorPoint( + [ray.origin.x, ray.origin.y, ray.origin.z], + [ray.direction.x, ray.direction.y, ray.direction.z], + elevation, + ) + return point ? { point } : null + }), + [gl, camera, elevation], + ) + useFrame(() => { + const level = levelId ? sceneRegistry.nodes.get(levelId) : null + if (!root.current) return + root.current.visible = !!level + if (level) { + level.updateWorldMatrix(true, false) + root.current.matrix.copy(level.matrixWorld) + } + }) + return ( + <> + + {typeof document !== 'undefined' && room && zone && ( + + )} + {room && !isFloorplanHovered && } + + {active && ( + + )} + {active && ( + + )} + + + + ) +} + +export function resolveRoomDividePlanPoint( + clientX: number, + clientY: number, +): DividePointerTarget | null { + const point = clientToPlan(clientX, clientY) + return point ? { point: [point[0], point[1]] } : null +} + +// The plan's draft cursor marker: a soft glow under a solid core, in pixels. +const MARKER_GLOW_PX = 10 +const MARKER_CORE_PX = 3 + +function PlanMarker({ at, color, upp }: { at: Point; color: string; upp: number }) { + return ( + <> + + + + ) +} + +/** The divide draft on the plan, drawn like the plan's wall draft. */ +function RoomDividePreview2D({ scope }: { scope: RoomDivideScope }) { + const context = useFloorplanRender() + const isDark = useSceneIsDark() + const label = useDivideLabel(scope) + const upp = context?.unitsPerPixel ?? 0.01 + const draft = isDark ? DRAFT_COLOR : DRAFT_COLOR_LIGHT_PLAN + const liveColor = scope.valid ? draft : INVALID_COLOR + const live = liveSegment(scope) + const at = labelPoint(scope) + const { points, end } = scope + return ( + + {points.length > 1 && ( + point.join(',')).join(' ')} + stroke={draft} + strokeLinecap="round" + strokeLinejoin="round" + strokeWidth={2 * upp} + /> + )} + {live && ( + + )} + {points.map((point, index) => ( + + ))} + {end && } + {label && at && ( + + + {label} + + + )} + + ) +} + +export function RoomControls2D({ levelId }: { levelId: string | null }) { + const room = useRoomControls() + const scope = useInteractionScope((s) => s.scope) + const active = scope.kind === 'room-divide' && scope.levelId === levelId ? scope : null + const ref = useRef(null) + useDivideLifetime() + useEffect(() => { + const svg = ref.current?.ownerSVGElement + if (!svg) return + return bindDividePointer(svg, (event) => { + if (!(event.target instanceof Element) || event.target.closest('foreignObject')) return null + return resolveRoomDividePlanPoint(event.clientX, event.clientY) + }) + }, []) + return ( + + {room && room.key.levelId === levelId && } + {active && } + + + ) +} diff --git a/packages/editor/src/components/editor/room-floor-highlight.tsx b/packages/editor/src/components/editor/room-floor-highlight.tsx new file mode 100644 index 0000000000..ec7daa844d --- /dev/null +++ b/packages/editor/src/components/editor/room-floor-highlight.tsx @@ -0,0 +1,128 @@ +'use client' + +import { type Point, useScene } from '@pascal-app/core' +import { useEffect, useMemo } from 'react' +import { + BufferGeometry, + DoubleSide, + Float32BufferAttribute, + Path, + Shape, + ShapeGeometry, + Vector2, +} from 'three' +import { MeshBasicNodeMaterial } from 'three/webgpu' +import { getRoomSelectionIndex } from '../../hooks/use-selected-room' +import { EDITOR_LAYER } from '../../lib/constants' + +const HIGHLIGHT_COLOR = '#818cf8' +/** Half width (m) of the outline ribbon. */ +const OUTLINE_HALF_WIDTH = 0.025 +/** Above the plane it marks, so the floor under it never z-fights. */ +const LIFT = 0.004 + +const fillMaterial = new MeshBasicNodeMaterial({ + color: HIGHLIGHT_COLOR, + depthTest: false, + depthWrite: false, + opacity: 0.2, + side: DoubleSide, + transparent: true, +}) +const edgeMaterial = new MeshBasicNodeMaterial({ + color: HIGHLIGHT_COLOR, + depthTest: false, + depthWrite: false, + opacity: 0.95, + side: DoubleSide, + transparent: true, +}) +const noRaycast = () => {} + +/** Flat quads along each ring edge: a line WebGPU draws at a real width. */ +function outlineRibbon(rings: readonly (readonly Point[])[], halfWidth: number) { + const positions: number[] = [] + for (const ring of rings) + for (let i = 0; i < ring.length; i++) { + const a = ring[i]! + const b = ring[(i + 1) % ring.length]! + const length = Math.hypot(b[0] - a[0], b[1] - a[1]) + if (length < 1e-9) continue + const nx = (-(b[1] - a[1]) / length) * halfWidth + const nz = ((b[0] - a[0]) / length) * halfWidth + const [p0, p1, p2, p3] = [ + [a[0] + nx, a[1] + nz], + [b[0] + nx, b[1] + nz], + [b[0] - nx, b[1] - nz], + [a[0] - nx, a[1] - nz], + ] as const + for (const [x, z] of [p0, p1, p2, p0, p2, p3]) positions.push(x, 0, z) + } + return new BufferGeometry().setAttribute('position', new Float32BufferAttribute(positions, 3)) +} + +/** + * A room's clear floor drawn on top of every wall (depth test off): a subtle + * fill and a strong outline, holes included, at `elevation` in the level + * frame — the plane a draft in that room lands on (Divide on the floor, Add + * mezzanine on the mezzanine's plane), so the user always sees whether the + * pointer is inside the room without any wall being cut away. + */ +export function RoomFloorHighlight3D({ + levelId, + zoneId, + elevation, + renderOrder = 998, +}: { + levelId: string + zoneId: string + elevation: number + /** The fill's order; the outline draws one above it. */ + renderOrder?: number +}) { + const nodes = useScene((s) => s.nodes) + const geometry = useMemo(() => { + const record = getRoomSelectionIndex(levelId) + .update(nodes) + .find((room) => room.zoneId === zoneId) + if (!record) return null + const shapes = record.clearPolygon.map(({ outer, holes }) => { + const shape = new Shape(outer.map(([x, z]) => new Vector2(x, z))) + shape.holes = holes.map((hole) => new Path(hole.map(([x, z]) => new Vector2(x, z)))) + return shape + }) + return { + fill: new ShapeGeometry(shapes).rotateX(Math.PI / 2), + outline: outlineRibbon( + record.clearPolygon.flatMap(({ outer, holes }) => [outer, ...holes]), + OUTLINE_HALF_WIDTH, + ), + } + }, [nodes, levelId, zoneId]) + useEffect( + () => () => { + geometry?.fill.dispose() + geometry?.outline.dispose() + }, + [geometry], + ) + if (!geometry) return null + return ( + + + + + ) +} diff --git a/packages/editor/src/components/editor/room-handles-2d.tsx b/packages/editor/src/components/editor/room-handles-2d.tsx new file mode 100644 index 0000000000..f7c83036ed --- /dev/null +++ b/packages/editor/src/components/editor/room-handles-2d.tsx @@ -0,0 +1,354 @@ +'use client' + +import { type FloorplanGeometry, type Point, roomDrawnFloor, useScene } from '@pascal-app/core' +import { useViewer } from '@pascal-app/viewer' +import { Minus, Plus } from 'lucide-react' +import { type PointerEvent as ReactPointerEvent, useMemo, useState } from 'react' +import { useSelectedRoom } from '../../hooks/use-selected-room' +import { formatLinearMeasurement, MEASUREMENT_FLOORPLAN_COLOR } from '../../lib/measurements' +import { + commitRoomFloorElevation, + roomRelativeFloorHeight, + stepRoomFloorElevation, +} from '../../lib/room-construction-commands' +import { + type MezzanineEdgeHandle, + mezzanineEdgeHandles, + type RoomHandleDrag, + roomPushHandles, + runFloorplanMezzanineEdge, + runFloorplanRoomPush, + useRoomHandleDrag, + type WallPushHandle, +} from '../../lib/room-handle-drag' +import type { RoomDimension } from '../../lib/room-push-dimensions' +import useEditor from '../../store/use-editor' +import useInteractionScope from '../../store/use-interaction-scope' +import { useFloorplanRender } from '../editor-2d/floorplan-render-context' +import { FloorplanGeometryRenderer } from '../editor-2d/renderers/floorplan-geometry-renderer' +import { suppressBoxSelectForPointer } from '../tools/select/box-select-state' +import { formatMeasurement } from './measurement-pill' +import { ActionMenuButton } from './node-action-menu' + +/** + * The selected room while its controls may show: structure select, nothing + * in progress, no element drilled into, the scene editable. + */ +export function useRoomControls() { + const room = useSelectedRoom() + const enabled = useEditor((s) => s.phase === 'structure' && s.mode === 'select') + const idle = useInteractionScope((s) => s.scope.kind === 'idle') + const readOnly = useScene((s) => s.readOnly) + const sole = useViewer((s) => s.selection.selectedIds.length === 0) + return enabled && idle && sole && !readOnly ? room : null +} + +/** A room floor's step on the plan's Floor height stepper, m. */ +export const FLOOR_HEIGHT_STEP = 0.05 + +function signed(text: string, value: number) { + return `${value > 0.0005 ? '+' : value < -0.0005 ? '−' : ''}${text}` +} + +/** + * The plan has no vertical drag: the room pill carries the floor's height + * above the floor it is measured from, in 5 cm steps, shown even at 0 — the + * 3D elevation handle's clamp and commit, one undo step a click. + */ +export function RoomFloorHeightStepper({ zoneId }: { zoneId: string }) { + const nodes = useScene((s) => s.nodes) + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + // A drawn-slab floor's height is the slab's: the room has no height to step. + if (roomDrawnFloor(nodes, zoneId)) return null + const height = roomRelativeFloorHeight(nodes, zoneId) + const down = stepRoomFloorElevation(nodes, zoneId, -FLOOR_HEIGHT_STEP) + const up = stepRoomFloorElevation(nodes, zoneId, FLOOR_HEIGHT_STEP) + const step = (next: number | null) => (event: { stopPropagation: () => void }) => { + event.stopPropagation() + if (next !== null) + commitRoomFloorElevation(zoneId, next, (meters) => + formatLinearMeasurement(meters, unit, metricNotation), + ) + } + return ( +
event.stopPropagation()} + onPointerUp={(event) => event.stopPropagation()} + > + Floor height + + + + + {signed(formatMeasurement(Math.abs(height), unit, metricNotation), height)} + + + + +
+ ) +} + +// The plan's push arrow: the wall arrows' shape and indigo, in plan metres. +const SHAFT = 0.1 +const HEAD = 0.12 +const SHAFT_HALF = 0.04 +const HEAD_HALF = 0.1 +const INSET = 0.03 +const ARROW_PATH = `M ${INSET},${-SHAFT_HALF} L ${INSET + SHAFT},${-SHAFT_HALF} L ${INSET + SHAFT},${-HEAD_HALF} L ${INSET + SHAFT + HEAD},0 L ${INSET + SHAFT},${HEAD_HALF} L ${INSET + SHAFT},${SHAFT_HALF} L ${INSET},${SHAFT_HALF} Z` +const ARROW_FILL = '#8381ed' +const ARROW_HOVER_FILL = '#a5b4fc' + +function PlanArrow({ + position, + outward, + kind, + onPointerDown, +}: { + position: Point + outward: Point + kind: 'room-push' | 'mezzanine-edge' + onPointerDown: (event: ReactPointerEvent) => void +}) { + const [hover, setHover] = useState(false) + const angle = (Math.atan2(outward[1], outward[0]) * 180) / Math.PI + return ( + event.stopPropagation()} + transform={`translate(${position[0]} ${position[1]}) rotate(${angle})`} + > + + setHover(true)} + onPointerLeave={() => setHover(false)} + pointerEvents="fill" + style={{ cursor: 'grab' }} + /> + + ) +} + +function startArrow(event: ReactPointerEvent, run: () => unknown) { + if (event.button !== 0) return + event.preventDefault() + event.stopPropagation() + suppressBoxSelectForPointer(event) + run() +} + +/** + * The selected room's arrows on the plan: one push/pull chevron per boundary + * span (on the far face, along the normal the handle supplies) and, for a + * mezzanine, one per plate edge. Mounted after every node's handles so a + * wall outline never takes the press. The drags are the 3D arrows' own. + */ +export function RoomHandles2D({ levelId }: { levelId: string | null }) { + const room = useRoomControls() + const nodes = useScene((s) => s.nodes) + const onLevel = !!room && room.key.levelId === levelId + const handles = useMemo( + () => (onLevel && room ? roomPushHandles(nodes, room.spans) : []), + [nodes, onLevel, room], + ) + const edges = useMemo( + () => (onLevel && room?.mezzanine ? mezzanineEdgeHandles(nodes, room.zoneId) : []), + [nodes, onLevel, room], + ) + if (!(onLevel && room)) return null + const push = (handle: WallPushHandle) => (event: ReactPointerEvent) => + startArrow(event, () => + runFloorplanRoomPush({ + handle, + levelId: room.key.levelId, + zoneId: room.zoneId, + clientX: event.clientX, + clientY: event.clientY, + }), + ) + const edge = (handle: MezzanineEdgeHandle) => (event: ReactPointerEvent) => + startArrow(event, () => + runFloorplanMezzanineEdge({ + handle, + levelId: room.key.levelId, + zoneId: room.zoneId, + clientX: event.clientX, + clientY: event.clientY, + }), + ) + return ( + + {handles.map((handle) => ( + + ))} + {edges.map((handle) => ( + + ))} + + ) +} + +const READOUT_HEIGHT_PX = 24 +const READOUT_CHAR_PX = 6.6 +const READOUT_PAD_PX = 12 + +/** A drag's readout pill on the plan, upright and screen-sized, at `at`. */ +function PlanReadout({ at, text, refused }: { at: Point; text: string; refused: boolean }) { + const context = useFloorplanRender() + const upp = context?.unitsPerPixel ?? 0.01 + const width = text.length * READOUT_CHAR_PX + READOUT_PAD_PX * 2 + return ( + + + + {text} + + + ) +} + +/** + * A push's live room widths on the plan, drawn as the measurement tool draws a + * distance: indigo line, end dots, outlined label along the line. + */ +function PlanRoomDimensions({ dimensions }: { dimensions: RoomDimension[] }) { + const context = useFloorplanRender() + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + const geometry = useMemo( + () => ({ + kind: 'group', + children: dimensions.flatMap(({ from, to, distance }): FloorplanGeometry[] => [ + { + kind: 'line', + x1: from[0], + y1: from[1], + x2: to[0], + y2: to[1], + stroke: MEASUREMENT_FLOORPLAN_COLOR, + strokeWidth: 2, + strokeLinecap: 'round', + vectorEffect: 'non-scaling-stroke', + }, + ...[from, to].map( + ([cx, cy]): FloorplanGeometry => ({ + kind: 'circle', + cx, + cy, + r: 0.045, + fill: MEASUREMENT_FLOORPLAN_COLOR, + }), + ), + { + kind: 'dimension-label', + appearance: 'outlined', + cx: (from[0] + to[0]) / 2, + cy: (from[1] + to[1]) / 2, + text: formatLinearMeasurement(distance, unit, metricNotation), + angle: Math.atan2(to[1] - from[1], to[0] - from[0]), + offsetPx: 14, + }, + ]), + }), + [dimensions, unit, metricNotation], + ) + if (!dimensions.length) return null + return ( + + + + ) +} + +type PlanDrag = Extract + +/** + * The room drag in flight on the plan: the signed distance or the refusal at + * the arrow's new spot, and a mezzanine's outline as the push would leave it — + * the plan twin of `RoomHandleDragPreview3D` (the pushed walls and floors + * themselves draw from the live overrides and the wall ghosts). + */ +export function RoomHandleDragPreview2D({ levelId }: { levelId: string | null }) { + const drag = useRoomHandleDrag((s) => s.drag) + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + if (!drag || drag.levelId !== levelId || drag.kind === 'elevation') return null + const plan = drag as PlanDrag + const at: Point = [ + plan.anchor[0] + plan.outward[0] * plan.distance, + plan.anchor[1] + plan.outward[1] * plan.distance, + ] + const text = + plan.message ?? + signed(formatMeasurement(Math.abs(plan.distance), unit, metricNotation), plan.distance) + return ( + + {plan.kind === 'mezzanine-edge' && plan.outline.length >= 3 && ( + `${x},${z}`).join(' ')} + stroke={plan.message ? '#ef4444' : ARROW_FILL} + strokeWidth={1.5} + vectorEffect="non-scaling-stroke" + /> + )} + + + + ) +} diff --git a/packages/editor/src/components/editor/room-handles.tsx b/packages/editor/src/components/editor/room-handles.tsx new file mode 100644 index 0000000000..4cf6660c01 --- /dev/null +++ b/packages/editor/src/components/editor/room-handles.tsx @@ -0,0 +1,675 @@ +'use client' + +import { + clampRoomFloorHandle, + type Point, + roomDrawnFloor, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { useViewer } from '@pascal-app/viewer' +import { Html } from '@react-three/drei' +import { type ThreeEvent, useFrame, useThree } from '@react-three/fiber' +import { useEffect, useMemo, useRef, useState } from 'react' +import { + BufferGeometry, + type Camera, + DoubleSide, + Float32BufferAttribute, + type Group, + OrthographicCamera, + Path, + Plane, + type Raycaster, + Shape, + ShapeGeometry, + Vector2, + Vector3, +} from 'three' +import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' +import { EDITOR_LAYER } from '../../lib/constants' +import { + clearStructuralElevationGuide, + publishStructuralElevationGuide, + resolveStructuralElevationSnap, +} from '../../lib/elevation-guides' +import { formatLinearMeasurement, MEASUREMENT_ACTIVE_COLOR } from '../../lib/measurements' +import { commitRoomFloorElevation, roomFloorBase } from '../../lib/room-construction-commands' +import { + type MezzanineEdgeHandle, + mezzanineEdgeHandles, + mezzanineElevationBounds, + ownFloorElevationBounds, + ROOM_ELEVATION_DRAG_LABEL, + type RoomHandleDrag, + roomFloorElevation, + roomPushHandles, + runMezzanineEdgeDrag, + runRoomHandleDrag, + useRoomHandleDrag, +} from '../../lib/room-handle-drag' +import type { RoomDimension } from '../../lib/room-push-dimensions' +import type { RoomSelectionRecord } from '../../lib/room-selection' +import useEditor, { isGridSnapActive, isMagneticSnapActive } from '../../store/use-editor' +import { suppressBoxSelectForPointer } from '../tools/select/box-select-state' +import { ARROW_COLOR, ARROW_SCALE, HandleArrow } from './handles/handle-arrow' +import { resolveResizeSnapValue } from './handles/resize-snap' +import { formatMeasurement } from './measurement-pill' +import { WallPushArrow } from './wall-push-arrow' + +const PILL = + 'pointer-events-none flex items-center gap-2 whitespace-nowrap rounded-full border border-border/60 bg-background/90 px-4 py-1.5 text-xs tabular-nums shadow-sm backdrop-blur' + +const noRaycast = () => {} + +/** Plan-space centroid of the room's reference outline (the elevation handle's spot). */ +export function outlineCentroid(rings: Point[][]): Point { + const outer = rings[0] ?? [] + let a = 0, + x = 0, + z = 0 + for (let i = 0; i < outer.length; i++) { + const p = outer[i]!, + q = outer[(i + 1) % outer.length]! + const c = p[0] * q[1] - q[0] * p[1] + a += c + x += (p[0] + q[0]) * c + z += (p[1] + q[1]) * c + } + if (Math.abs(a) < 1e-9) + return outer.length + ? [ + outer.reduce((s, p) => s + p[0], 0) / outer.length, + outer.reduce((s, p) => s + p[1], 0) / outer.length, + ] + : [0, 0] + return [x / (3 * a), z / (3 * a)] +} + +type DragPlumbing = { + camera: Camera + raycaster: Raycaster + dom: HTMLCanvasElement + levelId: string +} + +function pointerRay({ camera, raycaster, dom }: DragPlumbing, clientX: number, clientY: number) { + const rect = dom.getBoundingClientRect() + raycaster.setFromCamera( + new Vector2( + ((clientX - rect.left) / rect.width) * 2 - 1, + -((clientY - rect.top) / rect.height) * 2 + 1, + ), + camera, + ) + return raycaster.ray +} + +export function useHandleScale() { + const { camera } = useThree() + return camera instanceof OrthographicCamera ? 1 / camera.zoom : 1 +} + +function ElevationHandle({ + room, + anchor, + elevation, +}: { + room: RoomSelectionRecord + anchor: Point + elevation: number +}) { + const [hover, setHover] = useState(false) + const { camera, raycaster, gl } = useThree() + const zoom = useHandleScale() + const levelId = room.key.levelId + const onPointerDown = (event: ThreeEvent) => { + if (event.button !== 0) return + event.stopPropagation() + suppressBoxSelectForPointer(event) + const level = sceneRegistry.nodes.get(levelId) + if (!level) return + level.updateWorldMatrix(true, false) + const toLocal = level.matrixWorld.clone().invert() + const world = new Vector3(anchor[0], elevation, anchor[1]).applyMatrix4(level.matrixWorld) + const normal = camera.getWorldPosition(new Vector3()).sub(world).setY(0) + if (normal.lengthSq() === 0) return + const plane = new Plane().setFromNormalAndCoplanarPoint(normal.normalize(), world) + const plumbing = { camera, raycaster, dom: gl.domElement, levelId } + const localY = (clientX: number, clientY: number) => { + const hit = pointerRay(plumbing, clientX, clientY).intersectPlane(plane, new Vector3()) + return hit ? hit.applyMatrix4(toLocal).y : null + } + const startY = localY(event.nativeEvent.clientX, event.nativeEvent.clientY) + if (startY === null) return + const source = { nodeId: room.zoneId, levelId, anchor } + const outline = [room.polygon as Point[], ...(room.holes as Point[][])] + let value = elevation + const publish = (next: number) => + useRoomHandleDrag.setState({ + drag: { + kind: 'elevation', + zoneId: room.zoneId, + levelId, + anchor, + outline, + from: elevation, + value: next, + }, + }) + publish(value) + runRoomHandleDrag({ + label: ROOM_ELEVATION_DRAG_LABEL, + nodeId: room.zoneId, + zoneId: room.zoneId, + levelId, + requires: [room.zoneId], + sample: (x, y) => { + const pointerY = localY(x, y) + if (pointerY === null) return null + const nodes = useScene.getState().nodes + const snapped = resolveResizeSnapValue({ + rawValue: elevation + pointerY - startY, + gridSnapEnabled: true, + gridSnapActive: isGridSnapActive(), + gridSnapStep: Math.min(useEditor.getState().gridSnapStep, 0.05), + magneticSnapActive: isMagneticSnapActive(), + magneticSnap: (next) => resolveStructuralElevationSnap(source, next, nodes), + }) + // A mezzanine stays inside the heights core accepts for it; a room on + // its own floor, inside its plate's Floor height range. + const bounds = + mezzanineElevationBounds(nodes, room.zoneId) ?? + ownFloorElevationBounds(nodes, room.zoneId) + return bounds + ? Math.min(bounds.max, Math.max(bounds.min, snapped)) + : clampRoomFloorHandle(nodes, room.zoneId, snapped) + }, + onValue: (next) => { + value = next + publishStructuralElevationGuide(source, next, useScene.getState().nodes) + publish(next) + }, + onCommit: () => { + clearStructuralElevationGuide(room.zoneId) + if (Math.abs(value - elevation) <= 1e-6) return + const { unit, metricNotation } = useViewer.getState() + commitRoomFloorElevation(room.zoneId, value, (meters) => + formatLinearMeasurement(meters, unit, metricNotation), + ) + }, + onCancel: () => clearStructuralElevationGuide(room.zoneId), + }) + } + return ( + + ) +} + +/** + * Centre-to-centre distance (m, before zoom) from the floor cube to each + * chevron: the cube's half size (0.08) + a chevron's half length along its + * axis (0.14 at ARROW_SCALE) + a clear gap wide enough to stay open when a + * camera looking down foreshortens the vertical, so arrow / gap / cube / gap / + * arrow never touch. + */ +const ELEVATION_ARROW_GAP = 0.4 +// The flat chevron tipped to point along ±Y: the duct riser pair's rotation. +const UP_TILT: [number, number, number] = [0, Math.PI / 2, Math.PI / 2] +const DOWN_TILT: [number, number, number] = [0, Math.PI / 2, -Math.PI / 2] + +/** + * The floor's elevation handle: a cube between an up and a down chevron (the + * two-way look of the riser handles). The three share one hover and any of + * them starts the same vertical drag. The chevrons turn to face the camera so + * the plates never go edge-on. + */ +export function ElevationArrows({ + anchor, + hover, + zoom, + onHoverChange, + onPointerDown, +}: { + anchor: [number, number, number] + hover: boolean + zoom: number + onHoverChange: (hover: boolean) => void + onPointerDown: (event: ThreeEvent) => void +}) { + const group = useRef(null) + const { camera } = useThree() + const cameraPosition = useMemo(() => new Vector3(), []) + useFrame(() => { + const root = group.current + if (!root) return + const local = root.parent + ? root.parent.worldToLocal(camera.getWorldPosition(cameraPosition)) + : camera.getWorldPosition(cameraPosition) + root.rotation.y = Math.atan2(local.x - anchor[0], local.z - anchor[2]) + }) + // Moving between the cube and a chevron must not drop the shared hover. + const hovered = useRef(new Set()) + const hoverPart = (part: string) => (next: boolean) => { + if (next) hovered.current.add(part) + else hovered.current.delete(part) + onHoverChange(hovered.current.size > 0) + } + const gap = ELEVATION_ARROW_GAP * zoom + const baseScale = zoom * ARROW_SCALE + return ( + + + {[ + { key: 'up', y: gap, tilt: UP_TILT }, + { key: 'down', y: -gap, tilt: DOWN_TILT }, + ].map((arrow) => ( + + ))} + + ) +} + +/** + * A selected room's 3D handles: the floor elevation tracker at its centroid + * and one push/pull arrow outside every boundary wall. Rendered in the level + * frame by `RoomControls3D`, only while nothing else is in progress. + */ +export function RoomHandles3D({ room }: { room: RoomSelectionRecord }) { + const nodes = useScene((s) => s.nodes) + const elevation = roomFloorElevation(nodes, room.zoneId) + // A drawn-slab floor's height is the slab's: the room has no height to drag. + const drawnFloor = roomDrawnFloor(nodes, room.zoneId) !== null + const anchor = useMemo( + () => outlineCentroid([room.polygon as Point[], ...(room.holes as Point[][])]), + [room.polygon, room.holes], + ) + const handles = useMemo(() => roomPushHandles(nodes, room.spans), [nodes, room.spans]) + // A mezzanine has no walls: its plate edges carry the push arrows instead. + const edges = useMemo( + () => (room.mezzanine ? mezzanineEdgeHandles(nodes, room.zoneId) : []), + [nodes, room.mezzanine, room.zoneId], + ) + return ( + + {!drawnFloor && } + {edges.map((handle) => ( + + ))} + {handles.map((handle) => ( + + ))} + + ) +} + +/** The drag in flight: the value pill, and for elevation the floor at its new height. */ +type MezzanineEdgeDrag = Extract + +const edgeFill = (color: string) => + new MeshBasicNodeMaterial({ + color, + depthTest: false, + depthWrite: false, + opacity: 0.25, + side: DoubleSide, + transparent: true, + }) +const mezzanineEdgeValidFill = edgeFill(ARROW_COLOR) +const mezzanineEdgeRefusedFill = edgeFill('#ef4444') + +/** The mezzanine outline an edge push would leave, at plate height, red with its label when refused. */ +function MezzanineEdgeDragPreview({ drag }: { drag: MezzanineEdgeDrag }) { + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + const geometry = useMemo(() => { + if (drag.outline.length < 3) return null + const shape = new Shape(drag.outline.map(([x, z]) => new Vector2(x, z))) + return new ShapeGeometry(shape).rotateX(Math.PI / 2) + }, [drag.outline]) + useEffect(() => () => geometry?.dispose(), [geometry]) + const at: Point = [ + drag.anchor[0] + drag.outward[0] * drag.distance, + drag.anchor[1] + drag.outward[1] * drag.distance, + ] + const magnitude = formatMeasurement(Math.abs(drag.distance), unit, metricNotation) + const signed = `${drag.distance > 0 ? '+' : drag.distance < 0 ? '−' : ''}${magnitude}` + return ( + + + {geometry && ( + + )} + +
+ {drag.message ? ( + {drag.message} + ) : ( + {signed} + )} +
+ +
+ ) +} + +const dimensionLine = new LineBasicNodeMaterial({ + color: MEASUREMENT_ACTIVE_COLOR, + depthTest: false, + depthWrite: false, +}) +/** Half length (m) of the cross tick closing each end of a room dimension. */ +const DIMENSION_TICK = 0.1 +const DIMENSION_LABEL_OUTLINE = [ + [-1, -1], + [1, -1], + [-1, 1], + [1, 1], +] + .map(([x, y]) => `${x}px ${y}px 0 ${MEASUREMENT_ACTIVE_COLOR}`) + .join(', ') + +/** + * A push's live room widths: one measurement-tool line per dimension, just + * above its room's floor and drawn over the walls, closed by cross ticks, with + * the measurement's outlined label — apart from the moved-distance pill. + */ +function RoomDimensionLines3D({ dimensions }: { dimensions: RoomDimension[] }) { + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + const geometry = useMemo(() => { + if (!dimensions.length) return null + const positions: number[] = [] + for (const { from, to, elevation: y } of dimensions) { + const length = Math.hypot(to[0] - from[0], to[1] - from[1]) || 1 + const tx = (-(to[1] - from[1]) / length) * DIMENSION_TICK + const tz = ((to[0] - from[0]) / length) * DIMENSION_TICK + positions.push(from[0], y, from[1], to[0], y, to[1]) + for (const [x, z] of [from, to]) positions.push(x - tx, y, z - tz, x + tx, y, z + tz) + } + return new BufferGeometry().setAttribute('position', new Float32BufferAttribute(positions, 3)) + }, [dimensions]) + useEffect(() => () => geometry?.dispose(), [geometry]) + if (!geometry) return null + return ( + + + {dimensions.map((dimension) => ( + +
+ {formatMeasurement(dimension.distance, unit, metricNotation)} +
+ + ))} +
+ ) +} + +/** A mezzanine edge's push arrow: the room push arrow's look, driving `setZoneEdges`. */ +function MezzanineEdgeArrow({ + handle, + zoneId, + levelId, +}: { + handle: MezzanineEdgeHandle + zoneId: string + levelId: string +}) { + const [hover, setHover] = useState(false) + const { camera, raycaster, gl } = useThree() + const zoom = useHandleScale() + const onPointerDown = (event: ThreeEvent) => { + if (event.button !== 0) return + event.stopPropagation() + suppressBoxSelectForPointer(event) + const level = sceneRegistry.nodes.get(levelId) + if (!level) return + level.updateWorldMatrix(true, false) + const toLocal = level.matrixWorld.clone().invert() + const origin = new Vector3(handle.position[0], handle.height, handle.position[1]).applyMatrix4( + level.matrixWorld, + ) + const up = new Vector3(0, 1, 0).transformDirection(level.matrixWorld) + const plane = new Plane().setFromNormalAndCoplanarPoint(up, origin) + const plumbing = { camera, raycaster, dom: gl.domElement, levelId } + const along = (clientX: number, clientY: number) => { + const hit = pointerRay(plumbing, clientX, clientY).intersectPlane(plane, new Vector3()) + if (!hit) return null + const local = hit.applyMatrix4(toLocal) + return ( + (local.x - handle.position[0]) * handle.outward[0] + + (local.z - handle.position[1]) * handle.outward[1] + ) + } + const from = along(event.nativeEvent.clientX, event.nativeEvent.clientY) + if (from === null) return + runMezzanineEdgeDrag({ handle, zoneId, levelId, from, along }) + } + return ( + + ) +} + +export function RoomHandleDragPreview3D() { + const drag = useRoomHandleDrag((s) => s.drag) + const unit = useViewer((s) => s.unit) + const metricNotation = useViewer((s) => s.metricNotation) + const elevation = drag?.kind === 'elevation' ? drag : null + const geometry = useMemo(() => { + if (!elevation) return null + const [outer, ...holes] = elevation.outline + if (!outer?.length) return null + const ring = (target: T, points: Point[]) => { + for (const [i, [x, z]] of points.entries()) { + if (i) target.lineTo(x, z) + else target.moveTo(x, z) + } + target.closePath() + return target + } + const shape = ring(new Shape(), outer) + shape.holes = holes.map((points) => ring(new Path(), points)) + const [ax, az] = elevation.anchor + return { + floor: new ShapeGeometry(shape).rotateX(Math.PI / 2), + leader: new BufferGeometry().setAttribute( + 'position', + new Float32BufferAttribute([ax, elevation.from, az, ax, elevation.value, az], 3), + ), + } + }, [elevation]) + const materials = useMemo( + () => ({ + line: new LineBasicNodeMaterial({ color: ARROW_COLOR, depthTest: false, depthWrite: false }), + fill: new MeshBasicNodeMaterial({ + color: ARROW_COLOR, + depthTest: false, + depthWrite: false, + opacity: 0.2, + side: DoubleSide, + transparent: true, + }), + }), + [], + ) + useEffect( + () => () => { + geometry?.floor.dispose() + geometry?.leader.dispose() + }, + [geometry], + ) + useEffect( + () => () => { + materials.line.dispose() + materials.fill.dispose() + }, + [materials], + ) + if (!drag) return null + if (drag.kind === 'mezzanine-edge') return + if (drag.kind === 'elevation') { + const [ax, az] = drag.anchor + return ( + + {geometry && ( + <> + + + + )} + {}} + onPointerDown={() => {}} + placement={{ position: [ax, drag.value, az], baseScale: 1 }} + shape="tracker" + /> + +
+ Floor + + {formatMeasurement( + drag.value - roomFloorBase(useScene.getState().nodes, drag.zoneId), + unit, + metricNotation, + )} + +
+ +
+ ) + } + const at: Point = [ + drag.anchor[0] + drag.outward[0] * drag.distance, + drag.anchor[1] + drag.outward[1] * drag.distance, + ] + const magnitude = formatMeasurement(Math.abs(drag.distance), unit, metricNotation) + const signed = `${drag.distance > 0 ? '+' : drag.distance < 0 ? '−' : ''}${magnitude}` + return ( + + + {drag.ghosts.map((ghost, index) => { + const length = Math.hypot(ghost.end[0] - ghost.start[0], ghost.end[1] - ghost.start[1]) + if (length < 1e-3) return null + return ( + + + + ) + })} + +
+ {drag.message ? ( + {drag.message} + ) : ( + {signed} + )} +
+ +
+ ) +} diff --git a/packages/editor/src/components/editor/room-highlight.tsx b/packages/editor/src/components/editor/room-highlight.tsx new file mode 100644 index 0000000000..c885f2e056 --- /dev/null +++ b/packages/editor/src/components/editor/room-highlight.tsx @@ -0,0 +1,168 @@ +'use client' + +import { sceneRegistry, useScene } from '@pascal-app/core' +import { useFrame } from '@react-three/fiber' +import { useEffect, useMemo, useRef } from 'react' +import { BufferGeometry, DoubleSide, Float32BufferAttribute, type Group } from 'three' +import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' +import { useShallow } from 'zustand/react/shallow' +import { useHighlightedRoom } from '../../hooks/use-selected-room' +import { EDITOR_LAYER } from '../../lib/constants' +import { resolveOverlayPolicy } from '../../lib/interaction/overlay-policy' +import { getRoomAssembly, resolveRoomAssemblyHeights } from '../../lib/room-assembly-overlay' +import type { RoomSelectionRecord } from '../../lib/room-selection' +import useEditor from '../../store/use-editor' +import useInteractionScope from '../../store/use-interaction-scope' +import { RoomControls2D, RoomControls3D } from './room-controls' + +function useRoomHighlight() { + const room = useHighlightedRoom() + const visible = useInteractionScope( + (state) => resolveOverlayPolicy(state.scope).conflictingControls === 'shown', + ) + const enabled = useEditor((state) => state.phase === 'structure' && state.mode === 'select') + return enabled && visible ? room : null +} + +const noRaycast = () => {} +const outlineMaterial = new LineBasicNodeMaterial({ + color: '#818cf8', + depthTest: false, + depthWrite: false, +}) +const fillMaterial = (opacity: number) => + new MeshBasicNodeMaterial({ + color: '#818cf8', + depthTest: false, + depthWrite: false, + opacity, + side: DoubleSide, + transparent: true, + }) +const floorMaterial = fillMaterial(0.18) +// Walls and the ceiling stack over the floor when seen from above. +const surfaceMaterial = fillMaterial(0.1) + +function positions(array: Float32Array) { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new Float32BufferAttribute(array, 3)) + return geometry +} + +function RoomMesh({ room }: { room: RoomSelectionRecord }) { + const ref = useRef(null) + const { levelId } = room.key + // Zone, plate and ceiling edits already produce a new record; wall and + // storey heights live on these nodes. + const heightSources = useScene( + useShallow((state) => [ + state.nodes[levelId as keyof typeof state.nodes], + ...room.boundaryWallIds.map((id) => state.nodes[id as keyof typeof state.nodes]), + ]), + ) + // biome-ignore lint/correctness/useExhaustiveDependencies: `heightSources` re-resolves heights from the current node map. + const assembly = useMemo( + () => + getRoomAssembly(room.geometry, resolveRoomAssemblyHeights(room, useScene.getState().nodes)), + [room, heightSources], + ) + const geometry = useMemo( + () => ({ + floor: positions(assembly.floor), + surfaces: positions(assembly.surfaces), + outline: positions(assembly.outline), + }), + [assembly], + ) + useEffect( + () => () => { + geometry.floor.dispose() + geometry.surfaces.dispose() + geometry.outline.dispose() + }, + [geometry], + ) + useFrame(() => { + const level = sceneRegistry.nodes.get(levelId) + if (!ref.current) return + ref.current.visible = !!level + if (level) { + level.updateWorldMatrix(true, false) + ref.current.matrix.copy(level.matrixWorld) + } + }) + return ( + + + + + + ) +} + +export function RoomHighlight3D() { + const room = useRoomHighlight() + return ( + <> + + {room ? : null} + + ) +} + +export function RoomHighlight2D({ levelId }: { levelId: string | null }) { + const room = useRoomHighlight() + const shape = room?.geometry + const paths = useMemo(() => { + if (!shape) return null + const ringPath = (ring: [number, number][]) => + `M ${ring.map((point) => point.join(' ')).join(' L ')} Z` + return { + floor: shape.clearPolygon + .flatMap(({ outer, holes }) => [outer, ...holes]) + .map(ringPath) + .join(' '), + walls: shape.boundaryWallIds + .flatMap((id) => { + const ring = shape.context.wallFootprints.get(id) + return ring ? [ringPath(ring)] : [] + }) + .join(' '), + } + }, [shape]) + return ( + <> + + {room && paths && room.key.levelId === levelId && ( + + + + + )} + + ) +} diff --git a/packages/editor/src/components/editor/room-transform-ghost.tsx b/packages/editor/src/components/editor/room-transform-ghost.tsx new file mode 100644 index 0000000000..be8c2107b9 --- /dev/null +++ b/packages/editor/src/components/editor/room-transform-ghost.tsx @@ -0,0 +1,256 @@ +'use client' + +import { + type AnyNodeId, + DEFAULT_LEVEL_HEIGHT, + type Point, + sceneRegistry, + useScene, +} from '@pascal-app/core' +import { getSceneTheme, useViewer } from '@pascal-app/viewer' +import { useFrame } from '@react-three/fiber' +import { useEffect, useMemo, useRef } from 'react' +import { + BufferGeometry, + DoubleSide, + ExtrudeGeometry, + Float32BufferAttribute, + type Group, + Path, + Shape, + ShapeGeometry, +} from 'three' +import { LineBasicNodeMaterial, MeshBasicNodeMaterial } from 'three/webgpu' +import { EDITOR_LAYER } from '../../lib/constants' +import { + type RoomTransformSession, + transformRoomPoint, + useRoomTransform, +} from '../../lib/room-transform-session' +import { useFloorplanRender } from '../editor-2d/floorplan-render-context' +import { DraftMeasurementLabel } from '../tools/shared/draft-measurement-label' + +// The wall draft's colours: indigo while the room can land, red where it can't. +const GHOST_COLOR = '#818cf8' +const GHOST_COLOR_LIGHT_PLAN = '#6366f1' +const BLOCKED_COLOR = '#ef4444' + +const noRaycast = () => {} + +function ringShape(target: T, ring: Point[]): T { + ring.forEach(([x, z], i) => { + if (i) target.lineTo(x, z) + else target.moveTo(x, z) + }) + target.closePath() + return target +} + +function ghostLabel(session: RoomTransformSession) { + if (!session.valid) return session.message ?? null + if (session.angle !== 0) { + const degrees = Math.round((-session.angle * 180) / Math.PI) + return `${degrees}°` + } + return null +} + +/** The picked-up room riding the cursor in 3D: its floor and wall footprints. */ +export function RoomTransformGhost3D() { + const session = useRoomTransform((s) => s.session) + const root = useRef(null) + const levelId = session?.levelId + const zone = useScene((s) => (session ? s.nodes[session.zoneId as AnyNodeId] : undefined)) + const levelHeight = useScene((s) => { + const level = levelId ? s.nodes[levelId as AnyNodeId] : undefined + return level?.type === 'level' ? (level.height ?? DEFAULT_LEVEL_HEIGHT) : DEFAULT_LEVEL_HEIGHT + }) + const isDark = useViewer((s) => getSceneTheme(s.sceneTheme).appearance === 'dark') + const elevation = zone?.type === 'zone' ? (zone.floor?.elevation ?? 0.05) : 0.05 + const color = session?.valid === false ? BLOCKED_COLOR : GHOST_COLOR + const materials = useMemo( + () => ({ + floor: new MeshBasicNodeMaterial({ + color, + depthTest: false, + depthWrite: false, + opacity: 0.22, + side: DoubleSide, + transparent: true, + }), + walls: new MeshBasicNodeMaterial({ + color, + depthWrite: false, + opacity: 0.35, + side: DoubleSide, + transparent: true, + }), + outline: new LineBasicNodeMaterial({ color, depthTest: false, depthWrite: false }), + }), + [color], + ) + useEffect( + () => () => { + materials.floor.dispose() + materials.walls.dispose() + materials.outline.dispose() + }, + [materials], + ) + // Built once per pick-up at rest; the carry only moves the group below. + const restOutline = session?.outline + const restWalls = session?.walls + const geometry = useMemo(() => { + if (!(restOutline && restWalls)) return null + const outline = restOutline + const walls = restWalls + const [outer, ...holes] = outline + if (!outer) return null + const shape = ringShape(new Shape(), outer) + shape.holes = holes.map((ring) => ringShape(new Path(), ring)) + const floor = new ShapeGeometry(shape).rotateX(Math.PI / 2) + const wallShapes = walls + .filter((ring) => ring.length >= 3) + .map((ring) => ringShape(new Shape(), ring)) + const wallMesh = wallShapes.length + ? new ExtrudeGeometry(wallShapes, { depth: levelHeight, bevelEnabled: false }).rotateX( + Math.PI / 2, + ) + : null + const positions: number[] = [] + for (const ring of [...outline, ...walls]) + for (let i = 0; i < ring.length; i++) { + const a = ring[i]!, + b = ring[(i + 1) % ring.length]! + positions.push(a[0], 0, a[1], b[0], 0, b[1]) + } + const lines = new BufferGeometry().setAttribute( + 'position', + new Float32BufferAttribute(positions, 3), + ) + return { floor, walls: wallMesh, lines } + }, [restOutline, restWalls, levelHeight]) + useEffect( + () => () => { + geometry?.floor.dispose() + geometry?.walls?.dispose() + geometry?.lines.dispose() + }, + [geometry], + ) + useFrame(() => { + const level = levelId ? sceneRegistry.nodes.get(levelId) : null + if (!root.current) return + root.current.visible = !!level + if (level) { + level.updateWorldMatrix(true, false) + root.current.matrix.copy(level.matrixWorld) + } + }) + if (!(session && geometry)) return null + const label = ghostLabel(session) + const at = transformRoomPoint(session.pivot, session.pivot, session.angle, session.translate) + // The planner's transform as a group transform: rotation about the pivot + // (three's Y rotation has the planner's handedness), then the translation. + const [px, pz] = session.pivot + return ( + + + + + {geometry.walls && ( + + )} + + + + {label && ( + + )} + + ) +} + +/** The picked-up room on the plan. */ +export function RoomTransformGhost2D({ levelId }: { levelId: string | null }) { + const session = useRoomTransform((s) => s.session) + const context = useFloorplanRender() + const isDark = useViewer((s) => getSceneTheme(s.sceneTheme).appearance === 'dark') + const restOutline = session?.outline + const restWalls = session?.walls + const paths = useMemo(() => { + if (!(restOutline && restWalls)) return null + const ring = (points: Point[]) => `M ${points.map((p) => p.join(' ')).join(' L ')} Z` + return { floor: restOutline.map(ring).join(' '), walls: restWalls.map(ring).join(' ') } + }, [restOutline, restWalls]) + if (!(session && paths) || session.levelId !== levelId) return null + const upp = context?.unitsPerPixel ?? 0.01 + const color = session.valid ? (isDark ? GHOST_COLOR : GHOST_COLOR_LIGHT_PLAN) : BLOCKED_COLOR + const label = ghostLabel(session) + const at = transformRoomPoint(session.pivot, session.pivot, session.angle, session.translate) + return ( + + + + + + {label && ( + + + {label} + + + )} + + ) +} diff --git a/packages/editor/src/components/editor/room-webgpu-materials.test.ts b/packages/editor/src/components/editor/room-webgpu-materials.test.ts new file mode 100644 index 0000000000..b6323994dd --- /dev/null +++ b/packages/editor/src/components/editor/room-webgpu-materials.test.ts @@ -0,0 +1,27 @@ +import { expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' + +// `drawsLines`: the file renders line geometry, which must go through the +// WebGPU node material. The Divide preview draws a strip mesh like the wall +// draft instead, so it only has to stay clear of drei fat lines. +for (const [file, drawsLines] of [ + ['./room-controls.tsx', false], + ['./room-highlight.tsx', true], + ['../../../../nodes/src/separator/renderer.tsx', true], +] as const) { + test(`${file} uses WebGPU node materials instead of drei fat lines`, () => { + const source = readFileSync(new URL(file, import.meta.url), 'utf8') + const dreiImports = source.matchAll( + /import\s+([\w\s{},*]+)\s+from\s+['"]@react-three\/drei['"]/g, + ) + for (const [, bindings] of dreiImports) { + expect(bindings).not.toMatch(/\bLine\b|\*/) + } + expect(source).not.toMatch(/ { @@ -233,6 +279,14 @@ function resolveRoofMaterialTarget( return null } +function isCeilingGridHit(event: NodeEvent): boolean { + return ( + !event.viaHandle && + event.node.type === 'ceiling' && + getEventObject(event)?.name === 'ceiling-grid' + ) +} + function getEventObject(event: NodeEvent): Object3D { const eventWithObject = event as NodeEvent & { object?: Object3D } return eventWithObject.object ?? event.nativeEvent.object @@ -309,6 +363,31 @@ function meshSlotRoles(node: AnyNode): string[] { const roofSelectionWorldPoint = new Vector3() const wallPaintWorldPoint = new Vector3() +const roomHitPoint = new Vector3() +const roomHitXZ: [number, number] = [0, 0] +function roomForEvent(event: NodeEvent) { + if (event.node.type !== 'wall' && event.node.type !== 'slab' && event.node.type !== 'ceiling') + return null + // The floor edge band and the foundation belong to the footprint, not the + // room above: the plate takes the pick and opens Floor & foundation. + if (isFootprintConstructionHit(event.node, event.object)) return null + const levelId = resolveLevelId(event.node, useScene.getState().nodes) + if (!levelId) return null + if (event.viaHandle && event.node.type === 'ceiling') { + roomHitXZ[0] = event.position[0] + roomHitXZ[1] = event.position[2] + return resolveEditorRoomHit(event.node, levelId, roomHitXZ, '3d') + } + const level = sceneRegistry.nodes.get(levelId) + if (!level) return null + level.updateWorldMatrix(true, false) + roomHitPoint.set(...event.position) + level.worldToLocal(roomHitPoint) + roomHitXZ[0] = roomHitPoint.x + roomHitXZ[1] = roomHitPoint.z + return resolveEditorRoomHit(event.node, levelId, roomHitXZ, '3d') +} + function resolveWallPaintHit(event: NodeEvent): WallPaintHit | undefined { const wall = event.node if (wall.type !== 'wall') return undefined @@ -504,7 +583,7 @@ const HIGHLIGHT_PROFILES = { } as const type HighlightKind = keyof typeof HIGHLIGHT_PROFILES -type HoverHighlightMode = 'default' | 'delete' | 'paint-ready' | 'paint-disabled' +type HoverHighlightMode = 'default' | 'delete' | 'paint-ready' | 'erase-ready' | 'paint-disabled' type HighlightableMaterial = Material & { color?: Color @@ -662,6 +741,13 @@ const SELECTION_STRATEGIES: Record = { updates.buildingId = buildingId } + if (node.type === 'zone' && !useViewer.getState().focusedUnitId) { + const room = roomKeyForZone(node.id) + if (room) { + if (!sameRoom(useEditor.getState().room, room)) selectRoom(room) + return + } + } if (node.type === 'zone') { updates.zoneId = node.id // Don't reset selectedIds in structure phase for zone, but if we changed level, it might reset them via hierarchy guard. @@ -679,20 +765,13 @@ const SELECTION_STRATEGIES: Record = { } }, handleDeselect: () => { - const structureLayer = useEditor.getState().structureLayer - if (structureLayer === 'zones') { - useViewer.getState().setSelection({ zoneId: null }) - } else { - useViewer.getState().setSelection({ selectedIds: [] }) - } + useEditor.getState().clearRoom() + useViewer.getState().setSelection({ selectedIds: [], zoneId: null }) }, isValid: (node) => { if (!isNodeInCurrentLevel(node)) return false const structureLayer = useEditor.getState().structureLayer - if (structureLayer === 'zones') { - if (node.type === 'zone') return true - return false - } + if (node.type === 'zone') return structureLayer === 'zones' if ( node.type === 'wall' || node.type === 'fence' || @@ -772,6 +851,20 @@ const SELECTION_STRATEGIES: Record = { } export const SelectionManager = () => { + const roomLevelId = useViewer((s) => s.selection.levelId) + useRoomRecords(roomLevelId) + useEffect( + () => + useViewer.subscribe((state, previous) => { + if ( + state.selection.levelId !== previous.selection.levelId || + (state.selection.zoneId !== previous.selection.zoneId && state.selection.zoneId) + ) { + useEditor.getState().clearRoom() + } + }), + [], + ) const phase = useEditor((s) => s.phase) const mode = useEditor((s) => s.mode) // The canvas element — cursor styling must land here, not on `document.body`: @@ -825,6 +918,18 @@ export const SelectionManager = () => { // The last hover event, replayed when the application scope cycles so the // preview + chip update under a stationary cursor (Shift fires no pointer move). let lastEnterEvent: NodeEvent | null = null + // Paint never stops a pointer event. R3F keeps a hover that stopped + // propagation stopping every later move over that object, which would pin + // the pointer to a door or a wall it should pass through where it opens + // (see `paint-pass-through`). So the nearest surface that takes a pointer + // event claims it; farther ones see the claim and stand down. + let claimedEvent: unknown = null + let hoveredNodeId: string | null = null + const claim = (event: NodeEvent) => { + claimedEvent = event.nativeEvent.nativeEvent + } + const claimedByNearer = (event: NodeEvent) => + claimedEvent !== null && claimedEvent === event.nativeEvent.nativeEvent const clearActivePreview = () => { activePreview?.restore() @@ -842,8 +947,49 @@ export const SelectionManager = () => { selectedMaterialTarget: useEditor.getState().selectedMaterialTarget, }) + // The eyedropper: the hover shows what a click would take (the cursor + // swatch), the click takes it and returns to the sub-mode it came from. + const pickInteraction = ( + node: AnyNode, + role: string | null, + event: NodeEvent, + materialIndex: number | null, + ): PaintInteraction => { + const picked = role + ? eyedropperMaterial({ + node, + role, + nodes: useScene.getState().nodes, + hitObject: getEventObject(event), + materialIndex, + }) + : null + return { + key: `pick:${node.id}:${role ?? 'none'}:${paintMaterialKey(picked)}`, + hoveredId: node.id as AnyNodeId, + hoverMode: picked ? 'paint-ready' : 'paint-disabled', + paintHover: + picked && role + ? { scopes: ['single'], slotLabel: paintSurfaceLabel(node, role), nodeNoun: node.type } + : null, + apply: picked + ? () => useEditor.getState().armMaterialPaint(picked, paintPickReturnMode()) + : null, + preview: () => { + usePaintRegionMode.setState({ picked }) + return () => { + if (usePaintRegionMode.getState().picked === picked) + usePaintRegionMode.setState({ picked: null }) + } + }, + } + } + const resolvePaintInteraction = (event: NodeEvent): PaintInteraction | null => { - const eraser = useEditor.getState().paintEraser + // A region sub-mode draws its own region before painting; the + // whole-surface hover and click stand down. + if (paintRegionModeActive('material-paint')) return null + const eraser = isPaintErasing() const activePaintMaterial = resolveActivePaintMaterial() const node = event.node @@ -885,6 +1031,25 @@ export const SelectionManager = () => { hitObject: getEventObject(event), ray: event.nativeEvent.ray, }) + // Not claiming the hover lets the pointer event reach the surface behind: + // an empty door or window, or a wall's collision hit in one of its holes. + if ( + paintPassesThrough(node, role) || + ((node.type === 'door' || node.type === 'window') && + openingPartHidden( + getRegisteredNodeObject(node.id), + event.nativeEvent.ray, + event.nativeEvent.intersections, + )) || + (node.type === 'wall' && + wallHitInOpening( + getRegisteredNodeObject(node.id), + event.nativeEvent.ray, + event.nativeEvent.distance, + )) + ) + return null + if (isPaintPicking()) return pickInteraction(node, role, event, materialIndex ?? null) const compatible = role !== null && paintEnabled // Derive the node's slots (declared, else mesh tags) once — drives both // the chip's available scopes and the whole-object fan-out. @@ -893,7 +1058,13 @@ export const SelectionManager = () => { // / all matching / room). The scope is part of the key so cycling it // (Shift) re-keys the interaction → the preview re-applies for the new // spread instead of being deduped to the single-surface preview. - const scope = useEditor.getState().paintScope + const hover = compatible && role ? paintHoverInfo(node, role, slotRoles) : null + // A scope carried over from another surface paints what the chip + // shows for this one: the narrowest when it isn't offered here. + const scope = effectivePaintScope( + useEditor.getState().paintScope, + hover?.scopes ?? ['single'], + ) const wallHit = resolveWallPaintHit(event) const scopeTargets = compatible && role @@ -907,30 +1078,44 @@ export const SelectionManager = () => { wallHit, }) : [] - const scopeTargetKey = scopeTargets + // What the click changes on floor plates, fallbacks included (a room's + // floor carries its unpainted steps): the outline. The preview draws + // the same set, each follower through the surface it follows. + const scopeRole = compatible && role ? paintScopeRole(node, role, scope) : null + const sceneNodes = useScene.getState().nodes + const affected = scopeRole + ? (plateAffectedSurfaces(sceneNodes, node, scopeRole, { erasing: eraser }) ?? + ceilingAffectedSurfaces(node, scopeRole)) + : null + const previewTargets = mergePaintSurfaces( + scopeTargets, + scopeRole + ? (platePreviewSurfaces(sceneNodes, node, scopeRole) ?? + ceilingAffectedSurfaces(node, scopeRole)) + : null, + ) + const scopeTargetKey = previewTargets .map((target) => `${target.nodeId}:${target.role}`) .sort() .join(',') return { key: `${node.type}:${node.id}:${role ?? 'unsupported'}:${eraser ? 'erase' : 'paint'}:${scope}:${scopeTargetKey}`, hoveredId: node.id as AnyNodeId, - hoverMode: compatible ? 'paint-ready' : 'paint-disabled', - paintHover: - compatible && role - ? { - scopes: availablePaintScopes({ node, slotRoles }), - slotLabel: slotDisplayLabel(node, role), - nodeNoun: node.type, - } - : null, + hoverMode: compatible ? (eraser ? 'erase-ready' : 'paint-ready') : 'paint-disabled', + paintHover: hover, apply: compatible && role ? () => { + // A surface with nothing of its own to paint (a footprint's + // top where no room stands) says so instead of painting. + const refusal = floorPlatePaintRefusal(useScene.getState().nodes, node, role) + usePaintRegionMode.getState().setNotice(refusal?.message ?? null) + if (refusal) return // Spread targets are all the same slot-model kind, so one - // batched commit writes them in a single undo step; the - // single-surface case keeps the kind's own commit (covers - // non-slot kinds too). - if (scopeTargets.length > 1) { + // batched commit writes them in a single undo step; only + // the hovered surface itself keeps the kind's own commit + // (covers non-slot kinds too) — see `paintCommitRoute`. + if (paintCommitRoute(scopeTargets, node.id, role) === 'fanout') { commitPaintScopeFanout( scopeTargets, paintSpec.material, @@ -964,10 +1149,14 @@ export const SelectionManager = () => { // hovered surface. Each target is the same kind, so its own // paint capability builds the preview; restores combine. const restores: PaintPreviewCleanup[] = [] - const sceneNodes = useScene.getState().nodes + const liveNodes = useScene.getState().nodes + if (affected) { + usePaintOutline.setState({ surfaces: affected }) + restores.push(() => usePaintOutline.setState({ surfaces: null })) + } try { - for (const target of scopeTargets) { - const targetNode = sceneNodes[target.nodeId] + for (const target of previewTargets) { + const targetNode = liveNodes[target.nodeId] const targetRoot = getRegisteredNodeObject(target.nodeId) const targetCap = targetNode ? nodeRegistry.get(targetNode.type)?.capabilities?.paint @@ -1004,6 +1193,8 @@ export const SelectionManager = () => { if (roofNode?.type !== 'roof') return null const role = resolveRoofMaterialTarget(event as RoofEvent | RoofSegmentEvent) + if (isPaintPicking()) + return pickInteraction(isSegmentHit ? node : roofNode, role, event, null) const compatible = role !== null && paintEnabled // Painting directly on a segment (only possible in segment edit // mode, where the per-segment mesh is visible) writes to the @@ -1015,7 +1206,7 @@ export const SelectionManager = () => { segmentTarget ? segmentTarget.id : roofNode.id }:${role ?? 'unsupported'}:${eraser ? 'erase' : 'paint'}`, hoveredId: (segmentTarget ? segmentTarget.id : roofNode.id) as AnyNodeId, - hoverMode: compatible ? 'paint-ready' : 'paint-disabled', + hoverMode: compatible ? (eraser ? 'erase-ready' : 'paint-ready') : 'paint-disabled', // Roof isn't on the slot model (role-specific fields, custom commit), // so it offers only the single surface — but still labels it. paintHover: @@ -1091,17 +1282,20 @@ export const SelectionManager = () => { previewOwner.wrap(resolvePaintInteraction(event)) const onEnter = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return // A host-driven drag (handle resize/rotate) sets `inputDragging`. // useNodeEvents now emits hover events during such a drag so surface // move tools keep tracking the cursor — but paint preview must not fire // mid-drag, so gate on `inputDragging` here too. if (boxSelectHandled || useViewer.getState().inputDragging) return + if (claimedByNearer(event)) return const interaction = getPaintInteraction(event) if (!interaction) return - event.stopPropagation() + claim(event) lastEnterEvent = event + hoveredNodeId = interaction.hoveredId // Drive the paint HUD off this hover: the interaction carries the scopes + // labels for the painted surface (`null` when it isn't paintable — no @@ -1123,12 +1317,17 @@ export const SelectionManager = () => { } const onLeave = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return const interaction = getPaintInteraction(event) - if (!interaction) return + // A surface behind the hovered one (under an opening that never stops + // the pointer) leaving says nothing about the hover. + if (!interaction || interaction.hoveredId !== hoveredNodeId) return // Leaving any surface → the HUD shows the "hover a surface" hint again. + hoveredNodeId = null lastEnterEvent = null useEditor.getState().setPaintHover(null) + usePaintOutline.setState({ surfaces: null }) if (activePreview?.key !== interaction.key) { return @@ -1142,12 +1341,14 @@ export const SelectionManager = () => { } const onClick = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return if (boxSelectHandled) return + if (claimedByNearer(event)) return const interaction = getPaintInteraction(event) if (!interaction) return - event.stopPropagation() + claim(event) if (!interaction.apply) { return @@ -1202,11 +1403,22 @@ export const SelectionManager = () => { const unsubscribePaintScope = useEditor.subscribe((state, prev) => { if (state.paintScope === prev.paintScope || !lastEnterEvent) return clearActivePreview() + claimedEvent = null + onEnter(lastEnterEvent) + }) + const releasePickHold = bindPaintPickHold(window) + // So does switching the sub-mode (the eyedropper held on Alt, a mode icon). + const unsubscribePaintMode = usePaintRegionMode.subscribe((state, prev) => { + if (state.mode === prev.mode || !lastEnterEvent) return + clearActivePreview() + claimedEvent = null onEnter(lastEnterEvent) }) return () => { unsubscribePaintScope() + unsubscribePaintMode() + releasePickHold() for (const type of subscribedKinds) { emitter.off(`${type}:enter` as any, onEnter as any) emitter.off(`${type}:move` as any, onEnter as any) @@ -1215,6 +1427,7 @@ export const SelectionManager = () => { } clearActivePreview() useViewer.setState({ hoveredId: null }) + usePaintOutline.setState({ surfaces: null }) setHoverHighlightMode('default') useEditor.getState().setPaintHover(null) } @@ -1260,9 +1473,19 @@ export const SelectionManager = () => { if (movingNode || isCurveReshape) return const onPointerDown = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return if (!selectionEnabled(useInteractionScope.getState().scope)) return const pointer = pointerEventFromNodeEvent(event) - if (pointer.button !== 0) return + if (pointer.button !== 0 || pointer.altKey) return + if ( + roomPickingEnabled() && + shouldInterceptRoom( + roomForEvent(event), + selectionModifiersFromEvent(pointer), + event.node.id, + ) + ) + return const handleOwnsPointer = pointerEventHitsEditorHandle(event.nativeEvent) // Plain press on a transformable member of a multi-selection arms the @@ -1577,6 +1800,7 @@ export const SelectionManager = () => { if (movingNode || isCurveReshape) return const onClick = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return // Skip if box-select just completed (drag ended over a node) if (boxSelectHandled) return @@ -1588,8 +1812,11 @@ export const SelectionManager = () => { // body click so only the reshape tool handles the release. (Scoped to // `endpoint`: hole-edit relies on node clicks to exit, just below.) const activeScope = useInteractionScope.getState().scope - if (activeScope.kind === 'mesh-editing') return - if (activeScope.kind === 'reshaping' && activeScope.reshape === 'endpoint') return + if ( + !selectionEnabled(activeScope) && + !(activeScope.kind === 'reshaping' && activeScope.reshape === 'hole') + ) + return if (dispatchSceneAction(event.node, getEventObject(event))) { event.stopPropagation() @@ -1606,21 +1833,14 @@ export const SelectionManager = () => { selectedIds: useViewer.getState().selection.selectedIds, }) - // A ceiling is selectable only through its corner handles, never via - // the `ceiling-grid` body mesh. When the grid is revealed (ceiling - // selected, or an item placed beneath it) a top-down click hits the - // grid first; selecting the ceiling there both re-selects it as a - // no-op and stops propagation, blocking the hosted item below. By - // ignoring non-handle ceiling clicks (without stopping propagation) - // the click falls through to the item underneath. - if (node.type === 'ceiling' && !event.viaHandle) return - // Unit focus turns clicks inside a zone into the paint gesture: // membership toggles, the zone stays unselected, focus stays. const focusedUnitId = useViewer.getState().focusedUnitId if (focusedUnitId) { const zone = - node.type === 'zone' ? node : zoneAtWorldPoint(event.position[0], event.position[2]) + node.type === 'zone' + ? node + : zoneAtWorldPoint(event.position[0], event.position[2], event.position[1]) if (zone) { event.stopPropagation() clickHandledRef.current = true @@ -1649,7 +1869,7 @@ export const SelectionManager = () => { if ( target.phase === 'structure' && - target.structureLayer && + target.structureLayer === 'zones' && target.structureLayer !== currentStructureLayer ) { useEditor.getState().setStructureLayer(target.structureLayer) @@ -1673,7 +1893,31 @@ export const SelectionManager = () => { clickHandledRef.current = false }, 50) - let nodeToSelect = node + if ( + roomPickingEnabled() && + selectRoomFromHit( + roomForEvent(event), + selectionModifiersFromEvent(event.nativeEvent, modifierKeysRef.current), + node.id, + ) + ) + return + // Room first: a raised or sunken room's plate and a mezzanine's plate + // belong to their room, never selected on their own. Past the room (the + // drill click, or Alt) a raised or sunken room continues to the + // footprint floor it stands on, like a ground-level room; a mezzanine + // stays on its mezzanine. + let footprint: SlabNode | null = null + if (roomPickingEnabled() && isRoomOwnedPlate(node)) { + footprint = roomOwnedPlateDrillTarget(useScene.getState().nodes, node as SlabNode) + if (!footprint) { + const hit = roomForEvent(event) + if (hit) selectRoom(hit) + return + } + } + + let nodeToSelect: AnyNode = footprint ?? node if (node.type === 'stair-segment' && node.parentId) { const parentNode = useScene.getState().nodes[node.parentId as AnyNodeId] if (parentNode && parentNode.type === 'stair') { @@ -1701,13 +1945,15 @@ export const SelectionManager = () => { // Move button. The first (selecting) click can't hit this because the // node isn't yet in `selectedIdsBeforeRouting`. const nativeEvent = event.nativeEvent - const hasModifier = nativeEvent.shiftKey || isCommandModifier(nativeEvent) + const hasModifier = + nativeEvent.altKey || nativeEvent.shiftKey || isCommandModifier(nativeEvent) const isAlreadySole = selectedIdsBeforeRouting.length === 1 && selectedIdsBeforeRouting[0] === nodeToSelect.id if ( useEditor.getState().mode !== 'delete' && !hasModifier && isAlreadySole && + !expandSessionSelectionForNode(nodeToSelect.id) && !getMovingNode() && canDirectMoveNode(nodeToSelect) ) { @@ -1732,7 +1978,7 @@ export const SelectionManager = () => { // `capabilities.paint` route through this entry — wall, // chimney, dormer use it today. The legacy stair / roof / // single-surface arms below stay until they migrate too. - if (nodeToSelect.type === node.type) { + if (!footprint && nodeToSelect.type === node.type) { const paintCap = nodeRegistry.get(node.type)?.capabilities?.paint if (paintCap) { const materialIndex = getIntersectionMaterialIndex( @@ -1829,27 +2075,25 @@ export const SelectionManager = () => { const onGridClick = (event: GridEvent) => { if (clickHandledRef.current) return if (boxSelectHandled) return - if (useInteractionScope.getState().scope.kind === 'mesh-editing') return + if (!selectionEnabled(useInteractionScope.getState().scope)) return const nativeEvent = event.nativeEvent if (nativeEvent?.metaKey || nativeEvent?.ctrlKey || nativeEvent?.shiftKey) return // Unit focus: a ground click inside a zone paints it; elsewhere it // leaves focus and the unit selection alone. const focusedUnitId = useViewer.getState().focusedUnitId if (focusedUnitId) { - const zone = zoneAtLevelPoint(event.localPosition[0], event.localPosition[2]) + const zone = zoneAtLevelPoint( + event.localPosition[0], + event.localPosition[2], + event.localPosition[1], + ) if (zone) paintZoneMembership(focusedUnitId, zone.id) return } - const { phase, structureLayer } = useEditor.getState() + const { phase } = useEditor.getState() const activeStrategy = SELECTION_STRATEGIES[phase] if (activeStrategy) activeStrategy.handleDeselect() useEditor.getState().setSelectedMaterialTarget(null) - - // When deselecting from zone mode, return to structure select - if (phase === 'structure' && structureLayer === 'zones') { - useEditor.getState().setStructureLayer('elements') - useEditor.getState().setMode('select') - } } emitter.on('grid:click', onGridClick) @@ -1869,12 +2113,20 @@ export const SelectionManager = () => { if (movingNode || isCurveReshape) return const onEnter = (event: NodeEvent) => { - if (useInteractionScope.getState().scope.kind === 'mesh-editing') return + if (isCeilingGridHit(event)) return + if (!selectionEnabled(useInteractionScope.getState().scope)) return // A host-driven drag (handle resize/rotate, box-select) sets // `inputDragging`. useNodeEvents still emits hover events during it so // surface move tools keep tracking — but the select-hover outline must // stay put, so don't repaint under the cursor mid-drag. if (useViewer.getState().inputDragging) return + // An editor handle anywhere along the ray owns the pointer — it takes the + // press (handles draw on top of walls), so it takes the hover too: no + // stopPropagation, so the handle behind the wall still hears its enter. + if (pointerEventHitsEditorHandle(event.nativeEvent)) { + clearSelectHover(event) + return + } const node = resolveCanvasSelectionNode({ node: resolveSelectModeNodeTarget(event), nodes: useScene.getState().nodes, @@ -1902,10 +2154,20 @@ export const SelectionManager = () => { } event.stopPropagation() - useViewer.setState({ hoveredId: node.id }) + if ( + roomPickingEnabled() && + hoverRoomFromHit( + roomForEvent(event), + selectionModifiersFromEvent(event.nativeEvent, modifierKeysRef.current), + node.id, + ) + ) + return + useViewer.getState().setHoveredId(node.id) } - const onLeave = (event: NodeEvent) => { + const clearSelectHover = (event: NodeEvent) => { + useEditor.getState().setHoveredRoom(null) if (useViewer.getState().inputDragging) return const nodeId = resolveCanvasSelectionNode({ node: resolveSelectModeNodeTarget(event), @@ -1917,7 +2179,13 @@ export const SelectionManager = () => { } } + const onLeave = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return + clearSelectHover(event) + } + const onDoubleClick = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return if (useInteractionScope.getState().scope.kind === 'mesh-editing') return let node = resolveCanvasSelectionNode({ node: resolveSelectModeNodeTarget(event), @@ -1954,7 +2222,9 @@ export const SelectionManager = () => { // zone (focus stays); the two clicks before it cancel each other's paint. if (useViewer.getState().focusedUnitId) { const zone = - node.type === 'zone' ? node : zoneAtWorldPoint(event.position[0], event.position[2]) + node.type === 'zone' + ? node + : zoneAtWorldPoint(event.position[0], event.position[2], event.position[1]) if (zone) { event.stopPropagation() cancelPendingZonePaint(zone.id) @@ -2025,6 +2295,7 @@ export const SelectionManager = () => { subscribedKinds.forEach((type) => { emitter.on(`${type}:enter` as any, onEnter as any) + emitter.on(`${type}:move` as any, onEnter as any) emitter.on(`${type}:leave` as any, onLeave as any) emitter.on(`${type}:double-click` as any, onDoubleClick as any) }) @@ -2032,6 +2303,7 @@ export const SelectionManager = () => { return () => { subscribedKinds.forEach((type) => { emitter.off(`${type}:enter` as any, onEnter as any) + emitter.off(`${type}:move` as any, onEnter as any) emitter.off(`${type}:leave` as any, onLeave as any) emitter.off(`${type}:double-click` as any, onDoubleClick as any) }) @@ -2045,6 +2317,7 @@ export const SelectionManager = () => { if (mode !== 'delete') return const onClick = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return const node = event.node if (!isNodeInCurrentLevel(node)) return @@ -2063,14 +2336,16 @@ export const SelectionManager = () => { } const onEnter = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return const node = event.node if (!isNodeInCurrentLevel(node)) return if (node.type === 'building' || node.type === 'site') return event.stopPropagation() - useViewer.setState({ hoveredId: node.id }) + useViewer.getState().setHoveredId(node.id) } const onLeave = (event: NodeEvent) => { + if (isCeilingGridHit(event)) return const nodeId = event?.node?.id if (nodeId && useViewer.getState().hoveredId === nodeId) { useViewer.setState({ hoveredId: null }) @@ -2121,6 +2396,7 @@ export const SelectionManager = () => { + ) } @@ -2372,6 +2648,7 @@ const EditorOutlinerSync = () => { const registryVersion = useRegistryVersion() const outliner = useViewer((s) => s.outliner) const nodes = useScene((s) => s.nodes) + const paintOutline = usePaintOutline((s) => s.surfaces) useEffect(() => { void geometryRevision @@ -2417,7 +2694,11 @@ const EditorOutlinerSync = () => { } outliner.hoveredObjects.length = 0 - if (hoveredId) { + if (paintOutline) { + // Paint on a floor plate: exactly the surfaces the click changes. + for (const mesh of paintSurfaceMeshes(paintOutline, (id) => sceneRegistry.nodes.get(id))) + if (mesh.parent) outliner.hoveredObjects.push(mesh) + } else if (hoveredId) { if (!nodes[hoveredId as AnyNodeId]) { useViewer.setState({ hoveredId: null }) } else { @@ -2440,6 +2721,7 @@ const EditorOutlinerSync = () => { hoveredId, outliner, nodes, + paintOutline, ]) return null diff --git a/packages/editor/src/components/editor/slab-hole-highlights.tsx b/packages/editor/src/components/editor/slab-hole-highlights.tsx index bf369aef2c..be6f6684b7 100644 --- a/packages/editor/src/components/editor/slab-hole-highlights.tsx +++ b/packages/editor/src/components/editor/slab-hole-highlights.tsx @@ -417,7 +417,10 @@ function SlabHoleHighlight({ [holeIndex, metadata, slabId], ) + // Only a release that ends a press on a hole is the hole's: any other + // (a handle drag let go over the hole) must reach its owner. const handlePointerUp = useCallback((event: ThreeEvent) => { + if (!restoreNodeClickSuppression) return releaseNodeClickSuppression() stopPointerPropagation(event) }, []) diff --git a/packages/editor/src/components/editor/snapshot-capture-overlay.tsx b/packages/editor/src/components/editor/snapshot-capture-overlay.tsx index 226df5742b..df0126aa3f 100644 --- a/packages/editor/src/components/editor/snapshot-capture-overlay.tsx +++ b/packages/editor/src/components/editor/snapshot-capture-overlay.tsx @@ -29,6 +29,7 @@ import useEditor, { import { useFirstPersonHud } from '../../store/use-first-person-hud' import { Slider } from '../ui/slider' import { WalkthroughCrosshair } from '../walkthrough-hud' +import { CaptureLevelPicker } from './capture-level-picker' import { isOverlaySnapshotSave } from './snapshot-capture' // Local alias — distinct from `useEditor.captureMode` (which describes *why* @@ -710,6 +711,9 @@ export function SnapshotCaptureOverlay({ projectId }: { projectId: string }) {
)} + {/* Top-left: which levels the shot shows (the whole building by default). */} + {!isPreset && } + {/* Top-right dismiss button (icon-only on mobile) */}