Prompt specification
Build or customize the Three.js 3D scene "Reconfigure modules under circulation constraints" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Reconfigure modules under circulation constraints
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/reconfigure-modules-under-circulation-constraints-x2208
Scene Description Prompt:
Let users rearrange a small set of room modules. Highlight disconnected entrances, blocked corridors, and misaligned service connectors while preserving each module's dimensions and usable interior space. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (reconfigure-modules-under-circulation-constraints-x2208):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Roomflow — Modular Room Planner</title>
<style>
:root {
--ink: #23313b;
--muted: #71808a;
--panel: rgba(255, 255, 255, 0.92);
--line: rgba(40, 58, 69, 0.11);
--green: #2f9c73;
--red: #df5a58;
--amber: #e79a38;
--magenta: #bb57ae;
--shadow: 0 12px 40px rgba(50, 65, 74, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #edf0e9;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
touch-action: none;
}
button {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.glass {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.82);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
right: 18px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand,
.top-actions {
pointer-events: auto;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 285px;
padding: 12px 16px;
border-radius: 16px;
}
.brand-mark {
width: 39px;
height: 39px;
display: grid;
place-items: center;
border-radius: 11px;
color: white;
background: #293a43;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.12);
}
.brand-mark svg {
width: 22px;
height: 22px;
}
.brand h1 {
margin: 0;
font-size: 16px;
line-height: 1.1;
letter-spacing: 0.02em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.04em;
}
.top-actions {
display: flex;
align-items: center;
gap: 8px;
}
.top-action,
.tool-button {
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.9);
color: var(--ink);
cursor: pointer;
transition:
background 150ms ease,
transform 150ms ease,
border-color 150ms ease;
}
.top-action {
min-height: 40px;
padding: 0 13px;
font-size: 12px;
font-weight: 650;
}
.top-action:hover,
.tool-button:hover {
transform: translateY(-1px);
border-color: rgba(40, 58, 69, 0.25);
}
.top-action.active {
color: white;
background: #293a43;
border-color: #293a43;
}
.issue-counter {
display: inline-flex;
align-items: center;
gap: 8px;
margin-right: 4px;
}
.counter-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(47, 156, 115, 0.12);
}
.counter-dot.has-issues {
background: var(--red);
box-shadow: 0 0 0 4px rgba(223, 90, 88, 0.12);
}
.panel {
position: fixed;
z-index: 8;
top: 88px;
width: 278px;
max-height: calc(100vh - 190px);
overflow: hidden;
border-radius: 17px;
}
.module-panel {
left: 18px;
}
.diagnostics-panel {
right: 18px;
width: 304px;
}
.panel-header {
padding: 17px 18px 12px;
border-bottom: 1px solid var(--line);
}
.panel-title-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.panel h2 {
margin: 0;
font-size: 13px;
letter-spacing: 0.02em;
}
.panel-subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.count-badge {
flex: 0 0 auto;
padding: 4px 8px;
border-radius: 999px;
background: #eef1ed;
color: #617079;
font-size: 10px;
font-weight: 750;
}
.module-list {
padding: 8px;
}
.module-card {
width: 100%;
display: grid;
grid-template-columns: 10px 1fr auto;
grid-template-rows: auto auto;
column-gap: 10px;
row-gap: 7px;
margin: 0;
padding: 11px 10px;
border: 1px solid transparent;
border-radius: 12px;
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease;
}
.module-card:hover {
background: rgba(255, 255, 255, 0.75);
}
.module-card.selected {
background: white;
border-color: rgba(42, 57, 66, 0.13);
box-shadow: 0 5px 16px rgba(48, 62, 72, 0.07);
}
.module-swatch {
width: 9px;
height: 28px;
grid-row: 1 / 3;
align-self: center;
border-radius: 999px;
background: var(--module-color);
}
.module-copy {
min-width: 0;
}
.module-copy strong {
display: block;
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.module-copy small,
.module-coords {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.module-coords {
grid-column: 2 / 4;
font-variant-numeric: tabular-nums;
}
.status-pill {
align-self: center;
padding: 4px 7px;
border-radius: 999px;
font-size: 9px;
font-weight: 750;
white-space: nowrap;
}
.status-pill.good {
color: #25785a;
background: rgba(47, 156, 115, 0.11);
}
.status-pill.warning {
color: #9b631c;
background: rgba(231, 154, 56, 0.15);
}
.status-pill.error {
color: #ad3f3d;
background: rgba(223, 90, 88, 0.12);
}
.rigid-note {
display: flex;
align-items: center;
gap: 8px;
margin: 0 10px 10px;
padding: 9px 10px;
border-radius: 10px;
color: #65747d;
background: rgba(235, 239, 234, 0.78);
font-size: 10px;
line-height: 1.4;
}
.lock-icon {
display: grid;
flex: 0 0 auto;
width: 19px;
height: 19px;
place-items: center;
border-radius: 6px;
color: #4f626d;
background: white;
font-size: 10px;
}
.diagnostic-summary {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
padding: 10px;
border-bottom: 1px solid var(--line);
}
.summary-cell {
padding: 9px 5px;
border-radius: 10px;
background: rgba(241, 243, 240, 0.9);
text-align: center;
}
.summary-cell strong {
display: block;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.summary-cell span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.issue-list {
max-height: 360px;
overflow: auto;
padding: 9px;
}
.issue-item {
width: 100%;
display: grid;
grid-template-columns: 9px 1fr;
gap: 9px;
margin: 0 0 5px;
padding: 10px;
border: 0;
border-radius: 11px;
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
}
.issue-item:hover {
background: rgba(255, 255, 255, 0.8);
}
.issue-dot {
width: 8px;
height: 8px;
margin-top: 4px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 0 3px rgba(231, 154, 56, 0.12);
}
.issue-dot.disconnected {
background: var(--red);
box-shadow: 0 0 0 3px rgba(223, 90, 88, 0.12);
}
.issue-dot.service {
background: var(--magenta);
box-shadow: 0 0 0 3px rgba(187, 87, 174, 0.12);
}
.issue-copy strong {
display: block;
font-size: 11px;
}
.issue-copy span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.empty-state {
padding: 25px 18px 27px;
text-align: center;
}
.empty-icon {
width: 43px;
height: 43px;
display: grid;
place-items: center;
margin: 0 auto 10px;
border-radius: 50%;
color: var(--green);
background: rgba(47, 156, 115, 0.1);
font-size: 20px;
font-weight: 800;
}
.empty-state strong {
display: block;
font-size: 12px;
}
.empty-state span {
display: block;
max-width: 210px;
margin: 6px auto 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.toolbar {
position: fixed;
z-index: 10;
left: 50%;
bottom: 18px;
display: flex;
align-items: center;
gap: 8px;
padding: 9px;
border-radius: 17px;
transform: translateX(-50%);
}
.selection-summary {
min-width: 145px;
padding: 2px 11px 2px 5px;
border-right: 1px solid var(--line);
}
.selection-summary strong {
display: block;
font-size: 11px;
}
.selection-summary span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.tool-button {
min-height: 36px;
padding: 0 11px;
font-size: 10px;
font-weight: 700;
white-space: nowrap;
}
.tool-button.primary {
color: white;
background: #293a43;
border-color: #293a43;
}
.tool-button.active {
color: #245f4c;
background: rgba(47, 156, 115, 0.11);
border-color: rgba(47, 156, 115, 0.25);
}
.icon-tool {
width: 36px;
padding: 0;
font-size: 16px;
}
.divider {
width: 1px;
height: 27px;
background: var(--line);
}
.arrow-pad {
display: grid;
grid-template-columns: repeat(3, 28px);
grid-template-rows: repeat(2, 28px);
gap: 3px;
}
.arrow-pad button {
width: 28px;
height: 28px;
padding: 0;
border: 1px solid var(--line);
border-radius: 7px;
color: var(--ink);
background: rgba(255, 255, 255, 0.75);
cursor: pointer;
}
.arrow-pad button:hover {
background: white;
}
.arrow-pad [data-nudge="0,-1"] {
grid-column: 2;
}
.arrow-pad [data-nudge="-1,0"] {
grid-column: 1;
grid-row: 2;
}
.arrow-pad [data-nudge="0,1"] {
grid-column: 2;
grid-row: 2;
}
.arrow-pad [data-nudge="1,0"] {
grid-column: 3;
grid-row: 2;
}
.legend {
position: fixed;
z-index: 7;
right: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 13px;
padding: 10px 13px;
border-radius: 13px;
color: #66757e;
font-size: 9px;
font-weight: 700;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
white-space: nowrap;
}
.legend-swatch {
width: 8px;
height: 8px;
border-radius: 50%;
}
.legend-swatch.green {
background: var(--green);
}
.legend-swatch.red {
background: var(--red);
}
.legend-swatch.amber {
background: var(--amber);
}
.legend-swatch.magenta {
background: var(--magenta);
}
.hint {
position: fixed;
z-index: 6;
left: 50%;
top: 83px;
padding: 7px 11px;
border-radius: 999px;
color: #697881;
background: rgba(255, 255, 255, 0.68);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.025em;
transform: translateX(-50%);
pointer-events: none;
}
.toast {
position: fixed;
z-index: 20;
left: 50%;
bottom: 83px;
padding: 10px 15px;
border-radius: 10px;
color: white;
background: rgba(36, 49, 58, 0.94);
box-shadow: 0 10px 30px rgba(25, 35, 42, 0.2);
font-size: 11px;
font-weight: 650;
opacity: 0;
transform: translate(-50%, 8px);
transition: opacity 160ms ease, transform 160ms ease;
pointer-events: none;
}
.toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 1040px) {
.legend {
display: none;
}
.panel {
width: 248px;
}
.diagnostics-panel {
width: 270px;
}
}
@media (max-width: 790px) {
.brand {
min-width: 0;
}
.brand p,
.hint,
#cameraButton {
display: none;
}
.top-action {
padding: 0 10px;
}
.panel {
top: 77px;
max-height: calc(100vh - 165px);
}
.module-panel {
width: 205px;
}
.diagnostics-panel {
width: 225px;
}
.rigid-note,
.module-coords {
display: none;
}
.module-card {
grid-template-rows: auto;
}
.module-swatch {
grid-row: auto;
}
.toolbar {
bottom: 10px;
}
.selection-summary {
min-width: 100px;
}
.tool-button .optional-label {
display: none;
}
}
@media (max-width: 590px) {
.brand h1 {
font-size: 13px;
}
.brand-mark {
width: 34px;
height: 34px;
}
.module-panel {
display: none;
}
.diagnostics-panel {
width: 210px;
}
.diagnostic-summary {
gap: 3px;
}
.summary-cell {
padding: 7px 3px;
}
.selection-summary {
display: none;
}
.toolbar {
gap: 5px;
max-width: calc(100vw - 16px);
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<header class="topbar">
<div class="brand glass">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4z" stroke="currentColor" stroke-width="1.7"/>
<path d="M14 14h6v6h-6z" fill="currentColor" opacity=".5"/>
</svg>
</div>
<div>
<h1>ROOMFLOW</h1>
<p>RIGID MODULE PLANNER</p>
</div>
</div>
<div class="top-actions">
<button id="issueCounter" class="top-action" type="button" title="Show diagnostics">
<span class="issue-counter">
<span id="counterDot" class="counter-dot"></span>
<span id="openCount">0 open issues</span>
</span>
</button>
<button id="diagnosticsToggle" class="top-action active" type="button">
Diagnostics on
</button>
<button id="cameraButton" class="top-action" type="button">
Fit view
</button>
</div>
</header>
<div class="hint">DRAG ROOM · R ROTATE · ARROWS NUDGE · RIGHT-DRAG ORBIT · WHEEL ZOOM</div>
<aside class="panel module-panel glass">
<div class="panel-header">
<div class="panel-title-row">
<h2>Room modules</h2>
<span class="count-badge">4 rigid</span>
</div>
<p class="panel-subtitle">Modules keep their original dimensions and clear interior area.</p>
</div>
<div id="moduleList" class="module-list"></div>
<div class="rigid-note">
<span class="lock-icon">◆</span>
<span>Geometry is locked. Moving and rotating never scale a room or alter its furniture.</span>
</div>
</aside>
<aside class="panel diagnostics-panel glass">
<div class="panel-header">
<div class="panel-title-row">
<h2>Live diagnostics</h2>
<span id="diagnosticBadge" class="count-badge">All clear</span>
</div>
<p class="panel-subtitle">Entrances, corridor clearance, and service connections update as you move.</p>
</div>
<div class="diagnostic-summary">
<div class="summary-cell">
<strong id="doorCount">0</strong>
<span>Doors</span>
</div>
<div class="summary-cell">
<strong id="corridorCount">0</strong>
<span>Corridors</span>
</div>
<div class="summary-cell">
<strong id="serviceCount">0</strong>
<span>Services</span>
</div>
</div>
<div id="issueList" class="issue-list" aria-live="polite"></div>
</aside>
<div class="toolbar glass">
<div class="selection-summary">
<strong id="selectedName">Studio</strong>
<span id="selectedMeta">7 × 5 m · 32 m² clear</span>
</div>
<button id="rotateButton" class="tool-button" type="button" title="Rotate selected module 90 degrees">
↻ <span class="optional-label">Rotate</span>
</button>
<div class="arrow-pad" aria-label="Nudge selected module">
<button data-nudge="0,-1" type="button" title="Move north">↑</button>
<button data-nudge="-1,0" type="button" title="Move west">←</button>
<button data-nudge="0,1" type="button" title="Move south">↓</button>
<button data-nudge="1,0" type="button" title="Move east">→</button>
</div>
<div class="divider"></div>
<button id="snapButton" class="tool-button active" type="button">
Snap 0.5m
</button>
<button id="autoArrangeButton" class="tool-button primary" type="button">
Restore plan
</button>
</div>
<div class="legend glass">
<span class="legend-item"><span class="legend-swatch green"></span>Connected</span>
<span class="legend-item"><span class="legend-swatch red"></span>Disconnected</span>
<span class="legend-item"><span class="legend-swatch amber"></span>Blocked</span>
<span class="legend-item"><span class="legend-swatch magenta"></span>Service offset</span>
</div>
<div id="toast" class="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const moduleList = document.getElementById("moduleList");
const issueList = document.getElementById("issueList");
const toast = document.getElementById("toast");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xedf0e9);
scene.fog = new THREE.Fog(0xedf0e9, 45, 85);
const camera = new THREE.OrthographicCamera(-20, 20, 12, -12, 0.1, 150);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xffffff, 0xa8b3aa, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff5df, 3.1);
sun.position.set(-13, 24, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 28;
sun.shadow.camera.bottom = -28;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 70;
sun.shadow.bias = -0.0003;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xc9e1ef, 0.7);
fill.position.set(18, 12, -18);
scene.add(fill);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xe8ece5,
roughness: 1,
metalness: 0
});
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.055;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(80, 80, 0xbfc8c0, 0xd5dcd5);
grid.position.y = -0.035;
grid.material.transparent = true;
grid.material.opacity = 0.45;
scene.add(grid);
const baseFrame = new THREE.Mesh(
new THREE.BoxGeometry(31, 0.12, 18),
new THREE.MeshStandardMaterial({
color: 0xe1e6df,
roughness: 0.95
})
);
baseFrame.position.set(-1.5, -0.02, -2.7);
baseFrame.receiveShadow = true;
scene.add(baseFrame);
const overlayGroup = new THREE.Group();
scene.add(overlayGroup);
const moduleDefinitions = [
{
id: "entry",
name: "Entry Hall",
color: 0xe07b60,
w: 8,
d: 6,
clearArea: 46,
position: [-7.5, 0],
rotation: 0,
initialPosition: [-7.5, 0],
initialRotation: 0,
ports: [
{
id: "entry-door",
kind: "entrance",
side: "east",
along: 0,
pair: "entry-studio"
},
{
id: "entry-service",
kind: "service",
side: "east",
along: 1.7,
pair: "entry-service"
}
]
},
{
id: "studio",
name: "Studio",
color: 0x52b5a6,
w: 7,
d: 5,
clearArea: 32,
position: [0, 0],
rotation: 0,
initialPosition: [0, 0],
initialRotation: 0,
ports: [
{
id: "studio-west-door",
kind: "entrance",
side: "west",
along: 0,
pair: "entry-studio"
},
{
id: "studio-west-service",
kind: "service",
side: "west",
along: 1.7,
pair: "entry-service"
},
{
id: "studio-east-door",
kind: "entrance",
side: "east",
along: 0,
pair: "studio-utility"
},
{
id: "studio-east-service",
kind: "service",
side: "east",
along: -1.6,
pair: "studio-utility-service"
},
{
id: "studio-north-door",
kind: "entrance",
side: "north",
along: 0,
pair: "studio-bedroom"
}
]
},
{
id: "bedroom",
name: "Bedroom",
color: 0x6c8fd3,
w: 6,
d: 6,
clearArea: 34,
position: [0, -5.5],
rotation: 0,
initialPosition: [0, -5.5],
initialRotation: 0,
ports: [
{
id: "bedroom-south-door",
kind: "entrance",
side: "south",
along: 0,
pair: "studio-bedroom"
}
]
},
{
id: "utility",
name: "Utility",
color: 0xd6ad58,
w: 5,
d: 5,
clearArea: 22,
position: [6, 0],
rotation: 0,
initialPosition: [6, 0],
initialRotation: 0,
ports: [
{
id: "utility-west-door",
kind: "entrance",
side: "west",
along: 0,
pair: "studio-utility"
},
{
id: "utility-west-service",
kind: "service",
side: "west",
along: -1.6,
pair: "studio-utility-service"
}
]
}
];
const pairDefinitions = [
{
id: "entry-studio",
kind: "entrance",
a: ["entry", "entry-door"],
b: ["studio", "studio-west-door"],
label: "Entry Hall ↔ Studio"
},
{
id: "studio-bedroom",
kind: "entrance",
a: ["studio", "studio-north-door"],
b: ["bedroom", "bedroom-south-door"],
label: "Studio ↔ Bedroom"
},
{
id: "studio-utility",
kind: "entrance",
a: ["studio", "studio-east-door"],
b: ["utility", "utility-west-door"],
label: "Studio ↔ Utility"
},
{
id: "entry-service",
kind: "service",
a: ["entry", "entry-service"],
b: ["studio", "studio-west-service"],
label: "Entry Hall ↔ Studio service"
},
{
id: "studio-utility-service",
kind: "service",
a: ["studio", "studio-east-service"],
b: ["utility", "utility-west-service"],
label: "Studio ↔ Utility service"
}
];
const modules = new Map();
const moduleGroups = [];
const portVisuals = new Map();
let selectedId = "studio";
let showDiagnostics = true;
let snapEnabled = true;
let diagnostics = {
pairStatus: new Map(),
issues: [],
moduleState: new Map()
};
const baseFrustum = 23;
const cameraTarget = new THREE.Vector3(-1.4, 0, -2.5);
let cameraAzimuth = -0.72;
let cameraPolar = 0.77;
let cameraRadius = 42;
function addBox(parent, width, height, depth, x, y, z, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabelTexture(def) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 176;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
const x = 14;
const y = 14;
const width = 612;
const height = 146;
const radius = 24;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
ctx.fillStyle = "rgba(255,255,255,0.94)";
ctx.fill();
ctx.strokeStyle = "rgba(45,60,70,0.12)";
ctx.lineWidth = 3;
ctx.stroke();
const hex = "#" + def.color.toString(16).padStart(6, "0");
ctx.fillStyle = hex;
ctx.fillRect(x + 20, y + 25, 10, 94);
ctx.beginPath();
ctx.arc(x + 35, y + 40, 8, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#293840";
ctx.font = "700 34px system-ui, sans-serif";
ctx.textBaseline = "top";
ctx.fillText(def.name.toUpperCase(), x + 58, y + 24);
ctx.fillStyle = "#73818a";
ctx.font = "500 23px system-ui, sans-serif";
ctx.fillText(
`${def.w.toFixed(1)} × ${def.d.toFixed(1)} m · ${def.clearArea} m² clear`,
x + 58,
y + 78
);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
return texture;
}
function createLabel(def) {
const material = new THREE.SpriteMaterial({
map: makeLabelTexture(def),
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.position.set(0, 2.15, 0);
sprite.scale.set(4.25, 1.17, 1);
sprite.renderOrder = 8;
return sprite;
}
function createSelectionOutline(def) {
const points = [
new THREE.Vector3(-def.w / 2 - 0.1, 0.285, -def.d / 2 - 0.1),
new THREE.Vector3(def.w / 2 + 0.1, 0.285, -def.d / 2 - 0.1),
new THREE.Vector3(def.w / 2 + 0.1, 0.285, def.d / 2 + 0.1),
new THREE.Vector3(-def.w / 2 - 0.1, 0.285, def.d / 2 + 0.1)
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0x293a43,
transparent: true,
opacity: 0.9,
depthTest: false
});
const outline = new THREE.LineLoop(geometry, material);
outline.renderOrder = 7;
outline.visible = false;
return outline;
}
function buildWallSide(group, def, side, openings, material) {
const wallHeight = 0.78;
const thickness = 0.16;
const isVertical = side === "east" || side === "west";
const length = isVertical ? def.d : def.w;
const fixed = side === "east"
? def.w / 2 - thickness / 2
: side === "west"
? -def.w / 2 + thickness / 2
: side === "north"
? -def.d / 2 + thickness / 2
: def.d / 2 - thickness / 2;
const sorted = [...openings].sort((a, b) => a.center - b.center);
const segments = [];
let cursor = -length / 2;
for (const opening of sorted) {
const start = opening.center - opening.width / 2;
const end = opening.center + opening.width / 2;
if (start > cursor) {
segments.push([cursor, Math.min(start, length / 2)]);
}
cursor = Math.max(cursor, end);
}
if (cursor < length / 2) {
segments.push([cursor, length / 2]);
}
for (const [start, end] of segments) {
const segmentLength = end - start;
if (segmentLength <= 0.02) continue;
const center = (start + end) / 2;
if (isVertical) {
addBox(
group,
thickness,
wallHeight,
segmentLength,
fixed,
0.22 + wallHeight / 2,
center,
material
);
} else {
addBox(
group,
segmentLength,
wallHeight,
thickness,
center,
0.22 + wallHeight / 2,
fixed,
material
);
}
}
}
function createDoorVisual(group, def, port) {
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x2f9c73,
emissive: 0x2f9c73,
emissiveIntensity: 0.18,
roughness: 0.55,
metalness: 0.05
});
const stripMaterial = new THREE.MeshBasicMaterial({
color: 0x2f9c73,
transparent: true,
opacity: 0.82
});
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0x2f9c73
});
const vertical = port.side === "east" || port.side === "west";
const sign = port.side === "east" || port.side === "south" ? 1 : -1;
const halfGap = 0.73;
if (vertical) {
const x = sign * def.w / 2;
addBox(group, 0.14, 1.15, 0.11, x, 0.795, port.along - halfGap, frameMaterial);
addBox(group, 0.14, 1.15, 0.11, x, 0.795, port.along + halfGap, frameMaterial);
addBox(group, 0.14, 0.12, 1.57, x, 1.36, port.along, frameMaterial);
addBox(
group,
0.68,
0.025,
1.08,
x - sign * 0.36,
0.245,
port.along,
stripMaterial
);
} else {
const z = sign * def.d / 2;
addBox(group, 0.11, 1.15, 0.14, port.along - halfGap, 0.795, z, frameMaterial);
addBox(group, 0.11, 1.15, 0.14, port.along + halfGap, 0.795, z, frameMaterial);
addBox(group, 1.57, 0.12, 0.14, port.along, 1.36, z, frameMaterial);
addBox(
group,
1.08,
0.025,
0.68,
port.along,
0.245,
z - sign * 0.36,
stripMaterial
);
}
const normal = sideNormal(port.side);
const inward = new THREE.Vector3(-normal.x, 0, -normal.z);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.17, 0.43, 3),
arrowMaterial
);
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
inward
);
const center = portLocalPosition(def, port);
arrow.position.set(
center.x - normal.x * 0.74,
0.34,
center.z - normal.z * 0.74
);
group.add(arrow);
return {
pair: port.pair,
kind: "entrance",
materials: [frameMaterial, stripMaterial, arrowMaterial],
pulseMaterials: [frameMaterial]
};
}
function createServiceVisual(group, def, port) {
const material = new THREE.MeshStandardMaterial({
color: 0x2f9c73,
emissive: 0x2f9c73,
emissiveIntensity: 0.22,
roughness: 0.42,
metalness: 0.22
});
const center = portLocalPosition(def, port);
const vertical = port.side === "east" || port.side === "west";
const sign = port.side === "east" || port.side === "south" ? 1 : -1;
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.19, 0.047, 6, 18),
material
);
ring.position.set(center.x, 0.73, center.z);
if (vertical) ring.rotation.y = Math.PI / 2;
ring.castShadow = true;
group.add(ring);
const pipe = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 0.42, 8),
material
);
pipe.position.set(center.x, 0.73, center.z);
if (vertical) {
pipe.rotation.z = Math.PI / 2;
pipe.position.x -= sign * 0.12;
} else {
pipe.rotation.x = Math.PI / 2;
pipe.position.z -= sign * 0.12;
}
pipe.castShadow = true;
group.add(pipe);
return {
pair: port.pair,
kind: "service",
materials: [material],
pulseMaterials: [material]
};
}
function sideNormal(side) {
if (side === "east") return new THREE.Vector2(1, 0);
if (side === "west") return new THREE.Vector2(-1, 0);
if (side === "north") return new THREE.Vector2(0, -1);
return new THREE.Vector2(0, 1);
}
function portLocalPosition(def, port) {
if (port.side === "east") {
return new THREE.Vector2(def.w / 2, port.along);
}
if (port.side === "west") {
return new THREE.Vector2(-def.w / 2, port.along);
}
if (port.side === "north") {
return new THREE.Vector2(port.along, -def.d / 2);
}
return new THREE.Vector2(port.along, def.d / 2);
}
function furnishModule(group, def) {
const neutral = new THREE.MeshStandardMaterial({
color: 0xd8d8cd,
roughness: 0.9
});
const wood = new THREE.MeshStandardMaterial({
color: 0x9f7754,
roughness: 0.86
});
const dark = new THREE.MeshStandardMaterial({
color: 0x43535a,
roughness: 0.74
});
const fabric = new THREE.MeshStandardMaterial({
color: new THREE.Color(def.color).lerp(new THREE.Color(0xffffff), 0.2),
roughness: 1
});
if (def.id === "entry") {
addBox(group, 2.8, 0.8, 1.05, -1.55, 0.62, -0.9, wood);
addBox(group, 2.35, 0.12, 0.75, -1.55, 1.06, -0.9, neutral);
addBox(group, 1.8, 0.38, 0.72, 1.35, 0.41, -1.55, dark);
addBox(group, 0.7, 0.85, 0.7, -2.75, 0.645, 1.55, neutral);
}
if (def.id === "studio") {
addBox(group, 2.5, 0.38, 0.95, -1.55, 0.41, -1.25, fabric);
addBox(group, 2.5, 0.55, 0.18, -1.55, 0.65, -1.67, fabric);
addBox(group, 0.18, 0.55, 0.95, -2.7, 0.65, -1.25, fabric);
addBox(group, 0.18, 0.55, 0.95, -0.4, 0.65, -1.25, fabric);
addBox(group, 1.45, 0.12, 1.05, 1.15, 0.72, 0.65, wood);
addBox(group, 0.14, 0.5, 0.14, 1.15, 0.47, 0.65, dark);
}
if (def.id === "bedroom") {
addBox(group, 2.65, 0.28, 3.25, 0, 0.36, -0.85, wood);
addBox(group, 2.5, 0.3, 3.05, 0, 0.65, -0.85, neutral);
addBox(group, 2.45, 0.1, 1.05, 0, 0.85, -1.95, fabric);
addBox(group, 1.0, 0.16, 0.55, -0.62, 0.9, -2.05, neutral);
addBox(group, 1.0, 0.16, 0.55, 0.62, 0.9, -2.05, neutral);
addBox(group, 0.72, 0.58, 0.72, -2.05, 0.51, -0.55, wood);
addBox(group, 0.72, 0.58, 0.72, 2.05, 0.51, -0.55, wood);
}
if (def.id === "utility") {
addBox(group, 2.8, 0.72, 0.8, 0.65, 0.58, -1.45, neutral);
const tankMaterial = new THREE.MeshStandardMaterial({
color: 0x9caeb0,
roughness: 0.55,
metalness: 0.28
});
for (const x of [-1.25, 0.1]) {
const tank = new THREE.Mesh(
new THREE.CylinderGeometry(0.48, 0.48, 1.2, 10),
tankMaterial
);
tank.position.set(x, 0.82, 0.7);
tank.castShadow = true;
group.add(tank);
}
addBox(group, 1.15, 0.68, 0.7, -1.55, 0.56, 0.85, wood);
}
}
function createModule(def) {
const group = new THREE.Group();
group.userData.moduleId = def.id;
group.position.set(def.position[0], 0, def.position[1]);
group.rotation.y = def.rotation;
const slabMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(def.color).lerp(new THREE.Color(0xffffff), 0.64),
roughness: 0.86
});
const floorMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(def.color).lerp(new THREE.Color(0xffffff), 0.78),
roughness: 0.92
});
const wallMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(def.color).lerp(new THREE.Color(0xffffff), 0.48),
roughness: 0.83
});
addBox(
group,
def.w,
0.22,
def.d,
0,
0.11,
0,
slabMaterial
);
addBox(
group,
def.w - 0.28,
0.035,
def.d - 0.28,
0,
0.235,
0,
floorMaterial
);
const openingsBySide = {
east: [],
west: [],
north: [],
south: []
};
for (const port of def.ports) {
if (port.kind === "entrance") {
openingsBySide[port.side].push({
center: port.along,
width: 1.4
});
}
}
for (const side of ["east", "west", "north", "south"]) {
buildWallSide(group, def, side, openingsBySide[side], wallMaterial);
}
furnishModule(group, def);
for (const port of def.ports) {
const visual = port.kind === "entrance"
? createDoorVisual(group, def, port)
: createServiceVisual(group, def, port);
portVisuals.set(`${def.id}:${port.id}`, visual);
}
const label = createLabel(def);
group.add(label);
const selection = createSelectionOutline(def);
group.add(selection);
scene.add(group);
moduleGroups.push(group);
const record = {
def,
group,
selection,
ports: def.ports
};
modules.set(def.id, record);
return record;
}
moduleDefinitions.forEach(createModule);
function worldPort(moduleId, portId) {
const module = modules.get(moduleId);
const def = module.def;
const port = module.ports.find((item) => item.id === portId);
const local = portLocalPosition(def, port);
const normal = sideNormal(port.side);
const c = Math.cos(def.rotation);
const s = Math.sin(def.rotation);
const x = def.position[0] + c * local.x + s * local.y;
const z = def.position[1] - s * local.x + c * local.y;
const nx = c * normal.x + s * normal.y;
const nz = -s * normal.x + c * normal.y;
return {
position: new THREE.Vector3(x, 0.34, z),
normal: new THREE.Vector3(nx, 0, nz),
distance: Math.hypot(nx, nz),
port,
module
};
}
function transformToLocal(module, point) {
const def = module.def;
const c = Math.cos(def.rotation);
const s = Math.sin(def.rotation);
const dx = point.x - def.position[0];
const dz = point.z - def.position[1];
return {
x: c * dx - s * dz,
z: s * dx + c * dz
};
}
function transformDirectionToLocal(module, direction) {
const def = module.def;
const c = Math.cos(def.rotation);
const s = Math.sin(def.rotation);
return {
x: c * direction.x - s * direction.z,
z: s * direction.x + c * direction.z
};
}
function rayHitsModule(origin, direction, module, maxT) {
const localOrigin = transformToLocal(module, origin);
const localDirection = transformDirectionToLocal(module, direction);
const def = module.def;
let tMin = 0;
let tMax = maxT;
const axes = [
{
origin: localOrigin.x,
direction: localDirection.x,
min: -def.w / 2,
max: def.w / 2
},
{
origin: localOrigin.z,
direction: localDirection.z,
min: -def.d / 2,
max: def.d / 2
}
];
for (const axis of axes) {
if (Math.abs(axis.direction) < 1e-7) {
if (axis.origin < axis.min || axis.origin > axis.max) {
return null;
}
} else {
let t1 = (axis.min - axis.origin) / axis.direction;
let t2 = (axis.max - axis.origin) / axis.direction;
if (t1 > t2) [t1, t2] = [t2, t1];
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMax < tMin) return null;
}
}
return tMin;
}
function segmentHitsModule(start, end, module) {
const direction = end.clone().sub(start);
return rayHitsModule(start, direction, module, 1);
}
function findCorridorBlockers(pair, endpointA, endpointB) {
const blockers = [];
for (const module of modules.values()) {
if (module.def.id === pair.a[0]) continue;
const rayHit = rayHitsModule(
endpointA.position,
endpointA.normal,
module,
3.4
);
if (rayHit !== null && rayHit > 0.04) {
blockers.push({
name: module.def.name,
t: rayHit,
point: endpointA.position
.clone()
.addScaledVector(endpointA.normal, rayHit)
});
}
}
for (const module of modules.values()) {
if (module.def.id === pair.a[0] || module.def.id === pair.b[0]) {
continue;
}
const segmentHit = segmentHitsModule(
endpointA.position,
endpointB.position,
module
);
if (segmentHit !== null && segmentHit > 0.03 && segmentHit < 0.97) {
blockers.push({
name: module.def.name,
t: segmentHit,
point: endpointA.position.clone().lerp(endpointB.position, segmentHit)
});
}
}
blockers.sort((a, b) => a.t - b.t);
return blockers;
}
function computeDiagnostics() {
const pairStatus = new Map();
const issues = [];
const moduleIssueCounts = new Map();
for (const moduleId of modules.keys()) {
moduleIssueCounts.set(moduleId, 0);
}
for (const pair of pairDefinitions) {
const endpointA = worldPort(pair.a[0], pair.a[1]);
const endpointB = worldPort(pair.b[0], pair.b[1]);
const dx = endpointB.position.x - endpointA.position.x;
const dz = endpointB.position.z - endpointA.position.z;
const distance = Math.hypot(dx, dz);
const normalDot = endpointA.normal.dot(endpointB.normal);
if (pair.kind === "entrance") {
const aligned = distance <= 0.65 && normalDot <= -0.72;
const blockers = aligned
? []
: findCorridorBlockers(pair, endpointA, endpointB);
let status = "disconnected";
let detail = "";
if (aligned) {
status = "connected";
} else if (blockers.length || distance <= 3.4) {
status = "blocked";
detail = blockers.length
? `Corridor intersects ${blockers[0].name}.`
: `A ${distance.toFixed(1)} m gap interrupts the route.`;
} else {
detail = `Entrances are ${distance.toFixed(1)} m apart.`;
}
pairStatus.set(pair.id, {
status,
distance,
normalDot,
blockers,
endpointA,
endpointB
});
if (status === "disconnected") {
issues.push({
kind: "disconnected",
pairId: pair.id,
title: "Disconnected entrance",
detail: `${pair.label} · ${detail}`,
moduleId: pair.a[0]
});
moduleIssueCounts.set(pair.a[0], moduleIssueCounts.get(pair.a[0]) + 1);
moduleIssueCounts.set(pair.b[0], moduleIssueCounts.get(pair.b[0]) + 1);
}
if (status === "blocked") {
issues.push({
kind: "blocked",
pairId: pair.id,
title: "Blocked corridor",
detail: `${pair.label} · ${detail}`,
moduleId: pair.a[0]
});
moduleIssueCounts.set(pair.a[0], moduleIssueCounts.get(pair.a[0]) + 1);
moduleIssueCounts.set(pair.b[0], moduleIssueCounts.get(pair.b[0]) + 1);
}
} else {
const aligned = distance <= 0.55 && normalDot <= -0.82;
const status = aligned ? "connected" : "misaligned";
const detail = normalDot >= 0
? "Connector faces are not opposing."
: `Connectors are ${distance.toFixed(2)} m out of alignment.`;
pairStatus.set(pair.id, {
status,
distance,
normalDot,
endpointA,
endpointB
});
if (!aligned) {
issues.push({
kind: "service",
pairId: pair.id,
title: "Misaligned service connector",
detail: `${pair.label} · ${detail}`,
moduleId: pair.a[0]
});
moduleIssueCounts.set(pair.a[0], moduleIssueCounts.get(pair.a[0]) + 1);
moduleIssueCounts.set(pair.b[0], moduleIssueCounts.get(pair.b[0]) + 1);
}
}
}
const moduleState = new Map();
for (const [moduleId, count] of moduleIssueCounts) {
let worst = "good";
for (const port of modules.get(moduleId).ports) {
const status = pairStatus.get(port.pair)?.status;
if (status === "blocked") worst = "blocked";
else if (status === "misaligned" && worst !== "blocked") worst = "service";
else if (status === "disconnected" && worst === "good") worst = "disconnected";
}
moduleState.set(moduleId, { count, worst });
}
diagnostics = { pairStatus, issues, moduleState };
updateVisuals();
updateOverlays();
renderUI();
}
function updateVisuals() {
const connected = new THREE.Color(0x2f9c73);
const disconnected = new THREE.Color(0xdf5a58);
const blocked = new THREE.Color(0xe79a38);
const service = new THREE.Color(0xbb57ae);
const neutral = new THREE.Color(0x81919a);
for (const [key, visual] of portVisuals) {
const pair = diagnostics.pairStatus.get(visual.pair);
let color = neutral;
if (showDiagnostics && pair) {
if (visual.kind === "entrance") {
color =
pair.status === "connected"
? connected
: pair.status === "blocked"
? blocked
: disconnected;
} else {
color = pair.status === "connected" ? connected : service;
}
}
for (const material of visual.materials) {
material.color.copy(color);
if (material.emissive) {
material.emissive.copy(color);
}
}
}
}
function clearOverlay() {
while (overlayGroup.children.length) {
const child = overlayGroup.children.pop();
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach((material) => material.dispose());
} else {
object.material.dispose();
}
}
});
}
}
function addDashedLine(start, end, color, opacity = 0.9) {
const geometry = new THREE.BufferGeometry().setFromPoints([
start.clone(),
end.clone()
]);
const material = new THREE.LineDashedMaterial({
color,
dashSize: 0.28,
gapSize: 0.18,
transparent: true,
opacity,
depthTest: false
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
line.renderOrder = 10;
overlayGroup.add(line);
}
function addBlockedCorridor(pairData) {
const a = pairData.endpointA.position;
const b = pairData.endpointB.position;
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
if (length > 0.08) {
const material = new THREE.MeshBasicMaterial({
color: 0xe79a38,
transparent: true,
opacity: 0.24,
depthWrite: false,
side: THREE.DoubleSide
});
const corridor = new THREE.Mesh(
new THREE.BoxGeometry(1.3, 0.025, length + 0.35),
material
);
corridor.position.set(
(a.x + b.x) / 2,
0.29,
(a.z + b.z) / 2
);
corridor.rotation.y = Math.atan2(dx, dz);
corridor.renderOrder = 4;
overlayGroup.add(corridor);
addDashedLine(
new THREE.Vector3(a.x, 0.34, a.z),
new THREE.Vector3(b.x, 0.34, b.z),
0xd47e1e,
0.95
);
}
if (pairData.blockers.length) {
const point = pairData.blockers[0].point;
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.24, 0.34, 24),
new THREE.MeshBasicMaterial({
color: 0xe79a38,
transparent: true,
opacity: 0.85,
side: THREE.DoubleSide,
depthTest: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(point.x, 0.35, point.z);
ring.renderOrder = 10;
overlayGroup.add(ring);
}
}
function updateOverlays() {
clearOverlay();
if (!showDiagnostics) return;
for (const pair of pairDefinitions) {
const data = diagnostics.pairStatus.get(pair.id);
if (!data) continue;
if (pair.kind === "entrance" && data.status === "blocked") {
addBlockedCorridor(data);
}
if (pair.kind === "entrance" && data.status === "disconnected") {
addDashedLine(
data.endpointA.position,
data.endpointB.position,
0xdf5a58,
0.72
);
}
if (pair.kind === "service" && data.status === "misaligned") {
addDashedLine(
data.endpointA.position,
data.endpointB.position,
0xbb57ae,
0.92
);
}
}
}
function statusPill(state) {
if (!state || state.count === 0) {
return { label: "Aligned", className: "good" };
}
if (state.worst === "blocked") {
return { label: "Corridor blocked", className: "warning" };
}
if (state.worst === "service") {
return { label: "Service offset", className: "error" };
}
return { label: "Door open", className: "error" };
}
function renderUI() {
moduleList.innerHTML = moduleDefinitions.map((def) => {
const state = diagnostics.moduleState.get(def.id);
const pill = statusPill(state);
const selected = def.id === selectedId;
const color = "#" + def.color.toString(16).padStart(6, "0");
return `
<button
class="module-card ${selected ? "selected" : ""}"
type="button"
data-module="${def.id}"
style="--module-color:${color}"
>
<span class="module-swatch"></span>
<span class="module-copy">
<strong>${def.name}</strong>
<small>${def.w.toFixed(1)} × ${def.d.toFixed(1)} m · ${def.clearArea} m² clear</small>
</span>
<span class="status-pill ${pill.className}">${pill.label}</span>
<span class="module-coords">
x ${def.position[0].toFixed(1)} · z ${def.position[1].toFixed(1)} · ${Math.round(THREE.MathUtils.radToDeg(def.rotation))}°
</span>
</button>
`;
}).join("");
const disconnectedCount = diagnostics.issues.filter(
(issue) => issue.kind === "disconnected"
).length;
const blockedCount = diagnostics.issues.filter(
(issue) => issue.kind === "blocked"
).length;
const serviceCount = diagnostics.issues.filter(
(issue) => issue.kind === "service"
).length;
document.getElementById("openCount").textContent =
`${diagnostics.issues.length} open issue${diagnostics.issues.length === 1 ? "" : "s"}`;
document.getElementById("doorCount").textContent = disconnectedCount;
document.getElementById("corridorCount").textContent = blockedCount;
document.getElementById("serviceCount").textContent = serviceCount;
document.getElementById("counterDot").classList.toggle(
"has-issues",
diagnostics.issues.length > 0
);
const badge = document.getElementById("diagnosticBadge");
badge.textContent = diagnostics.issues.length
? `${diagnostics.issues.length} issue${diagnostics.issues.length === 1 ? "" : "s"}`
: "All clear";
if (diagnostics.issues.length === 0) {
issueList.innerHTML = `
<div class="empty-state">
<div class="empty-icon">✓</div>
<strong>Everything is aligned</strong>
<span>
All entrances connect, corridors remain clear, and service connectors match.
</span>
</div>
`;
} else {
issueList.innerHTML = diagnostics.issues.map((issue) => `
<button class="issue-item" type="button" data-pair="${issue.pairId}">
<span class="issue-dot ${issue.kind}"></span>
<span class="issue-copy">
<strong>${issue.title}</strong>
<span>${issue.detail}</span>
</span>
</button>
`).join("");
}
const selected = modules.get(selectedId);
if (selected) {
document.getElementById("selectedName").textContent = selected.def.name;
document.getElementById("selectedMeta").textContent =
`${selected.def.w.toFixed(1)} × ${selected.def.d.toFixed(1)} m · ${selected.def.clearArea} m² clear`;
}
}
function selectModule(id) {
if (!modules.has(id)) return;
selectedId = id;
for (const [moduleId, module] of modules) {
module.selection.visible = moduleId === id;
}
renderUI();
}
function setModuleTransform(module, x, z) {
if (snapEnabled) {
x = Math.round(x * 2) / 2;
z = Math.round(z * 2) / 2;
}
module.def.position[0] = THREE.MathUtils.clamp(x, -24, 24);
module.def.position[1] = THREE.MathUtils.clamp(z, -18, 18);
module.group.position.x = module.def.position[0];
module.group.position.z = module.def.position[1];
}
function rotateSelected() {
const module = modules.get(selectedId);
if (!module) return;
module.def.rotation =
(module.def.rotation + Math.PI / 2) % (Math.PI * 2);
module.group.rotation.y = module.def.rotation;
scheduleDiagnostics();
showToast(`${module.def.name} rotated 90°`);
}
function nudgeSelected(dx, dz) {
const module = modules.get(selectedId);
if (!module) return;
setModuleTransform(
module,
module.def.position[0] + dx,
module.def.position[1] + dz
);
scheduleDiagnostics();
}
function restorePlan() {
for (const module of modules.values()) {
module.def.position[0] = module.def.initialPosition[0];
module.def.position[1] = module.def.initialPosition[1];
module.def.rotation = module.def.initialRotation;
module.group.position.set(
module.def.position[0],
0,
module.def.position[1]
);
module.group.rotation.y = module.def.rotation;
}
fitView();
scheduleDiagnostics();
showToast("Connected layout restored");
}
let toastTimer;
function showToast(message) {
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("visible");
}, 1700);
}
let diagnosticsQueued = false;
function scheduleDiagnostics() {
if (diagnosticsQueued) return;
diagnosticsQueued = true;
requestAnimationFrame(() => {
diagnosticsQueued = false;
computeDiagnostics();
});
}
function updateCamera() {
const sinPolar = Math.sin(cameraPolar);
const cosPolar = Math.cos(cameraPolar);
camera.position.set(
cameraTarget.x + cameraRadius * sinPolar * Math.sin(cameraAzimuth),
cameraTarget.y + cameraRadius * cosPolar,
cameraTarget.z + cameraRadius * sinPolar * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
camera.updateProjectionMatrix();
}
function fitView() {
let minX = Infinity;
let maxX = -Infinity;
let minZ = Infinity;
let maxZ = -Infinity;
for (const module of modules.values()) {
const def = module.def;
const c = Math.abs(Math.cos(def.rotation));
const s = Math.abs(Math.sin(def.rotation));
const halfX = c * def.w / 2 + s * def.d / 2;
const halfZ = s * def.w / 2 + c * def.d / 2;
minX = Math.min(minX, def.position[0] - halfX);
maxX = Math.max(maxX, def.position[0] + halfX);
minZ = Math.min(minZ, def.position[1] - halfZ);
maxZ = Math.max(maxZ, def.position[1] + halfZ);
}
const width = maxX - minX + 3;
const depth = maxZ - minZ + 3;
const aspect = window.innerWidth / window.innerHeight;
const requiredHeight = Math.max(depth * 1.35, (width * 1.22) / aspect);
cameraTarget.set(
(minX + maxX) / 2,
0,
(minZ + maxZ) / 2
);
camera.zoom = THREE.MathUtils.clamp(
baseFrustum / Math.max(requiredHeight, 1),
0.7,
1.35
);
updateCamera();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
camera.left = (-baseFrustum * aspect) / 2;
camera.right = (baseFrustum * aspect) / 2;
camera.top = baseFrustum / 2;
camera.bottom = -baseFrustum / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resize();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.24);
const dragPoint = new THREE.Vector3();
const dragOffset = new THREE.Vector3();
let pointerMode = null;
let draggedModule = null;
let previousPointer = { x: 0, y: 0 };
let spacePressed = false;
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function findModuleId(object) {
let current = object;
while (current) {
if (current.userData.moduleId) return current.userData.moduleId;
current = current.parent;
}
return null;
}
function panCamera(dx, dy) {
const scale = (baseFrustum / camera.zoom) / renderer.domElement.clientHeight;
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 1);
up.y = 0;
if (up.lengthSq() < 0.0001) up.set(0, 0, -1);
up.normalize();
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(up, dy * scale);
updateCamera();
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
updatePointer(event);
previousPointer = { x: event.clientX, y: event.clientY };
renderer.domElement.setPointerCapture(event.pointerId);
if (event.button === 2) {
pointerMode = "orbit";
return;
}
if (event.button === 1) {
pointerMode = "pan";
event.preventDefault();
return;
}
if (event.button !== 0) return;
if (event.shiftKey || spacePressed) {
pointerMode = "pan";
return;
}
const hits = raycaster.intersectObjects(moduleGroups, true);
const moduleId = hits.length ? findModuleId(hits[0].object) : null;
if (moduleId) {
selectModule(moduleId);
draggedModule = modules.get(moduleId);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
dragOffset.set(
dragPoint.x - draggedModule.def.position[0],
0,
dragPoint.z - draggedModule.def.position[1]
);
pointerMode = "drag";
renderer.domElement.style.cursor = "grabbing";
}
} else {
pointerMode = "orbit";
renderer.domElement.style.cursor = "grabbing";
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerMode) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
previousPointer = { x: event.clientX, y: event.clientY };
if (pointerMode === "drag" && draggedModule) {
updatePointer(event);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
setModuleTransform(
draggedModule,
dragPoint.x - dragOffset.x,
dragPoint.z - dragOffset.z
);
scheduleDiagnostics();
}
} else if (pointerMode === "orbit") {
cameraAzimuth -= dx * 0.007;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar - dy * 0.006,
0.36,
1.25
);
updateCamera();
} else if (pointerMode === "pan") {
panCamera(dx, dy);
}
});
function endPointer(event) {
pointerMode = null;
draggedModule = null;
renderer.domElement.style.cursor = "default";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
const factor = Math.exp(-event.deltaY * 0.0012);
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * factor,
0.55,
2.7
);
updateCamera();
},
{ passive: false }
);
moduleList.addEventListener("click", (event) => {
const card = event.target.closest("[data-module]");
if (card) selectModule(card.dataset.module);
});
issueList.addEventListener("click", (event) => {
const item = event.target.closest("[data-pair]");
if (!item) return;
const issue = diagnostics.issues.find(
(entry) => entry.pairId === item.dataset.pair
);
if (issue) selectModule(issue.moduleId);
});
document.getElementById("rotateButton").addEventListener("click", rotateSelected);
document.querySelectorAll("[data-nudge]").forEach((button) => {
button.addEventListener("click", () => {
const [dx, dz] = button.dataset.nudge.split(",").map(Number);
nudgeSelected(dx, dz);
});
});
document.getElementById("snapButton").addEventListener("click", (event) => {
snapEnabled = !snapEnabled;
event.currentTarget.classList.toggle("active", snapEnabled);
event.currentTarget.textContent = snapEnabled ? "Snap 0.5m" : "Snap off";
showToast(snapEnabled ? "Grid snap enabled" : "Free positioning enabled");
});
document.getElementById("autoArrangeButton").addEventListener("click", restorePlan);
document.getElementById("cameraButton").addEventListener("click", fitView);
document.getElementById("diagnosticsToggle").addEventListener("click", (event) => {
showDiagnostics = !showDiagnostics;
event.currentTarget.classList.toggle("active", showDiagnostics);
event.currentTarget.textContent = showDiagnostics
? "Diagnostics on"
: "Diagnostics off";
updateVisuals();
updateOverlays();
});
document.getElementById("issueCounter").addEventListener("click", () => {
document.querySelector(".diagnostics-panel").scrollIntoView({
behavior: "smooth",
block: "nearest"
});
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
spacePressed = true;
event.preventDefault();
}
if (event.key.toLowerCase() === "r") {
rotateSelected();
}
const nudgeAmount = event.shiftKey ? 1 : 0.5;
if (event.key === "ArrowLeft") {
nudgeSelected(-nudgeAmount, 0);
event.preventDefault();
}
if (event.key === "ArrowRight") {
nudgeSelected(nudgeAmount, 0);
event.preventDefault();
}
if (event.key === "ArrowUp") {
nudgeSelected(0, -nudgeAmount);
event.preventDefault();
}
if (event.key === "ArrowDown") {
nudgeSelected(0, nudgeAmount);
event.preventDefault();
}
});
window.addEventListener("keyup", (event) => {
if (event.code === "Space") spacePressed = false;
});
selectModule(selectedId);
fitView();
computeDiagnostics();
function animate(time) {
requestAnimationFrame(animate);
const pulse = 0.5 + 0.5 * Math.sin(time * 0.004);
for (const visual of portVisuals.values()) {
const pair = diagnostics.pairStatus.get(visual.pair);
const isProblem =
pair &&
(pair.status === "disconnected" ||
pair.status === "blocked" ||
pair.status === "misaligned");
for (const material of visual.pulseMaterials) {
material.emissiveIntensity = isProblem
? 0.16 + pulse * 0.42
: 0.16;
}
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```