Prompt specification
Build or customize the Three.js 3D scene "Compact room transformation puzzle" 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: Compact room transformation puzzle
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/compact-room-transformation-puzzle-x0208
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing nesting tables. Build a room with nested tables, sofa, cabinet, and floor grid; users arrange accessible work surfaces while preserving enough open space for a moving delivery cart. Low-poly.
Working Three.js Starter (compact-room-transformation-puzzle-x0208):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>NEST — Accessible Room Planner</title>
<style>
:root {
--ink: #18342c;
--muted: #6d7d76;
--paper: #f8faf6;
--panel: #ffffff;
--line: #dfe6df;
--accent: #df704f;
--accent-soft: #fff0e9;
--green: #4d876c;
--green-soft: #e8f3ec;
--red: #c95445;
--red-soft: #fbe9e5;
--shadow: 0 18px 55px rgba(24, 52, 44, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9eee8;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
button:focus-visible,
input:focus-visible {
outline: 3px solid rgba(223, 112, 79, 0.28);
outline-offset: 2px;
}
#app {
display: grid;
grid-template-rows: 70px 1fr;
width: 100%;
height: 100%;
}
header {
position: relative;
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 22px;
background: rgba(248, 250, 246, 0.96);
border-bottom: 1px solid var(--line);
backdrop-filter: blur(12px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 190px;
}
.brand-mark {
position: relative;
width: 34px;
height: 34px;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
width: 21px;
height: 21px;
border: 2px solid var(--ink);
border-radius: 3px;
transform: rotate(30deg) skew(-5deg);
}
.brand-mark::before {
top: 1px;
left: 2px;
background: #f0c678;
}
.brand-mark::after {
right: 0;
bottom: 0;
background: #dcebe2;
}
.brand-name {
font-size: 20px;
font-weight: 800;
letter-spacing: 0.16em;
line-height: 1;
}
.brand-subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.project-heading {
flex: 1;
text-align: center;
}
.project-heading strong {
display: block;
font-size: 14px;
font-weight: 750;
}
.project-heading span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
}
.header-actions {
display: flex;
align-items: center;
gap: 8px;
}
.button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
min-height: 38px;
padding: 0 13px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fff;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: 160ms ease;
}
.button:hover {
border-color: #bdcbc2;
background: #f4f7f3;
transform: translateY(-1px);
}
.button:active {
transform: translateY(0);
}
.button.primary {
border-color: var(--ink);
background: var(--ink);
color: #fff;
}
.button.primary:hover {
background: #24483d;
}
.button.icon {
width: 38px;
padding: 0;
}
#planToggle {
display: none;
}
main {
position: relative;
min-height: 0;
overflow: hidden;
}
#viewport {
position: absolute;
inset: 0;
overflow: hidden;
background:
radial-gradient(circle at 55% 35%, rgba(255, 255, 255, 0.95), rgba(231, 237, 230, 0.82));
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#sidebar {
position: absolute;
z-index: 10;
top: 18px;
bottom: 18px;
left: 18px;
width: 292px;
overflow: auto;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 17px;
background: rgba(250, 251, 248, 0.95);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: #cbd6ce transparent;
}
.eyebrow {
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.sidebar-title {
margin: 6px 0 5px;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.04em;
}
.sidebar-intro {
margin: 0 0 19px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.section {
padding-top: 17px;
margin-top: 17px;
border-top: 1px solid var(--line);
}
.section:first-of-type {
border-top: 0;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.section-heading h2 {
margin: 0;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.section-heading span {
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
#itemList {
display: grid;
gap: 7px;
}
.furniture-item {
display: grid;
grid-template-columns: 36px 1fr 12px;
align-items: center;
gap: 10px;
width: 100%;
min-height: 54px;
padding: 8px 10px;
border: 1px solid transparent;
border-radius: 11px;
background: transparent;
text-align: left;
cursor: pointer;
transition: 150ms ease;
}
.furniture-item:hover {
background: #f0f4ef;
}
.furniture-item.active {
border-color: #cbdacf;
background: #edf4ef;
}
.item-swatch {
position: relative;
display: grid;
place-items: center;
width: 36px;
height: 36px;
overflow: hidden;
border-radius: 9px;
background: #e9eee8;
}
.item-swatch::before {
content: "";
width: 19px;
height: 13px;
border-radius: 2px;
background: var(--swatch);
box-shadow: 0 7px 0 -5px var(--swatch);
transform: perspective(35px) rotateX(8deg) rotateZ(-2deg);
}
.item-copy strong {
display: block;
margin-bottom: 4px;
font-size: 12px;
font-weight: 750;
}
.item-copy span {
display: block;
color: var(--muted);
font-size: 10px;
}
.item-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 3px var(--green-soft);
}
.selection-title {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 14px;
}
.selection-color {
width: 11px;
height: 32px;
border-radius: 5px;
background: var(--accent);
}
.selection-title strong {
display: block;
font-size: 14px;
}
.selection-title span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.field-label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.position-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.input-wrap {
position: relative;
}
.input-wrap span {
position: absolute;
top: 50%;
left: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
transform: translateY(-50%);
pointer-events: none;
}
.input-wrap input {
width: 100%;
height: 38px;
padding: 0 8px 0 27px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fff;
color: var(--ink);
font-size: 12px;
font-weight: 700;
}
.rotation-row {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 8px;
margin-top: 10px;
}
.rotation-row span {
min-width: 38px;
color: var(--muted);
font-size: 11px;
font-weight: 750;
text-align: center;
}
#heightRow {
margin-top: 15px;
}
.height-label {
display: flex;
justify-content: space-between;
margin-bottom: 9px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
}
.height-label strong {
color: var(--ink);
font-size: 12px;
}
input[type="range"] {
width: 100%;
height: 5px;
border-radius: 99px;
appearance: none;
background: #dce5dd;
accent-color: var(--accent);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #fff;
border-radius: 50%;
appearance: none;
background: var(--accent);
box-shadow: 0 2px 7px rgba(24, 52, 44, 0.22);
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #91a098;
font-size: 9px;
}
.check-card {
padding: 13px;
border: 1px solid #cfe0d4;
border-radius: 12px;
background: var(--green-soft);
transition: 180ms ease;
}
.check-card.blocked {
border-color: #edc3ba;
background: var(--red-soft);
}
.check-heading {
display: flex;
align-items: center;
gap: 9px;
font-size: 12px;
font-weight: 800;
}
.check-icon {
display: grid;
place-items: center;
width: 23px;
height: 23px;
border-radius: 50%;
background: var(--green);
color: #fff;
font-size: 12px;
}
.blocked .check-icon {
background: var(--red);
}
.check-detail {
margin: 7px 0 0 32px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 10px;
}
.metric {
padding: 9px;
border: 1px solid rgba(77, 135, 108, 0.14);
border-radius: 9px;
background: rgba(255, 255, 255, 0.56);
}
.metric strong {
display: block;
font-size: 14px;
}
.metric span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.tip-list {
display: grid;
gap: 9px;
margin: 0;
padding: 0;
list-style: none;
}
.tip-list li {
display: grid;
grid-template-columns: 20px 1fr;
gap: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.key {
display: inline-grid;
place-items: center;
min-width: 20px;
height: 20px;
padding: 0 5px;
border: 1px solid #cbd5ce;
border-bottom-width: 2px;
border-radius: 5px;
background: #fff;
color: var(--ink);
font-size: 9px;
font-weight: 800;
}
.room-pill {
position: absolute;
z-index: 4;
top: 20px;
left: 330px;
display: flex;
align-items: center;
gap: 10px;
padding: 9px 13px;
border: 1px solid rgba(255, 255, 255, 0.9);
border-radius: 99px;
background: rgba(255, 255, 255, 0.82);
box-shadow: 0 6px 24px rgba(24, 52, 44, 0.08);
backdrop-filter: blur(10px);
pointer-events: none;
}
.room-pill strong {
font-size: 11px;
}
.room-pill span {
color: var(--muted);
font-size: 10px;
}
.room-pill i {
width: 1px;
height: 14px;
background: var(--line);
}
.view-controls {
position: absolute;
z-index: 5;
top: 20px;
right: 20px;
display: flex;
gap: 6px;
padding: 5px;
border: 1px solid rgba(255, 255, 255, 0.85);
border-radius: 11px;
background: rgba(255, 255, 255, 0.86);
box-shadow: 0 8px 25px rgba(24, 52, 44, 0.09);
backdrop-filter: blur(10px);
}
.view-controls button {
height: 31px;
padding: 0 10px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
font-size: 10px;
font-weight: 750;
cursor: pointer;
}
.view-controls button:hover,
.view-controls button.active {
background: #eaf1eb;
color: var(--ink);
}
.legend {
position: absolute;
z-index: 4;
bottom: 22px;
left: 330px;
display: flex;
align-items: center;
gap: 14px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.9);
border-radius: 10px;
background: rgba(255, 255, 255, 0.86);
box-shadow: 0 8px 25px rgba(24, 52, 44, 0.08);
backdrop-filter: blur(10px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.legend-line {
width: 21px;
height: 7px;
border-radius: 2px;
background: rgba(77, 135, 108, 0.25);
border: 1px solid rgba(77, 135, 108, 0.42);
}
.legend-dash {
width: 21px;
border-top: 2px dashed var(--green);
}
.legend-cart {
position: relative;
width: 13px;
height: 9px;
border: 2px solid #4c6d60;
border-radius: 2px;
}
.legend-cart::before,
.legend-cart::after {
content: "";
position: absolute;
bottom: -5px;
width: 3px;
height: 3px;
border-radius: 50%;
background: #4c6d60;
}
.legend-cart::before {
left: 0;
}
.legend-cart::after {
right: 0;
}
#toast {
position: absolute;
z-index: 30;
left: 50%;
bottom: 25px;
max-width: min(420px, calc(100vw - 30px));
padding: 11px 15px;
border-radius: 10px;
background: var(--ink);
color: #fff;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 650;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition: 220ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
background: var(--red);
}
@media (max-width: 800px) {
#app {
grid-template-rows: 62px 1fr;
}
header {
padding: 0 12px;
}
.brand {
min-width: auto;
}
.brand-name {
font-size: 16px;
}
.brand-subtitle,
.project-heading,
#undoButton span,
#resetButton span,
#saveButton span {
display: none;
}
#planToggle {
display: inline-flex;
}
#sidebar {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 43vh;
padding: 17px;
border-radius: 15px;
transform: translateY(calc(100% + 24px));
transition: transform 220ms ease;
}
.sidebar-open #sidebar {
transform: translateY(0);
}
.room-pill {
top: 12px;
left: 12px;
}
.view-controls {
top: 12px;
right: 12px;
}
.legend {
bottom: 12px;
left: 12px;
}
.legend-item:nth-child(2) {
display: none;
}
#toast {
bottom: 64px;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<div class="brand-name">NEST</div>
<div class="brand-subtitle">Accessible space planner</div>
</div>
</div>
<div class="project-heading">
<strong>Nesting Studio</strong>
<span>Room 04 · Furniture layout</span>
</div>
<div class="header-actions">
<button class="button icon" id="planToggle" title="Open furniture panel" aria-label="Open furniture panel">☰</button>
<button class="button" id="undoButton" title="Undo (Ctrl+Z)">↶ <span>Undo</span></button>
<button class="button" id="resetButton" title="Reset arrangement">↺ <span>Reset</span></button>
<button class="button primary" id="saveButton" title="Save layout">↓ <span>Save layout</span></button>
</div>
</header>
<main>
<div id="viewport"></div>
<aside id="sidebar" aria-label="Furniture layout controls">
<div class="eyebrow">Room 04 / Workspace</div>
<h1 class="sidebar-title">Nesting Studio</h1>
<p class="sidebar-intro">
Arrange work surfaces while keeping the protected delivery lane open.
</p>
<section class="section">
<div class="section-heading">
<h2>Furniture</h2>
<span id="itemCount">4 pieces</span>
</div>
<div id="itemList"></div>
</section>
<section class="section">
<div class="section-heading">
<h2>Selected object</h2>
<span id="selectionType">Table</span>
</div>
<div id="emptySelection" hidden>
<p class="sidebar-intro">Select an object in the room or list.</p>
</div>
<div id="selectedContent">
<div class="selection-title">
<div class="selection-color" id="selectionColor"></div>
<div>
<strong id="selectionName"></strong>
<span id="selectionDimensions"></span>
</div>
</div>
<div class="field-label">Floor position · meters</div>
<div class="position-grid">
<label class="input-wrap">
<span>X</span>
<input id="positionX" type="number" step="0.25" aria-label="X position" />
</label>
<label class="input-wrap">
<span>Z</span>
<input id="positionZ" type="number" step="0.25" aria-label="Z position" />
</label>
</div>
<div class="rotation-row">
<button class="button" id="rotateLeft" title="Rotate counterclockwise">↶ 15°</button>
<span id="rotationValue">0°</span>
<button class="button" id="rotateRight" title="Rotate clockwise">↷ 15°</button>
</div>
<div id="heightRow">
<div class="height-label">
<span>Primary work height</span>
<strong id="heightValue">76 cm</strong>
</div>
<input id="heightSlider" type="range" min="68" max="108" step="1" aria-label="Work surface height" />
<div class="range-ends">
<span>68 cm</span>
<span>108 cm</span>
</div>
</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Layout check</h2>
<span>Live</span>
</div>
<div class="check-card" id="checkCard">
<div class="check-heading">
<div class="check-icon" id="checkIcon">✓</div>
<div id="checkTitle">Delivery lane clear</div>
</div>
<div class="check-detail" id="checkDetail">
A 1.25 m cart clearance is protected around the full route.
</div>
</div>
<div class="metrics">
<div class="metric">
<strong id="openFloorValue">90%</strong>
<span>Open floor area</span>
</div>
<div class="metric">
<strong>1.25 m</strong>
<span>Cart clearance</span>
</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Controls</h2>
</div>
<ul class="tip-list">
<li><span class="key">Drag</span><span>Move furniture on the floor grid.</span></li>
<li><span class="key">R</span><span>Rotate the selected object by 15°.</span></li>
<li><span class="key">Right</span><span>Right-drag to orbit; scroll to zoom.</span></li>
<li><span class="key">Del</span><span>Invalid cart-lane placements are rejected.</span></li>
</ul>
</section>
</aside>
<div class="room-pill">
<strong>12 × 10 m</strong>
<i></i>
<span>120 m² room</span>
</div>
<div class="view-controls" aria-label="Camera views">
<button id="isoView" class="active">Isometric</button>
<button id="topView">Top</button>
<button id="fitView">Fit</button>
</div>
<div class="legend" aria-label="Route legend">
<div class="legend-item"><span class="legend-line"></span>Protected lane</div>
<div class="legend-item"><span class="legend-dash"></span>Cart route</div>
<div class="legend-item"><span class="legend-cart"></span>Delivery cart</div>
</div>
<div id="toast" role="status" aria-live="polite"></div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Application state
// -------------------------------------------------------------------------
const ROOM = { width: 12, depth: 10, area: 120 };
const LANE_WIDTH = 1.25;
const LANE_HALF = LANE_WIDTH / 2;
const SNAP = 0.25;
const STORAGE_KEY = "nest-studio-layout-v1";
const viewport = document.querySelector("#viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color("#e7ede6");
scene.fog = new THREE.Fog("#e7ede6", 30, 55);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.04;
viewport.appendChild(renderer.domElement);
const clock = new THREE.Clock();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const floorPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const cameraState = {
target: new THREE.Vector3(0, 0.45, 0),
yaw: 0.72,
elevation: 0.62,
radius: 22
};
const cameraGoal = {
target: cameraState.target.clone(),
yaw: cameraState.yaw,
elevation: cameraState.elevation,
radius: cameraState.radius
};
const definitions = [
{
id: "nesting",
name: "Nesting worktables",
type: "table",
typeLabel: "Work surfaces",
width: 3.7,
depth: 1.55,
height: 76,
x: -1.25,
z: 0.15,
rot: 0,
color: "#d6a56b"
},
{
id: "mobile",
name: "Mobile worktop",
type: "table",
typeLabel: "Work surface",
width: 1.5,
depth: 0.85,
height: 74,
x: 2.65,
z: 1.15,
rot: 0,
color: "#6f9e9b"
},
{
id: "sofa",
name: "Three-seat sofa",
type: "sofa",
typeLabel: "Lounge",
width: 2.65,
depth: 1,
height: 98,
x: -3.75,
z: -4.2,
rot: 0,
color: "#789985"
},
{
id: "cabinet",
name: "Low cabinet",
type: "cabinet",
typeLabel: "Storage",
width: 2.45,
depth: 0.72,
height: 160,
x: 3.4,
z: -4.35,
rot: 0,
color: "#a77750"
}
];
const items = definitions.map((definition) => ({
...definition,
defaults: {
x: definition.x,
z: definition.z,
rot: definition.rot,
height: definition.height
},
group: new THREE.Group()
}));
const itemMap = new Map(items.map((item) => [item.id, item]));
const undoStack = [];
let selectedId = "nesting";
let toastTimer;
let heightEditSnapshot = null;
// -------------------------------------------------------------------------
// Scene, room, lights and grid
// -------------------------------------------------------------------------
const hemi = new THREE.HemisphereLight("#ffffff", "#9eaa98", 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight("#fff7df", 3.2);
sun.position.set(7, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight("#c8dcff", 0.75);
fill.position.set(-9, 7, 4);
scene.add(fill);
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.82,
metalness: options.metalness ?? 0,
flatShading: options.flatShading ?? true,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1,
side: options.side ?? THREE.FrontSide,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
}
function addBox(parent, width, height, depth, color, x = 0, y = 0, z = 0, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
standardMaterial(color, options)
);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function addCylinder(parent, radiusTop, radiusBottom, height, color, x, y, z, segments = 8) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments),
standardMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function buildRoom() {
const floor = addBox(
scene,
ROOM.width,
0.14,
ROOM.depth,
"#f4f0e6",
0,
-0.08,
0,
{ castShadow: false }
);
floor.receiveShadow = true;
const underfloor = addBox(
scene,
ROOM.width + 0.18,
0.18,
ROOM.depth + 0.18,
"#c9d2c8",
0,
-0.22,
0,
{ castShadow: false }
);
underfloor.receiveShadow = true;
// Back and left cutaway walls.
addBox(scene, 12.15, 2.85, 0.14, "#f7f3e9", 0, 1.35, -5.08);
addBox(scene, 0.14, 2.85, 10.15, "#edf0e8", -6.08, 1.35, 0);
// Baseboards.
addBox(scene, 11.8, 0.13, 0.055, "#d7ddd5", 0, 0.1, -4.985);
addBox(scene, 0.055, 0.13, 9.8, "#d7ddd5", -5.985, 0.1, 0);
// Low-poly window.
addBox(scene, 3.25, 1.25, 0.035, "#c8e0df", 0, 1.83, -4.985, {
emissive: "#8fbcc1",
emissiveIntensity: 0.16,
castShadow: false
});
addBox(scene, 0.08, 1.3, 0.07, "#f8f5eb", 0, 1.83, -4.945);
addBox(scene, 3.3, 0.08, 0.07, "#f8f5eb", 0, 1.83, -4.945);
addBox(scene, 3.5, 0.08, 0.17, "#ddd8cc", 0, 1.17, -4.92);
// Wall art.
addBox(scene, 0.78, 0.96, 0.045, "#d9b074", -2.5, 1.75, -4.96);
addBox(scene, 0.58, 0.72, 0.055, "#e6d6ae", -2.5, 1.75, -4.93);
addBox(scene, 0.25, 0.38, 0.06, "#6d8d80", -2.5, 1.72, -4.89);
// Entrance threshold on the right.
addBox(scene, 0.8, 0.025, 1.65, "#d7b46d", 5.62, 0.008, 0, {
castShadow: false
});
for (let i = 0; i < 4; i++) {
addBox(scene, 0.045, 0.03, 1.35, "#f7ebcb", 5.29 + i * 0.19, 0.025, 0, {
castShadow: false
});
}
buildFloorGrid();
}
function buildFloorGrid() {
const minor = [];
const major = [];
for (let x = -6; x <= 6.001; x += 0.5) {
const target = Math.abs(x - Math.round(x)) < 0.01 ? major : minor;
target.push(x, 0.004, -5, x, 0.004, 5);
}
for (let z = -5; z <= 5.001; z += 0.5) {
const target = Math.abs(z - Math.round(z)) < 0.01 ? major : minor;
target.push(-6, 0.004, z, 6, 0.004, z);
}
const minorGeometry = new THREE.BufferGeometry();
minorGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(minor, 3)
);
const minorLines = new THREE.LineSegments(
minorGeometry,
new THREE.LineBasicMaterial({
color: "#8da095",
transparent: true,
opacity: 0.16
})
);
scene.add(minorLines);
const majorGeometry = new THREE.BufferGeometry();
majorGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(major, 3)
);
const majorLines = new THREE.LineSegments(
majorGeometry,
new THREE.LineBasicMaterial({
color: "#71887c",
transparent: true,
opacity: 0.26
})
);
scene.add(majorLines);
}
// -------------------------------------------------------------------------
// Furniture construction
// -------------------------------------------------------------------------
function clearGroup(group) {
const geometries = new Set();
const materials = new Set();
group.traverse((child) => {
if (child.geometry) geometries.add(child.geometry);
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach((material) => materials.add(material));
} else {
materials.add(child.material);
}
}
});
group.clear();
geometries.forEach((geometry) => geometry.dispose());
materials.forEach((material) => material.dispose());
}
function buildFurniture(item) {
clearGroup(item.group);
item.group.userData.itemId = item.id;
item.group.position.set(item.x, 0, item.z);
item.group.rotation.y = THREE.MathUtils.degToRad(item.rot);
if (item.type === "table") {
buildTable(item);
} else if (item.type === "sofa") {
buildSofa(item);
} else if (item.type === "cabinet") {
buildCabinet(item);
}
scene.add(item.group);
}
function buildTable(item) {
const h = item.height / 100;
const topThickness = 0.11;
if (item.id === "nesting") {
// Large oak worktable.
addBox(item.group, 3, topThickness, 1.55, item.color, -0.45, h - 0.055, 0);
const legHeight = h - topThickness;
const legY = legHeight / 2;
[-1.72, 0.82].forEach((x) => {
[-0.58, 0.58].forEach((z) => {
addBox(item.group, 0.105, legHeight, 0.105, "#8d6e4b", x, legY, z);
});
});
addBox(item.group, 2.45, 0.09, 0.09, "#a17c50", -0.45, 0.29, -0.58);
addBox(item.group, 2.45, 0.09, 0.09, "#a17c50", -0.45, 0.29, 0.58);
// Smaller table tucked partly beneath the larger surface.
const nestedHeight = Math.max(0.62, h - 0.14);
const nestedTop = 0.095;
addBox(
item.group,
1.65,
nestedTop,
0.9,
"#bf7357",
0.95,
nestedHeight - nestedTop / 2,
0.12
);
const nestedLegHeight = nestedHeight - nestedTop;
[0.3, 1.6].forEach((x) => {
[-0.2, 0.44].forEach((z) => {
addBox(
item.group,
0.075,
nestedLegHeight,
0.075,
"#855f4b",
x,
nestedLegHeight / 2,
z + 0.12
);
});
});
// A compact monitor on the primary work surface.
addBox(item.group, 0.62, 0.035, 0.38, "#394c46", -0.7, h + 0.018, -0.22);
addBox(item.group, 0.07, 0.24, 0.07, "#4b5d57", -0.7, h + 0.13, -0.25);
addBox(item.group, 0.56, 0.34, 0.045, "#253b35", -0.7, h + 0.35, -0.27);
addBox(
item.group,
0.48,
0.27,
0.012,
"#85aaa0",
-0.7,
h + 0.35,
-0.241,
{ emissive: "#608d82", emissiveIntensity: 0.1 }
);
} else {
addBox(item.group, item.width, topThickness, item.depth, item.color, 0, h - 0.055, 0);
const legHeight = h - topThickness;
const legY = legHeight / 2;
const xOffset = item.width / 2 - 0.13;
const zOffset = item.depth / 2 - 0.12;
[-xOffset, xOffset].forEach((x) => {
[-zOffset, zOffset].forEach((z) => {
addBox(item.group, 0.08, legHeight, 0.08, "#3d5f5c", x, legY, z);
});
});
addBox(item.group, item.width - 0.3, 0.06, 0.055, "#3d5f5c", 0, 0.25, zOffset);
addBox(item.group, 0.43, 0.025, 0.29, "#f3eee2", 0, h + 0.014, -0.02);
}
}
function buildSofa(item) {
const fabric = item.color;
const cushion = "#8baa96";
[-1.12, 1.12].forEach((x) => {
[-0.34, 0.34].forEach((z) => {
addBox(item.group, 0.12, 0.2, 0.12, "#5c4938", x, 0.1, z);
});
});
addBox(item.group, 2.65, 0.22, 1, fabric, 0, 0.32, 0);
addBox(item.group, 2.65, 0.58, 0.2, fabric, 0, 0.72, -0.4);
[-1.24, 1.24].forEach((x) => {
addBox(item.group, 0.19, 0.5, 1, fabric, x, 0.58, 0);
});
[-0.82, 0, 0.82].forEach((x) => {
addBox(item.group, 0.77, 0.18, 0.72, cushion, x, 0.51, 0.08);
addBox(item.group, 0.77, 0.39, 0.14, cushion, x, 0.72, -0.28);
});
const pillow = addBox(item.group, 0.35, 0.34, 0.14, "#d2b078", -0.83, 0.72, -0.16);
pillow.rotation.z = -0.12;
const pillow2 = addBox(item.group, 0.32, 0.31, 0.13, "#d9d2bf", 0.91, 0.7, -0.16);
pillow2.rotation.z = 0.14;
}
function buildCabinet(item) {
const wood = item.color;
const darkWood = "#7e573c";
[-1, 1].forEach((x) => {
[-0.23, 0.23].forEach((z) => {
addBox(item.group, 0.09, 0.17, 0.09, darkWood, x * 1.03, 0.085, z);
});
});
addBox(item.group, 2.45, 1.25, 0.72, wood, 0, 0.8, 0);
addBox(item.group, 2.55, 0.09, 0.78, "#bc8d61", 0, 1.47, 0);
[-0.61, 0.61].forEach((x) => {
addBox(item.group, 1.12, 1.04, 0.035, "#b17e51", x, 0.79, 0.377);
addBox(item.group, 0.035, 0.22, 0.045, "#e4d6b7", x + (x < 0 ? 0.43 : -0.43), 0.87, 0.41);
});
// Low-poly plant.
addCylinder(item.group, 0.18, 0.14, 0.3, "#b56d51", 0.82, 1.66, 0, 7);
addCylinder(item.group, 0.035, 0.045, 0.5, "#526e48", 0.82, 1.99, 0, 6);
const leafMaterial = standardMaterial("#648558");
[
[-0.17, 2.12, 0.02, 0.45],
[0.16, 2.17, -0.02, -0.5],
[-0.05, 2.32, 0.12, 0.12],
[0.08, 2.36, -0.1, -0.18]
].forEach(([x, y, z, rz]) => {
const leaf = new THREE.Mesh(
new THREE.ConeGeometry(0.18, 0.48, 6),
leafMaterial
);
leaf.position.set(0.82 + x, y, z);
leaf.rotation.z = rz;
leaf.castShadow = true;
item.group.add(leaf);
});
}
// -------------------------------------------------------------------------
// Delivery route and animated low-poly cart
// -------------------------------------------------------------------------
function createRoundedRectanglePoints() {
const hx = 4.5;
const hz = 2.5;
const radius = 0.65;
const steps = 14;
const points = [];
const corners = [
{ x: hx - radius, z: hz - radius, start: 0 },
{ x: -hx + radius, z: hz - radius, start: Math.PI / 2 },
{ x: -hx + radius, z: -hz + radius, start: Math.PI },
{ x: hx - radius, z: -hz + radius, start: Math.PI * 1.5 }
];
corners.forEach((corner) => {
for (let i = 0; i <= steps; i++) {
const angle = corner.start + (i / steps) * Math.PI / 2;
points.push(
new THREE.Vector3(
corner.x + Math.cos(angle) * radius,
0,
corner.z + Math.sin(angle) * radius
)
);
}
});
return points;
}
const routePoints = createRoundedRectanglePoints();
const routeSegments = [];
let routeLength = 0;
for (let i = 0; i < routePoints.length; i++) {
const next = routePoints[(i + 1) % routePoints.length];
const length = routePoints[i].distanceTo(next);
routeLength += length;
routeSegments.push({ a: routePoints[i], b: next, length, start: routeLength - length });
}
const lanePositions = [];
const laneIndices = [];
for (let i = 0; i < routePoints.length; i++) {
const previous = routePoints[(i - 1 + routePoints.length) % routePoints.length];
const next = routePoints[(i + 1) % routePoints.length];
const tangent = next.clone().sub(previous).normalize();
const normal = new THREE.Vector3(-tangent.z, 0, tangent.x).multiplyScalar(LANE_HALF);
const point = routePoints[i];
lanePositions.push(
point.x + normal.x, 0.024, point.z + normal.z,
point.x - normal.x, 0.024, point.z - normal.z
);
const nextIndex = (i + 1) % routePoints.length;
const a = i * 2;
const b = nextIndex * 2;
laneIndices.push(a, a + 1, b, a + 1, b + 1, b);
}
const laneGeometry = new THREE.BufferGeometry();
laneGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(lanePositions, 3)
);
laneGeometry.setIndex(laneIndices);
laneGeometry.computeVertexNormals();
const laneMaterial = new THREE.MeshBasicMaterial({
color: "#4d876c",
transparent: true,
opacity: 0.16,
depthWrite: false,
side: THREE.DoubleSide
});
const laneMesh = new THREE.Mesh(laneGeometry, laneMaterial);
laneMesh.renderOrder = 1;
scene.add(laneMesh);
const routeLineGeometry = new THREE.BufferGeometry().setFromPoints(
routePoints.map((point) => new THREE.Vector3(point.x, 0.043, point.z))
);
const routeLineMaterial = new THREE.LineDashedMaterial({
color: "#4d876c",
dashSize: 0.18,
gapSize: 0.11,
transparent: true,
opacity: 0.8
});
const routeLine = new THREE.Line(routeLineGeometry, routeLineMaterial);
routeLine.computeLineDistances();
scene.add(routeLine);
function sampleRoute(distance) {
const d = ((distance % routeLength) + routeLength) % routeLength;
for (const segment of routeSegments) {
if (d <= segment.start + segment.length) {
const t = (d - segment.start) / segment.length;
const point = segment.a.clone().lerp(segment.b, t);
const tangent = segment.b.clone().sub(segment.a).normalize();
return { point, tangent };
}
}
return { point: routePoints[0].clone(), tangent: new THREE.Vector3(0, 0, 1) };
}
const cart = new THREE.Group();
addBox(cart, 0.68, 0.12, 0.9, "#344d45", 0, 0.21, 0);
addBox(cart, 0.62, 0.48, 0.7, "#d1a65d", 0, 0.53, 0.02);
addBox(cart, 0.66, 0.06, 0.74, "#e7c479", 0, 0.79, 0.02);
[-0.36, 0.36].forEach((x) => {
[-0.3, 0.3].forEach((z) => {
const wheel = addCylinder(cart, 0.115, 0.115, 0.075, "#283a35", x, 0.12, z, 10);
wheel.rotation.z = Math.PI / 2;
});
});
const cartHandle = addBox(cart, 0.72, 0.06, 0.06, "#3b504a", 0, 0.86, -0.42);
cartHandle.castShadow = true;
scene.add(cart);
// -------------------------------------------------------------------------
// Selection highlight
// -------------------------------------------------------------------------
const highlightGroup = new THREE.Group();
const highlightFloor = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
new THREE.MeshBasicMaterial({
color: "#df704f",
transparent: true,
opacity: 0.13,
depthWrite: false,
side: THREE.DoubleSide
})
);
highlightFloor.rotation.x = -Math.PI / 2;
highlightFloor.position.y = 0.035;
highlightGroup.add(highlightFloor);
const highlightEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 0.025, 1)),
new THREE.LineBasicMaterial({
color: "#df704f",
transparent: true,
opacity: 0.85
})
);
highlightEdges.position.y = 0.035;
highlightGroup.add(highlightEdges);
scene.add(highlightGroup);
// -------------------------------------------------------------------------
// Route collision checking
// -------------------------------------------------------------------------
function segmentIntersectsExpandedBox(segment, item, x, z, rotation) {
const radians = THREE.MathUtils.degToRad(rotation);
const cosine = Math.cos(radians);
const sine = Math.sin(radians);
// Local X and Z axes after Y rotation.
const axisX = { x: cosine, z: -sine };
const axisZ = { x: sine, z: cosine };
const dx = segment.b.x - segment.a.x;
const dz = segment.b.z - segment.a.z;
const length = Math.hypot(dx, dz);
if (length < 0.00001) return false;
const direction = { x: dx / length, z: dz / length };
const relA = { x: segment.a.x - x, z: segment.a.z - z };
const relB = { x: segment.b.x - x, z: segment.b.z - z };
const halfWidth = item.width / 2 + LANE_HALF + 0.025;
const halfDepth = item.depth / 2 + LANE_HALF + 0.025;
const aX = relA.x * axisX.x + relA.z * axisX.z;
const bX = relB.x * axisX.x + relB.z * axisX.z;
const minX = Math.min(aX, bX);
const maxX = Math.max(aX, bX);
if (maxX < -halfWidth || minX > halfWidth) return false;
const aZ = relA.x * axisZ.x + relA.z * axisZ.z;
const bZ = relB.x * axisZ.x + relB.z * axisZ.z;
const minZ = Math.min(aZ, bZ);
const maxZ = Math.max(aZ, bZ);
if (maxZ < -halfDepth || minZ > halfDepth) return false;
// Separating axis perpendicular to the route segment.
const aD = relA.x * direction.x + relA.z * direction.z;
const bD = relB.x * direction.x + relB.z * direction.z;
const minD = Math.min(aD, bD);
const maxD = Math.max(aD, bD);
const radius =
halfWidth * Math.abs(axisX.x * direction.x + axisX.z * direction.z) +
halfDepth * Math.abs(axisZ.x * direction.x + axisZ.z * direction.z);
return !(maxD < -radius || minD > radius);
}
function itemBlocksRoute(item, x = item.x, z = item.z, rotation = item.rot) {
return routeSegments.some((segment) =>
segmentIntersectsExpandedBox(segment, item, x, z, rotation)
);
}
function blockedItems() {
return items.filter((item) => itemBlocksRoute(item));
}
function placementIsValid(item, x, z, rotation) {
return !items.some((candidate) => {
const isCandidate = candidate.id === item.id;
const candidateX = isCandidate ? x : candidate.x;
const candidateZ = isCandidate ? z : candidate.z;
const candidateRotation = isCandidate ? rotation : candidate.rot;
return itemBlocksRoute(candidate, candidateX, candidateZ, candidateRotation);
});
}
function clampItemToRoom(item, x, z) {
const radians = THREE.MathUtils.degToRad(item.rot);
const cosine = Math.abs(Math.cos(radians));
const sine = Math.abs(Math.sin(radians));
const extentX =
(item.width / 2) * cosine + (item.depth / 2) * sine;
const extentZ =
(item.width / 2) * sine + (item.depth / 2) * cosine;
return {
x: THREE.MathUtils.clamp(x, -ROOM.width / 2 + extentX, ROOM.width / 2 - extentX),
z: THREE.MathUtils.clamp(z, -ROOM.depth / 2 + extentZ, ROOM.depth / 2 - extentZ)
};
}
// -------------------------------------------------------------------------
// State snapshots and undo
// -------------------------------------------------------------------------
function captureSnapshot() {
return items.map((item) => ({
id: item.id,
x: item.x,
z: item.z,
rot: item.rot,
height: item.height
}));
}
function applySnapshot(snapshot) {
snapshot.forEach((state) => {
const item = itemMap.get(state.id);
if (!item) return;
const heightChanged = item.height !== state.height;
item.x = state.x;
item.z = state.z;
item.rot = state.rot;
item.height = state.height;
item.group.position.set(item.x, 0, item.z);
item.group.rotation.y = THREE.MathUtils.degToRad(item.rot);
if (heightChanged && item.type === "table") {
buildFurniture(item);
}
});
updateAllUI();
}
function pushUndo(snapshot) {
undoStack.push(snapshot);
if (undoStack.length > 30) undoStack.shift();
}
function undo() {
const snapshot = undoStack.pop();
if (!snapshot) {
showToast("Nothing to undo");
return;
}
applySnapshot(snapshot);
showToast("Last arrangement change undone");
}
function resetArrangement() {
pushUndo(captureSnapshot());
items.forEach((item) => {
item.x = item.defaults.x;
item.z = item.defaults.z;
item.rot = item.defaults.rot;
item.height = item.defaults.height;
buildFurniture(item);
});
try {
localStorage.removeItem(STORAGE_KEY);
} catch (_) {}
updateAllUI();
showToast("Arrangement reset to the original layout");
}
function saveLayout() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(captureSnapshot()));
showToast("Layout saved in this browser");
} catch (_) {
showToast("This browser does not allow local layout storage");
}
}
function loadSavedLayout() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const snapshot = JSON.parse(raw);
if (!Array.isArray(snapshot) || snapshot.length !== items.length) return;
const valid = snapshot.every((state) => {
const item = itemMap.get(state.id);
if (!item) return false;
return placementIsValid(item, state.x, state.z, state.rot);
});
if (valid) applySnapshot(snapshot);
} catch (_) {}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
function showToast(message, error = false) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.classList.toggle("error", error);
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
function renderItemList() {
const list = document.querySelector("#itemList");
list.innerHTML = "";
items.forEach((item) => {
const button = document.createElement("button");
button.className = `furniture-item${item.id === selectedId ? " active" : ""}`;
button.innerHTML = `
<span class="item-swatch" style="--swatch:${item.color}"></span>
<span class="item-copy">
<strong>${item.name}</strong>
<span>${item.width.toFixed(2)} × ${item.depth.toFixed(2)} m · ${item.height} cm</span>
</span>
<span class="item-dot"></span>
`;
button.addEventListener("click", () => selectItem(item.id));
list.appendChild(button);
});
}
function selectItem(id) {
selectedId = id;
updateHighlight();
updateEditor();
renderItemList();
}
function updateEditor() {
const item = itemMap.get(selectedId);
const content = document.querySelector("#selectedContent");
const empty = document.querySelector("#emptySelection");
if (!item) {
content.hidden = true;
empty.hidden = false;
return;
}
content.hidden = false;
empty.hidden = true;
document.querySelector("#selectionType").textContent = item.typeLabel;
document.querySelector("#selectionName").textContent = item.name;
document.querySelector("#selectionDimensions").textContent =
`${item.width.toFixed(2)} × ${item.depth.toFixed(2)} m`;
document.querySelector("#selectionColor").style.background = item.color;
document.querySelector("#positionX").value = item.x.toFixed(2);
document.querySelector("#positionZ").value = item.z.toFixed(2);
document.querySelector("#rotationValue").textContent = `${item.rot}°`;
const heightRow = document.querySelector("#heightRow");
heightRow.hidden = item.type !== "table";
if (item.type === "table") {
document.querySelector("#heightSlider").value = item.height;
document.querySelector("#heightValue").textContent = `${item.height} cm`;
}
}
function updateHighlight() {
const item = itemMap.get(selectedId);
if (!item) {
highlightGroup.visible = false;
return;
}
highlightGroup.visible = true;
highlightGroup.position.set(item.x, 0, item.z);
highlightGroup.rotation.y = THREE.MathUtils.degToRad(item.rot);
highlightFloor.scale.set(item.width + 0.16, item.depth + 0.16, 1);
highlightEdges.scale.set(item.width + 0.16, 1, item.depth + 0.16);
}
function updateStatus() {
const blocked = blockedItems();
const card = document.querySelector("#checkCard");
const icon = document.querySelector("#checkIcon");
const title = document.querySelector("#checkTitle");
const detail = document.querySelector("#checkDetail");
if (blocked.length) {
card.classList.add("blocked");
icon.textContent = "!";
title.textContent = "Delivery lane blocked";
detail.textContent = `${blocked[0].name} enters the protected cart clearance.`;
laneMaterial.color.set("#c95445");
routeLineMaterial.color.set("#c95445");
} else {
card.classList.remove("blocked");
icon.textContent = "✓";
title.textContent = "Delivery lane clear";
detail.textContent = "A 1.25 m cart clearance is protected around the full route.";
laneMaterial.color.set("#4d876c");
routeLineMaterial.color.set("#4d876c");
}
const occupied = items.reduce(
(sum, item) => sum + item.width * item.depth,
0
);
const openPercent = Math.max(
0,
Math.round((1 - occupied / ROOM.area) * 100)
);
document.querySelector("#openFloorValue").textContent = `${openPercent}%`;
}
function updateAllUI() {
renderItemList();
updateEditor();
updateHighlight();
updateStatus();
}
function rotateSelected(delta) {
const item = itemMap.get(selectedId);
if (!item) return;
const before = captureSnapshot();
const nextRotation = ((item.rot + delta) % 360 + 360) % 360;
if (!placementIsValid(item, item.x, item.z, nextRotation)) {
showToast("Rotation blocked: keep the delivery lane clear", true);
return;
}
item.rot = nextRotation;
item.group.rotation.y = THREE.MathUtils.degToRad(item.rot);
pushUndo(before);
updateAllUI();
}
document.querySelector("#rotateLeft").addEventListener("click", () => rotateSelected(-15));
document.querySelector("#rotateRight").addEventListener("click", () => rotateSelected(15));
function commitPositionChange() {
const item = itemMap.get(selectedId);
if (!item) return;
const x = Number(document.querySelector("#positionX").value);
const z = Number(document.querySelector("#positionZ").value);
if (!Number.isFinite(x) || !Number.isFinite(z)) return;
const before = captureSnapshot();
const clamped = clampItemToRoom(item, x, z);
if (!placementIsValid(item, clamped.x, clamped.z, item.rot)) {
showToast("Position blocked: keep the delivery lane clear", true);
applySnapshot(before);
return;
}
item.x = clamped.x;
item.z = clamped.z;
item.group.position.set(item.x, 0, item.z);
pushUndo(before);
updateAllUI();
}
document.querySelector("#positionX").addEventListener("change", commitPositionChange);
document.querySelector("#positionZ").addEventListener("change", commitPositionChange);
const heightSlider = document.querySelector("#heightSlider");
heightSlider.addEventListener("pointerdown", () => {
heightEditSnapshot = captureSnapshot();
});
heightSlider.addEventListener("focus", () => {
if (!heightEditSnapshot) heightEditSnapshot = captureSnapshot();
});
heightSlider.addEventListener("input", () => {
const item = itemMap.get(selectedId);
if (!item || item.type !== "table") return;
item.height = Number(heightSlider.value);
buildFurniture(item);
document.querySelector("#heightValue").textContent = `${item.height} cm`;
renderItemList();
});
heightSlider.addEventListener("change", () => {
if (heightEditSnapshot) pushUndo(heightEditSnapshot);
heightEditSnapshot = null;
updateAllUI();
});
document.querySelector("#undoButton").addEventListener("click", undo);
document.querySelector("#resetButton").addEventListener("click", resetArrangement);
document.querySelector("#saveButton").addEventListener("click", saveLayout);
document.querySelector("#planToggle").addEventListener("click", () => {
document.body.classList.toggle("sidebar-open");
});
// -------------------------------------------------------------------------
// Pointer interaction: furniture dragging and camera orbit
// -------------------------------------------------------------------------
let pointerState = null;
function setPointerFromEvent(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;
}
function getFloorIntersection() {
raycaster.setFromCamera(pointer, camera);
const point = new THREE.Vector3();
return raycaster.ray.intersectPlane(floorPlane, point);
}
function getItemFromPointer() {
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(
items.map((item) => item.group),
true
);
for (const hit of hits) {
let object = hit.object;
while (object) {
if (object.userData.itemId) {
return itemMap.get(object.userData.itemId);
}
object = object.parent;
}
}
return null;
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
setPointerFromEvent(event);
renderer.domElement.setPointerCapture(event.pointerId);
const item = event.button === 0 ? getItemFromPointer() : null;
if (item) {
const floorPoint = getFloorIntersection();
if (!floorPoint) return;
selectItem(item.id);
pointerState = {
mode: "furniture",
item,
before: captureSnapshot(),
offsetX: item.x - floorPoint.x,
offsetZ: item.z - floorPoint.z,
moved: false
};
} else {
pointerState = {
mode: "camera",
lastX: event.clientX,
lastY: event.clientY,
moved: false
};
if (event.button === 0) {
selectItem(null);
}
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
setPointerFromEvent(event);
if (!pointerState) {
renderer.domElement.style.cursor = getItemFromPointer() ? "grab" : "default";
return;
}
if (pointerState.mode === "camera") {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
cameraGoal.yaw -= dx * 0.006;
cameraGoal.elevation = THREE.MathUtils.clamp(
cameraGoal.elevation + dy * 0.005,
0.3,
1.48
);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved = true;
return;
}
const floorPoint = getFloorIntersection();
if (!floorPoint) return;
const item = pointerState.item;
let x = floorPoint.x + pointerState.offsetX;
let z = floorPoint.z + pointerState.offsetZ;
x = Math.round(x / SNAP) * SNAP;
z = Math.round(z / SNAP) * SNAP;
const clamped = clampItemToRoom(item, x, z);
item.x = clamped.x;
item.z = clamped.z;
item.group.position.set(item.x, 0, item.z);
pointerState.moved = true;
renderer.domElement.style.cursor = "grabbing";
updateHighlight();
updateStatus();
updateEditor();
});
function finishPointer(event) {
if (!pointerState) return;
if (pointerState.mode === "furniture") {
const item = pointerState.item;
if (!placementIsValid(item, item.x, item.z, item.rot)) {
const before = pointerState.before;
applySnapshot(before);
showToast("Drop blocked: preserve the 1.25 m delivery lane", true);
} else if (pointerState.moved) {
pushUndo(pointerState.before);
}
}
pointerState = null;
renderer.domElement.style.cursor = "default";
updateAllUI();
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", finishPointer);
renderer.domElement.addEventListener("pointercancel", finishPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraGoal.radius = THREE.MathUtils.clamp(
cameraGoal.radius + event.deltaY * 0.014,
12,
30
);
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Camera views and keyboard controls
// -------------------------------------------------------------------------
function setView(view) {
document.querySelectorAll(".view-controls button").forEach((button) => {
button.classList.toggle("active", button.id === `${view}View`);
});
if (view === "top") {
cameraGoal.yaw = 0;
cameraGoal.elevation = 1.47;
cameraGoal.radius = 19;
} else if (view === "fit") {
cameraGoal.yaw = 0.72;
cameraGoal.elevation = 0.62;
cameraGoal.radius = 22;
} else {
cameraGoal.yaw = 0.72;
cameraGoal.elevation = 0.62;
cameraGoal.radius = 22;
}
}
document.querySelector("#isoView").addEventListener("click", () => setView("iso"));
document.querySelector("#topView").addEventListener("click", () => setView("top"));
document.querySelector("#fitView").addEventListener("click", () => setView("fit"));
window.addEventListener("keydown", (event) => {
const tag = event.target.tagName;
if (tag === "INPUT" || tag === "TEXTAREA") return;
if (event.key.toLowerCase() === "r") {
rotateSelected(event.shiftKey ? -15 : 15);
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") {
event.preventDefault();
undo();
}
if (event.key === "Escape") {
selectItem(null);
}
});
function updateCamera(dt) {
const smoothing = 1 - Math.pow(0.0008, dt);
cameraState.yaw = THREE.MathUtils.lerp(cameraState.yaw, cameraGoal.yaw, smoothing);
cameraState.elevation = THREE.MathUtils.lerp(
cameraState.elevation,
cameraGoal.elevation,
smoothing
);
cameraState.radius = THREE.MathUtils.lerp(
cameraState.radius,
cameraGoal.radius,
smoothing
);
cameraState.target.lerp(cameraGoal.target, smoothing);
const horizontal = Math.cos(cameraState.elevation) * cameraState.radius;
const desired = new THREE.Vector3(
cameraState.target.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y + Math.sin(cameraState.elevation) * cameraState.radius,
cameraState.target.z + Math.cos(cameraState.yaw) * horizontal
);
camera.position.lerp(desired, smoothing);
camera.lookAt(cameraState.target);
}
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(1, height);
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
buildRoom();
items.forEach((item) => {
item.group.userData.itemId = item.id;
scene.add(item.group);
buildFurniture(item);
});
loadSavedLayout();
updateAllUI();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateCamera(dt);
const routeSample = sampleRoute((elapsed * 0.8) % routeLength);
cart.position.set(routeSample.point.x, 0, routeSample.point.z);
cart.rotation.y = Math.atan2(routeSample.tangent.x, routeSample.tangent.z);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```