Prompt specification
Build or customize the Three.js 3D scene "Furnishing-through-doorway 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: Furnishing-through-doorway puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/furnishing-through-doorway-puzzle-x0284
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a measuring tape. Create several boxes and a doorway with measurable width and height; users rotate and compare bounding dimensions before moving each box through a continuous collision-checked path. Voxel style.
Working Three.js Starter (furnishing-through-doorway-puzzle-x0284):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tape / Fit — Voxel Measuring & Collision Lab</title>
<style>
:root {
--ink: #172126;
--muted: #657277;
--paper: #f4f1e8;
--panel: rgba(248, 246, 238, 0.96);
--line: #c9c6bc;
--yellow: #f4c542;
--yellow-dark: #b98513;
--orange: #eb7047;
--blue: #3c82a6;
--green: #64a879;
--red: #cc4b43;
--shadow: 0 8px 0 rgba(23, 33, 38, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d8d6cd;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.topbar {
position: fixed;
z-index: 20;
top: 14px;
left: 16px;
right: 16px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand,
.top-actions {
pointer-events: auto;
background: var(--panel);
border: 2px solid var(--ink);
box-shadow: 4px 4px 0 rgba(23, 33, 38, 0.18);
}
.brand {
display: flex;
align-items: center;
min-height: 48px;
padding: 8px 12px;
gap: 10px;
}
.brand-mark {
width: 30px;
height: 30px;
position: relative;
background: var(--yellow);
border: 2px solid var(--ink);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: var(--ink);
}
.brand-mark::before {
width: 2px;
height: 22px;
left: 8px;
top: 2px;
}
.brand-mark::after {
width: 15px;
height: 2px;
left: 2px;
top: 8px;
box-shadow: 0 6px 0 var(--ink), 0 12px 0 var(--ink);
}
.brand h1 {
margin: 0;
font-size: 15px;
letter-spacing: 0.08em;
}
.brand small {
display: block;
color: var(--muted);
font-size: 9px;
margin-top: 3px;
letter-spacing: 0.08em;
}
.top-actions {
display: flex;
padding: 6px;
gap: 6px;
}
.icon-button {
min-height: 32px;
border: 1px solid var(--ink);
background: #fff;
padding: 6px 9px;
cursor: pointer;
font-size: 11px;
box-shadow: 2px 2px 0 rgba(23, 33, 38, 0.16);
}
.icon-button:hover {
background: var(--yellow);
}
.icon-button:active {
transform: translate(1px, 1px);
box-shadow: none;
}
.panel {
position: fixed;
z-index: 15;
top: 78px;
width: 296px;
max-height: calc(100vh - 108px);
overflow: auto;
scrollbar-width: thin;
background: var(--panel);
border: 2px solid var(--ink);
box-shadow: var(--shadow);
}
#controls {
left: 16px;
}
#compare {
right: 16px;
width: 292px;
}
.panel-head {
padding: 12px 13px 10px;
background: var(--ink);
color: #fff;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.panel-head span:last-child {
color: var(--yellow);
font-size: 9px;
}
.section {
padding: 12px 13px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
border-bottom: 0;
}
.section-title {
margin: 0 0 10px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.09em;
}
.section-title small {
color: var(--muted);
text-transform: none;
letter-spacing: 0;
font-size: 9px;
}
.box-list {
display: grid;
gap: 7px;
}
.box-card {
width: 100%;
display: grid;
grid-template-columns: 31px 1fr auto;
gap: 9px;
align-items: center;
padding: 8px;
text-align: left;
border: 1px solid var(--line);
background: #fff;
cursor: pointer;
}
.box-card:hover {
border-color: var(--ink);
}
.box-card.active {
border: 2px solid var(--ink);
padding: 7px;
box-shadow: 3px 3px 0 rgba(23, 33, 38, 0.12);
}
.swatch {
width: 27px;
height: 27px;
border: 2px solid var(--ink);
box-shadow: inset -6px -6px 0 rgba(0, 0, 0, 0.12);
}
.box-name {
font-weight: 800;
font-size: 11px;
}
.box-dims {
color: var(--muted);
font-size: 9px;
margin-top: 4px;
line-height: 1.35;
}
.fit-badge {
padding: 4px 5px;
border: 1px solid currentColor;
font-size: 8px;
font-weight: 800;
white-space: nowrap;
}
.fit-badge.yes {
color: #397a51;
background: #e7f3e9;
}
.fit-badge.no {
color: #a33b35;
background: #f7e5e2;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 9px 0;
font-size: 10px;
}
.control-row output {
min-width: 66px;
text-align: right;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--orange);
cursor: pointer;
}
.primary,
.secondary {
width: 100%;
min-height: 38px;
border: 2px solid var(--ink);
font-weight: 800;
font-size: 10px;
letter-spacing: 0.06em;
cursor: pointer;
}
.primary {
background: var(--yellow);
box-shadow: 3px 3px 0 var(--ink);
}
.primary:hover {
background: #ffd95c;
}
.primary:active {
transform: translate(2px, 2px);
box-shadow: 1px 1px 0 var(--ink);
}
.primary:disabled {
cursor: wait;
opacity: 0.6;
}
.secondary {
margin-top: 8px;
background: #fff;
}
.secondary:hover {
background: #ece9df;
}
.status {
margin-top: 10px;
min-height: 42px;
padding: 8px;
border-left: 4px solid var(--blue);
background: #edf2f3;
font-size: 9px;
line-height: 1.45;
}
.status.good {
border-color: var(--green);
background: #edf5ee;
}
.status.bad {
border-color: var(--red);
background: #f8e9e6;
}
.status.busy {
border-color: var(--yellow-dark);
background: #faf4dc;
}
.opening-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.metric {
padding: 9px;
background: #fff;
border: 1px solid var(--line);
}
.metric strong {
display: block;
font-size: 18px;
font-variant-numeric: tabular-nums;
}
.metric small {
color: var(--muted);
font-size: 8px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.tape-wrap {
margin-top: 10px;
border: 2px solid var(--ink);
background: var(--yellow);
padding: 8px 8px 6px;
position: relative;
}
.tape-ruler {
height: 34px;
position: relative;
overflow: hidden;
border-bottom: 2px solid var(--ink);
background:
repeating-linear-gradient(
90deg,
transparent 0 15px,
var(--ink) 15px 17px,
transparent 17px 30px
);
}
.tape-ruler::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 10px;
background:
repeating-linear-gradient(
90deg,
transparent 0 29px,
var(--ink) 29px 31px,
transparent 31px 60px
);
}
.tape-needle {
position: absolute;
z-index: 3;
top: 0;
bottom: 0;
width: 3px;
background: var(--red);
transform: translateX(-1px);
transition: left 120ms ease;
}
.tape-caption {
display: flex;
justify-content: space-between;
margin-top: 7px;
font-size: 9px;
font-weight: 800;
}
.compare-list {
display: grid;
gap: 7px;
}
.compare-row {
padding: 9px;
border: 1px solid var(--line);
background: #fff;
cursor: pointer;
}
.compare-row.active {
border: 2px solid var(--ink);
padding: 8px;
}
.compare-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
font-size: 10px;
font-weight: 800;
}
.compare-data {
color: var(--muted);
margin-top: 6px;
font-size: 9px;
line-height: 1.45;
}
.width-bar {
height: 5px;
margin-top: 7px;
background: #e4e1d8;
overflow: hidden;
}
.width-bar i {
display: block;
height: 100%;
background: var(--blue);
}
.width-bar i.over {
background: var(--red);
}
.legend {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 8px;
margin-top: 8px;
}
.help {
position: fixed;
z-index: 12;
left: 50%;
bottom: 13px;
transform: translateX(-50%);
padding: 8px 11px;
background: rgba(23, 33, 38, 0.88);
color: #fff;
font-size: 9px;
letter-spacing: 0.025em;
pointer-events: none;
white-space: nowrap;
box-shadow: 3px 3px 0 rgba(23, 33, 38, 0.18);
}
.help b {
color: var(--yellow);
}
#toast {
position: fixed;
z-index: 40;
top: 80px;
left: 50%;
transform: translate(-50%, -12px);
max-width: 420px;
padding: 10px 14px;
border: 2px solid var(--ink);
background: #fff;
box-shadow: 4px 4px 0 rgba(23, 33, 38, 0.18);
font-size: 10px;
line-height: 1.45;
opacity: 0;
pointer-events: none;
transition: opacity 150ms ease, transform 150ms ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.bad {
border-color: var(--red);
}
#toast.good {
border-color: var(--green);
}
@media (max-width: 980px) {
#compare {
width: 260px;
}
#controls {
width: 270px;
}
}
@media (max-width: 760px) {
.brand small,
.help,
#compare {
display: none;
}
.panel {
top: auto;
bottom: 12px;
max-height: 48vh;
}
#controls {
left: 10px;
width: calc(100% - 20px);
}
.topbar {
left: 10px;
right: 10px;
top: 10px;
}
.brand {
min-height: 40px;
}
.brand-mark {
width: 25px;
height: 25px;
}
.brand h1 {
font-size: 12px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>TAPE / FIT</h1>
<small>VOXEL MEASUREMENT + COLLISION LAB</small>
</div>
</div>
<div class="top-actions">
<button class="icon-button" id="cameraReset" title="Reset camera">RESET VIEW</button>
</div>
</div>
<aside class="panel" id="controls">
<div class="panel-head">
<span>Load Control</span>
<span>01 / SELECT</span>
</div>
<div class="section">
<h2 class="section-title">
Cargo boxes
<small>click model or card</small>
</h2>
<div class="box-list" id="boxList"></div>
</div>
<div class="section">
<h2 class="section-title">
Rotation
<small>yaw around vertical axis</small>
</h2>
<label class="control-row">
<span>ANGLE</span>
<output id="yawValue">0°</output>
</label>
<input id="yaw" type="range" min="0" max="355" step="5" value="0">
<button class="secondary" id="rotate90">ROTATE +90°</button>
</div>
<div class="section">
<h2 class="section-title">
Destination
<small>route uses doorway center</small>
</h2>
<label class="control-row">
<span>X</span>
<output id="targetXValue">0.00 m</output>
</label>
<input id="targetX" type="range" min="-4.5" max="4.5" step="0.1" value="0">
<label class="control-row">
<span>Z</span>
<output id="targetZValue">3.50 m</output>
</label>
<input id="targetZ" type="range" min="2" max="6" step="0.1" value="3.5">
<button class="primary" id="moveBox">MOVE / CHECK PATH</button>
<div class="status" id="status">
Ready. Select a cargo box and inspect its rotated bounds.
</div>
<button class="secondary" id="resetLayout">RESET ALL BOXES</button>
</div>
</aside>
<aside class="panel" id="compare">
<div class="panel-head">
<span>Measurement Board</span>
<span>02 / COMPARE</span>
</div>
<div class="section">
<h2 class="section-title">
Doorway
<small>clear opening</small>
</h2>
<div class="opening-grid">
<div class="metric">
<strong>2.40 m</strong>
<small>clear width</small>
</div>
<div class="metric">
<strong>2.40 m</strong>
<small>clear height</small>
</div>
</div>
<div class="tape-wrap">
<div class="tape-ruler">
<i class="tape-needle" id="tapeNeedle"></i>
</div>
<div class="tape-caption">
<span id="selectedWidth">1.55 m BOUND</span>
<span>2.40 m DOOR</span>
</div>
</div>
</div>
<div class="section">
<h2 class="section-title">
Bounding dimensions
<small>ranked by footprint area</small>
</h2>
<div class="compare-list" id="compareList"></div>
<div class="legend">
<span>W × H × D</span>
<span>BAR = ROTATED WIDTH</span>
</div>
</div>
</aside>
<div class="help">
<b>DRAG</b> orbit ·
<b>RIGHT/SHIFT DRAG</b> pan ·
<b>WHEEL</b> zoom ·
<b>CLICK</b> select ·
<b>1–3</b> cargo ·
<b>R</b> rotate ·
<b>SPACE</b> move
</div>
<div id="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Configuration
// ------------------------------------------------------------
const DOOR = {
width: 2.4,
height: 2.4,
thickness: 0.44,
wallMinX: -7,
wallMaxX: 7,
wallHeight: 4.2
};
const DEFAULT_BOXES = [
{
id: "A",
name: "Crate A",
color: 0xeb7047,
dimensions: [1.55, 1.15, 1.35],
position: [-3.5, -3.6],
yaw: 0,
target: [0, 3.5]
},
{
id: "B",
name: "Crate B",
color: 0x3c82a6,
dimensions: [1.05, 1.85, 0.95],
position: [0, -4.4],
yaw: 90,
target: [2, 4.4]
},
{
id: "C",
name: "Crate C",
color: 0x64a879,
dimensions: [2.6, 0.85, 1.25],
position: [3.5, -3.4],
yaw: 0,
target: [-2, 4.4]
}
];
const boxes = DEFAULT_BOXES.map((source) => ({
...source,
dimensions: [...source.dimensions],
position: [...source.position],
target: [...source.target],
yaw: THREE.MathUtils.degToRad(source.yaw)
}));
let selectedId = "A";
let motion = null;
let toastTimer = 0;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd8d6cd);
scene.fog = new THREE.Fog(0xd8d6cd, 18, 38);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
document.querySelector("#scene").appendChild(renderer.domElement);
renderer.domElement.tabIndex = 0;
const camera = new THREE.OrthographicCamera(
-10,
10,
8,
-8,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.9, 0);
const cameraSpherical = new THREE.Spherical(22, 0.83, 0.72);
let cameraZoom = 1;
function applyCamera() {
camera.position.setFromSpherical(cameraSpherical).add(cameraTarget);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewSize = aspect < 1 ? 17 : 12.5;
camera.left = (-viewSize * aspect) / 2;
camera.right = (viewSize * aspect) / 2;
camera.top = viewSize / 2;
camera.bottom = -viewSize / 2;
renderer.setSize(width, height, false);
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
applyCamera();
// ------------------------------------------------------------
// Lighting
// ------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xf7f3df, 0x69777a, 2.2));
const sun = new THREE.DirectionalLight(0xfff1ce, 3.2);
sun.position.set(-7, 13, -8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -13;
sun.shadow.camera.right = 13;
sun.shadow.camera.top = 13;
sun.shadow.camera.bottom = -13;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xaac9dd, 1.05);
fill.position.set(9, 7, 10);
scene.add(fill);
// ------------------------------------------------------------
// Ground and voxel architecture
// ------------------------------------------------------------
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xd1cec3,
roughness: 0.95,
metalness: 0
});
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(32, 32),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.035;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(30, 60, 0x8d918b, 0xa9aaa3);
grid.position.y = -0.015;
grid.material.transparent = true;
grid.material.opacity = 0.25;
scene.add(grid);
const stagingPad = new THREE.Mesh(
new THREE.PlaneGeometry(11.5, 6.4),
new THREE.MeshStandardMaterial({
color: 0xc8bba8,
roughness: 1
})
);
stagingPad.rotation.x = -Math.PI / 2;
stagingPad.position.set(0, -0.025, -3.3);
stagingPad.receiveShadow = true;
scene.add(stagingPad);
const dockPad = new THREE.Mesh(
new THREE.PlaneGeometry(11.5, 6.4),
new THREE.MeshStandardMaterial({
color: 0xb9c6bb,
roughness: 1
})
);
dockPad.rotation.x = -Math.PI / 2;
dockPad.position.set(0, -0.025, 3.3);
dockPad.receiveShadow = true;
scene.add(dockPad);
const wallPalette = [0xc9c5b8, 0xd4d0c3, 0xbdb9ad, 0xded9ca];
function buildVoxelWall(x0, x1, y0, y1) {
const voxelX = 0.5;
const voxelY = 0.6;
let x = x0;
while (x < x1 - 0.0001) {
const width = Math.min(voxelX, x1 - x);
let y = y0;
while (y < y1 - 0.0001) {
const height = Math.min(voxelY, y1 - y);
const colorIndex =
(Math.floor((x - x0) / voxelX) +
Math.floor((y - y0) / voxelY)) %
wallPalette.length;
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width - 0.012, height - 0.012, DOOR.thickness),
new THREE.MeshStandardMaterial({
color: wallPalette[colorIndex],
roughness: 0.88
})
);
mesh.position.set(
x + width / 2,
y + height / 2,
0
);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
y += height;
}
x += width;
}
}
const halfDoor = DOOR.width / 2;
buildVoxelWall(DOOR.wallMinX, -halfDoor, 0, DOOR.wallHeight);
buildVoxelWall(halfDoor, DOOR.wallMaxX, 0, DOOR.wallHeight);
buildVoxelWall(-halfDoor, halfDoor, DOOR.height, DOOR.wallHeight);
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x35454a,
roughness: 0.7
});
function framePiece(width, height, x, y) {
const piece = new THREE.Mesh(
new THREE.BoxGeometry(width, height, 0.56),
frameMaterial
);
piece.position.set(x, y, -0.02);
piece.castShadow = true;
piece.receiveShadow = true;
scene.add(piece);
}
// Frame pieces sit outside the measured clear opening.
framePiece(0.14, DOOR.height, -halfDoor - 0.07, DOOR.height / 2);
framePiece(0.14, DOOR.height, halfDoor + 0.07, DOOR.height / 2);
framePiece(DOOR.width + 0.28, 0.14, 0, DOOR.height + 0.07);
// ------------------------------------------------------------
// Static collision geometry
// ------------------------------------------------------------
function staticBox(label, x0, x1, y0, y1, z0, z1) {
return {
label,
type: "static",
cx: (x0 + x1) / 2,
cz: (z0 + z1) / 2,
hx: (x1 - x0) / 2,
hz: (z1 - z0) / 2,
yaw: 0,
bottom: y0,
top: y1
};
}
const staticColliders = [
staticBox(
"left wall",
DOOR.wallMinX,
-halfDoor,
0,
DOOR.wallHeight,
-DOOR.thickness / 2,
DOOR.thickness / 2
),
staticBox(
"right wall",
halfDoor,
DOOR.wallMaxX,
0,
DOOR.wallHeight,
-DOOR.thickness / 2,
DOOR.thickness / 2
),
staticBox(
"door lintel",
-halfDoor,
halfDoor,
DOOR.height,
DOOR.wallHeight,
-DOOR.thickness / 2,
DOOR.thickness / 2
)
];
// ------------------------------------------------------------
// Text and tape helpers
// ------------------------------------------------------------
function makeTextSprite(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
if (options.background !== false) {
context.fillStyle = options.background || "rgba(23,33,38,0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
}
context.fillStyle = options.color || "#ffffff";
context.font = `${options.weight || 700} ${options.size || 36}px monospace`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: options.depthTest !== false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(options.width || 2.2, options.height || 0.55, 1);
sprite.renderOrder = 8;
return sprite;
}
function makeHorizontalTapeTexture(length) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "#f4c542";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(0,0,0,0.12)";
context.fillRect(0, 100, canvas.width, 28);
const pixelsPerMeter = canvas.width / length;
for (let tenth = 0; tenth <= length * 10; tenth++) {
const x = (tenth / 10) * pixelsPerMeter;
const major = tenth % 5 === 0;
const meter = tenth % 10 === 0;
context.fillStyle = meter ? "#bd3e35" : "#172126";
context.fillRect(
Math.min(canvas.width - 2, x),
0,
meter ? 3 : 2,
major ? 67 : 37
);
if (major && tenth > 0) {
context.fillStyle = "#172126";
context.font = "700 25px monospace";
context.textAlign = "left";
context.fillText(
(tenth / 10).toFixed(1),
Math.min(canvas.width - 42, x + 5),
92
);
}
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
function makeVerticalTapeTexture(length) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 1024;
const context = canvas.getContext("2d");
context.fillStyle = "#f4c542";
context.fillRect(0, 0, canvas.width, canvas.height);
const pixelsPerMeter = canvas.height / length;
for (let tenth = 0; tenth <= length * 10; tenth++) {
const y = canvas.height - (tenth / 10) * pixelsPerMeter;
const major = tenth % 5 === 0;
const meter = tenth % 10 === 0;
context.fillStyle = meter ? "#bd3e35" : "#172126";
context.fillRect(
0,
Math.max(0, y - (meter ? 3 : 2)),
major ? 68 : 38,
meter ? 3 : 2
);
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
// Physical yellow tape reel and extended tape.
const reel = new THREE.Group();
reel.position.set(-halfDoor - 0.36, 0.27, -0.4);
const reelBody = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.5, 0.24),
new THREE.MeshStandardMaterial({
color: 0xf4c542,
roughness: 0.65
})
);
reelBody.castShadow = true;
reel.add(reelBody);
const reelFace = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.18, 0.035),
new THREE.MeshStandardMaterial({
color: 0x263438,
roughness: 0.7
})
);
reelFace.position.z = 0.14;
reel.add(reelFace);
const reelButton = new THREE.Mesh(
new THREE.BoxGeometry(0.1, 0.06, 0.04),
new THREE.MeshStandardMaterial({ color: 0xcc4b43 })
);
reelButton.position.set(0, 0.18, 0.17);
reel.add(reelButton);
scene.add(reel);
const horizontalTape = new THREE.Mesh(
new THREE.PlaneGeometry(DOOR.width, 0.18),
new THREE.MeshStandardMaterial({
map: makeHorizontalTapeTexture(DOOR.width),
side: THREE.DoubleSide,
roughness: 0.75
})
);
horizontalTape.rotation.x = -Math.PI / 2;
horizontalTape.position.set(0, 0.018, -0.31);
horizontalTape.receiveShadow = true;
scene.add(horizontalTape);
const tapeConnector = new THREE.Mesh(
new THREE.BoxGeometry(0.3, 0.025, 0.18),
new THREE.MeshStandardMaterial({ color: 0xf4c542 })
);
tapeConnector.position.set(-halfDoor - 0.15, 0.018, -0.31);
scene.add(tapeConnector);
const verticalTape = new THREE.Mesh(
new THREE.PlaneGeometry(0.18, DOOR.height),
new THREE.MeshStandardMaterial({
map: makeVerticalTapeTexture(DOOR.height),
side: THREE.DoubleSide,
roughness: 0.75
})
);
verticalTape.position.set(-halfDoor - 0.16, DOOR.height / 2, -0.29);
scene.add(verticalTape);
const widthLabel = makeTextSprite("2.40 m CLEAR", {
width: 1.8,
height: 0.42,
size: 34
});
widthLabel.position.set(0, 2.72, -0.36);
scene.add(widthLabel);
const heightLabel = makeTextSprite("2.40 m", {
width: 1.15,
height: 0.38,
size: 34
});
heightLabel.position.set(-halfDoor - 0.28, 1.18, -0.36);
scene.add(heightLabel);
// ------------------------------------------------------------
// Cargo boxes
// ------------------------------------------------------------
const pickables = [];
function createBox(box) {
const group = new THREE.Group();
const [width, height, depth] = box.dimensions;
const material = new THREE.MeshStandardMaterial({
color: box.color,
roughness: 0.68,
metalness: 0.02,
flatShading: true
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.boxId = box.id;
group.add(mesh);
pickables.push(mesh);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x263438,
transparent: true,
opacity: 0.8
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
edgeMaterial
);
group.add(edges);
// A small raised voxel "strap" makes the boxes read as cargo.
const strap = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.035, 0.045, depth + 0.035),
new THREE.MeshStandardMaterial({
color: 0x263438,
roughness: 0.8
})
);
strap.position.y = height * 0.17;
strap.castShadow = true;
group.add(strap);
const label = makeTextSprite(
`${box.id} ${width.toFixed(2)}×${height.toFixed(2)}×${depth.toFixed(2)}`,
{
width: 2.55,
height: 0.48,
size: 29,
depthTest: false
}
);
label.position.set(0, height + 0.38, 0);
group.add(label);
scene.add(group);
box.group = group;
box.mesh = mesh;
updateBoxTransform(box);
}
function updateBoxTransform(box) {
box.group.position.set(box.position[0], 0, box.position[1]);
box.group.rotation.y = box.yaw;
}
boxes.forEach(createBox);
// ------------------------------------------------------------
// Selection ring, target marker, and path display
// ------------------------------------------------------------
const selectionMaterial = new THREE.LineBasicMaterial({
color: 0xeb7047,
depthTest: false
});
const selectionRing = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.5, 0, -0.5),
new THREE.Vector3(0.5, 0, -0.5),
new THREE.Vector3(0.5, 0, 0.5),
new THREE.Vector3(-0.5, 0, 0.5)
]),
selectionMaterial
);
selectionRing.renderOrder = 7;
scene.add(selectionRing);
const targetMaterial = new THREE.LineBasicMaterial({
color: 0x31865c,
depthTest: false
});
const targetMarker = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.72, 0, -0.72),
new THREE.Vector3(0.72, 0, -0.72),
new THREE.Vector3(0.72, 0, 0.72),
new THREE.Vector3(-0.72, 0, 0.72)
]),
targetMaterial
);
targetMarker.position.y = 0.025;
targetMarker.renderOrder = 7;
scene.add(targetMarker);
const targetLabel = makeTextSprite("DESTINATION", {
width: 1.65,
height: 0.36,
size: 28,
background: "rgba(49,134,92,0.9)"
});
targetLabel.position.y = 0.28;
targetMarker.add(targetLabel);
const pathGroup = new THREE.Group();
scene.add(pathGroup);
let pathLine = null;
let pathWaypoints = [];
function clearPathVisuals() {
if (pathLine) {
pathLine.geometry.dispose();
pathLine.material.dispose();
pathGroup.remove(pathLine);
pathLine = null;
}
for (const point of pathWaypoints) {
point.geometry.dispose();
point.material.dispose();
pathGroup.remove(point);
}
pathWaypoints = [];
}
function makePath(box) {
const startX = box.position[0];
const startZ = box.position[1];
const endX = box.target[0];
const endZ = box.target[1];
const clearanceLane = 1.72;
const points = [];
function add(x, z) {
const previous = points[points.length - 1];
if (!previous || Math.hypot(previous.x - x, previous.z - z) > 0.0001) {
points.push({ x, z });
}
}
add(startX, startZ);
if (startZ < 0) {
add(startX, -clearanceLane);
add(0, -clearanceLane);
add(0, clearanceLane);
add(endX, clearanceLane);
add(endX, endZ);
} else if (endZ < 0) {
add(endX, clearanceLane);
add(0, clearanceLane);
add(0, -clearanceLane);
add(startX, -clearanceLane);
add(startX, startZ);
} else {
add(endX, endZ);
}
const lengths = [];
let total = 0;
for (let i = 1; i < points.length; i++) {
const length = Math.hypot(
points[i].x - points[i - 1].x,
points[i].z - points[i - 1].z
);
lengths.push(length);
total += length;
}
return { points, lengths, total };
}
function updatePathVisuals() {
clearPathVisuals();
const box = getSelectedBox();
const path = makePath(box);
if (path.points.length < 2) return;
const geometry = new THREE.BufferGeometry().setFromPoints(
path.points.map((point) => new THREE.Vector3(point.x, 0.055, point.z))
);
pathLine = new THREE.Line(
geometry,
new THREE.LineDashedMaterial({
color: 0x2e789d,
dashSize: 0.16,
gapSize: 0.1,
linewidth: 1,
depthTest: false
})
);
pathLine.computeLineDistances();
pathLine.renderOrder = 6;
pathGroup.add(pathLine);
for (const point of path.points) {
const waypoint = new THREE.Mesh(
new THREE.BoxGeometry(0.11, 0.055, 0.11),
new THREE.MeshBasicMaterial({
color: 0x2e789d,
depthTest: false
})
);
waypoint.position.set(point.x, 0.04, point.z);
waypoint.renderOrder = 6;
pathGroup.add(waypoint);
pathWaypoints.push(waypoint);
}
}
// ------------------------------------------------------------
// Bounds, oriented boxes, and SAT collision checks
// ------------------------------------------------------------
function getSelectedBox() {
return boxes.find((box) => box.id === selectedId);
}
function rotatedBounds(box) {
const cosine = Math.abs(Math.cos(box.yaw));
const sine = Math.abs(Math.sin(box.yaw));
const [width, height, depth] = box.dimensions;
return {
width: cosine * width + sine * depth,
height,
depth: sine * width + cosine * depth,
area:
(cosine * width + sine * depth) *
(sine * width + cosine * depth)
};
}
function makeOBB(box, x = box.position[0], z = box.position[1], yaw = box.yaw) {
const cosine = Math.cos(yaw);
const sine = Math.sin(yaw);
return {
label: box.name,
type: "box",
id: box.id,
cx: x,
cz: z,
hx: box.dimensions[0] / 2,
hz: box.dimensions[2] / 2,
bottom: 0,
top: box.dimensions[1],
axisX: { x: cosine, z: -sine },
axisZ: { x: sine, z: cosine }
};
}
function obbFromStatic(collider) {
return {
...collider,
axisX: { x: 1, z: 0 },
axisZ: { x: 0, z: 1 }
};
}
function intersectsOBB(a, b) {
const epsilon = 0.00001;
if (
a.top <= b.bottom + epsilon ||
b.top <= a.bottom + epsilon
) {
return false;
}
const axes = [
a.axisX || { x: 1, z: 0 },
a.axisZ || { x: 0, z: 1 },
b.axisX || { x: 1, z: 0 },
b.axisZ || { x: 0, z: 1 }
];
for (const axis of axes) {
const distance = Math.abs(
(b.cx - a.cx) * axis.x +
(b.cz - a.cz) * axis.z
);
const radiusA =
a.hx * Math.abs(
(a.axisX || { x: 1, z: 0 }).x * axis.x +
(a.axisX || { x: 1, z: 0 }).z * axis.z
) +
a.hz * Math.abs(
(a.axisZ || { x: 0, z: 1 }).x * axis.x +
(a.axisZ || { x: 0, z: 1 }).z * axis.z
);
const radiusB =
b.hx * Math.abs(
(b.axisX || { x: 1, z: 0 }).x * axis.x +
(b.axisX || { x: 1, z: 0 }).z * axis.z
) +
b.hz * Math.abs(
(b.axisZ || { x: 0, z: 1 }).x * axis.x +
(b.axisZ || { x: 0, z: 1 }).z * axis.z
);
if (distance > radiusA + radiusB - epsilon) {
return false;
}
}
return true;
}
function findCollision(box, x, z, yaw, excludedId = box.id) {
const candidate = makeOBB(box, x, z, yaw);
for (const collider of staticColliders) {
if (intersectsOBB(candidate, obbFromStatic(collider))) {
return collider;
}
}
for (const other of boxes) {
if (other.id === excludedId) continue;
if (intersectsOBB(candidate, makeOBB(other))) {
return {
label: other.name,
type: "box"
};
}
}
return null;
}
function pointAtDistance(path, distance) {
if (path.total <= 0) {
return { ...path.points[0] };
}
let remaining = Math.max(0, Math.min(distance, path.total));
for (let i = 0; i < path.lengths.length; i++) {
const length = path.lengths[i];
if (remaining <= length || i === path.lengths.length - 1) {
const t = length > 0 ? remaining / length : 0;
const a = path.points[i];
const b = path.points[i + 1];
return {
x: THREE.MathUtils.lerp(a.x, b.x, t),
z: THREE.MathUtils.lerp(a.z, b.z, t)
};
}
remaining -= length;
}
return { ...path.points[path.points.length - 1] };
}
// ------------------------------------------------------------
// UI construction and updates
// ------------------------------------------------------------
const boxList = document.querySelector("#boxList");
const compareList = document.querySelector("#compareList");
const yawInput = document.querySelector("#yaw");
const targetXInput = document.querySelector("#targetX");
const targetZInput = document.querySelector("#targetZ");
const statusElement = document.querySelector("#status");
const moveButton = document.querySelector("#moveBox");
for (const box of boxes) {
const card = document.createElement("button");
card.className = "box-card";
card.dataset.id = box.id;
card.innerHTML = `
<span class="swatch" style="background:#${box.color.toString(16).padStart(6, "0")}"></span>
<span>
<span class="box-name">${box.name}</span>
<span class="box-dims"></span>
</span>
<span class="fit-badge"></span>
`;
boxList.appendChild(card);
const row = document.createElement("button");
row.className = "compare-row";
row.dataset.id = box.id;
row.innerHTML = `
<span class="compare-top">
<span class="rank-name">${box.name}</span>
<span class="fit-badge"></span>
</span>
<span class="compare-data"></span>
<span class="width-bar"><i></i></span>
`;
compareList.appendChild(row);
}
function fitState(box) {
const bounds = rotatedBounds(box);
const fits =
bounds.width <= DOOR.width + 0.0001 &&
bounds.height <= DOOR.height + 0.0001;
return {
fits,
bounds,
label: fits ? "FIT" : "NO FIT"
};
}
function setStatus(message, type = "") {
statusElement.textContent = message;
statusElement.className = `status ${type}`;
}
function showToast(message, type = "") {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.className = `visible ${type}`;
window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => {
toast.className = "";
}, 2400);
}
function updateSelectionVisuals() {
const box = getSelectedBox();
const bounds = rotatedBounds(box);
const halfWidth = bounds.width / 2 + 0.08;
const halfDepth = bounds.depth / 2 + 0.08;
selectionRing.position.set(box.position[0], 0.035, box.position[1]);
selectionRing.scale.set(halfWidth * 2, 1, halfDepth * 2);
targetMarker.position.x = box.target[0];
targetMarker.position.z = box.target[1];
}
function updateUI() {
const selected = getSelectedBox();
for (const box of boxes) {
const state = fitState(box);
const bounds = state.bounds;
const card = boxList.querySelector(`[data-id="${box.id}"]`);
const row = compareList.querySelector(`[data-id="${box.id}"]`);
card.classList.toggle("active", box.id === selectedId);
row.classList.toggle("active", box.id === selectedId);
card.querySelector(".box-dims").innerHTML =
`BASE ${box.dimensions.map((v) => v.toFixed(2)).join(" × ")}<br>` +
`BOUND ${bounds.width.toFixed(2)} × ${bounds.height.toFixed(2)} × ${bounds.depth.toFixed(2)}`;
card.querySelector(".fit-badge").textContent = state.label;
card.querySelector(".fit-badge").className =
`fit-badge ${state.fits ? "yes" : "no"}`;
row.querySelector(".fit-badge").textContent = state.label;
row.querySelector(".fit-badge").className =
`fit-badge ${state.fits ? "yes" : "no"}`;
row.querySelector(".compare-data").innerHTML =
`W ${bounds.width.toFixed(2)} m H ${bounds.height.toFixed(2)} m D ${bounds.depth.toFixed(2)} m<br>` +
`Footprint ${bounds.area.toFixed(2)} m² / width clearance ${(DOOR.width - bounds.width).toFixed(2)} m`;
const bar = row.querySelector(".width-bar i");
const ratio = Math.min(bounds.width / DOOR.width, 1);
bar.style.width = `${ratio * 100}%`;
bar.classList.toggle("over", bounds.width > DOOR.width);
}
const sorted = [...boxes].sort(
(a, b) => rotatedBounds(b).area - rotatedBounds(a).area
);
for (const box of sorted) {
compareList.appendChild(
compareList.querySelector(`[data-id="${box.id}"]`)
);
}
const selectedBounds = rotatedBounds(selected);
const selectedDegrees = Math.round(
THREE.MathUtils.radToDeg(selected.yaw)
) % 360;
yawInput.value = selectedDegrees;
document.querySelector("#yawValue").textContent = `${selectedDegrees}°`;
targetXInput.value = selected.target[0];
targetZInput.value = selected.target[1];
document.querySelector("#targetXValue").textContent =
`${selected.target[0].toFixed(2)} m`;
document.querySelector("#targetZValue").textContent =
`${selected.target[1].toFixed(2)} m`;
document.querySelector("#selectedWidth").textContent =
`${selectedBounds.width.toFixed(2)} m BOUND`;
const needle = document.querySelector("#tapeNeedle");
const needlePercent = Math.min(
(selectedBounds.width / DOOR.width) * 100,
100
);
needle.style.left = `${needlePercent}%`;
updateSelectionVisuals();
}
function selectBox(id) {
if (motion) {
showToast("Wait for the current collision-checked move to finish.", "bad");
return;
}
selectedId = id;
updateUI();
updatePathVisuals();
setStatus(
`${getSelectedBox().name} selected. Rotate it to compare its clear width before moving.`
);
}
// ------------------------------------------------------------
// Rotation
// ------------------------------------------------------------
function trySetYaw(degrees) {
const box = getSelectedBox();
if (motion) {
showToast("Cannot rotate while a box is moving.", "bad");
return false;
}
const oldYaw = box.yaw;
const normalized = ((degrees % 360) + 360) % 360;
box.yaw = THREE.MathUtils.degToRad(normalized);
const collision = findCollision(
box,
box.position[0],
box.position[1],
box.yaw
);
if (collision) {
box.yaw = oldYaw;
updateBoxTransform(box);
updateUI();
setStatus(
`Rotation blocked by ${collision.label}. Try another yaw angle.`,
"bad"
);
showToast(`Rotation blocked by ${collision.label}.`, "bad");
return false;
}
updateBoxTransform(box);
updateUI();
updateSelectionVisuals();
const bounds = rotatedBounds(box);
setStatus(
`Yaw ${normalized}°. Rotated bounds: ${bounds.width.toFixed(2)} × ` +
`${bounds.height.toFixed(2)} × ${bounds.depth.toFixed(2)} m.`,
bounds.width <= DOOR.width ? "good" : "bad"
);
return true;
}
yawInput.addEventListener("input", () => {
trySetYaw(Number(yawInput.value));
});
document.querySelector("#rotate90").addEventListener("click", () => {
const box = getSelectedBox();
const degrees = Math.round(THREE.MathUtils.radToDeg(box.yaw));
trySetYaw(degrees + 90);
});
// ------------------------------------------------------------
// Continuous swept motion
// ------------------------------------------------------------
function updateMotion(delta) {
if (!motion) return;
const speed = 2.35;
let remaining = speed * delta;
while (remaining > 0 && motion) {
const step = Math.min(remaining, 0.04);
const nextDistance = Math.min(
motion.path.total,
motion.distance + step
);
const nextPoint = pointAtDistance(
motion.path,
nextDistance
);
const collision = findCollision(
motion.box,
nextPoint.x,
nextPoint.z,
motion.box.yaw
);
if (collision) {
const safePoint = pointAtDistance(
motion.path,
motion.distance
);
motion.box.position[0] = safePoint.x;
motion.box.position[1] = safePoint.z;
updateBoxTransform(motion.box);
setStatus(
`Path blocked by ${collision.label}. The box stopped at the last safe sample.`,
"bad"
);
showToast(
`Collision with ${collision.label}. Rotate or choose another destination.`,
"bad"
);
motion = null;
moveButton.disabled = false;
updateUI();
return;
}
motion.distance = nextDistance;
motion.box.position[0] = nextPoint.x;
motion.box.position[1] = nextPoint.z;
updateBoxTransform(motion.box);
remaining -= step;
if (motion.distance >= motion.path.total - 0.00001) {
motion.box.position[0] = motion.box.target[0];
motion.box.position[1] = motion.box.target[1];
updateBoxTransform(motion.box);
setStatus(
`${motion.box.name} arrived. Every swept path sample passed the collision test.`,
"good"
);
showToast(
`${motion.box.name} moved successfully through the checked route.`,
"good"
);
motion = null;
moveButton.disabled = false;
updateUI();
return;
}
}
if (motion) {
const percent = Math.round(
(motion.distance / Math.max(motion.path.total, 0.0001)) * 100
);
setStatus(
`Moving ${motion.box.name}... swept collision test active (${percent}%).`,
"busy"
);
}
}
moveButton.addEventListener("click", () => {
if (motion) return;
const box = getSelectedBox();
const path = makePath(box);
if (path.total < 0.001) {
setStatus("The box is already at this destination.", "good");
return;
}
motion = {
box,
path,
distance: 0
};
moveButton.disabled = true;
setStatus(
`Moving ${box.name}. Checking the full path in 4 cm swept samples...`,
"busy"
);
});
targetXInput.addEventListener("input", () => {
const box = getSelectedBox();
box.target[0] = Number(targetXInput.value);
document.querySelector("#targetXValue").textContent =
`${box.target[0].toFixed(2)} m`;
updateSelectionVisuals();
updatePathVisuals();
});
targetZInput.addEventListener("input", () => {
const box = getSelectedBox();
box.target[1] = Number(targetZInput.value);
document.querySelector("#targetZValue").textContent =
`${box.target[1].toFixed(2)} m`;
updateSelectionVisuals();
updatePathVisuals();
});
document.querySelector("#resetLayout").addEventListener("click", () => {
motion = null;
moveButton.disabled = false;
boxes.forEach((box, index) => {
const defaults = DEFAULT_BOXES[index];
box.position = [...defaults.position];
box.yaw = THREE.MathUtils.degToRad(defaults.yaw);
box.target = [...defaults.target];
updateBoxTransform(box);
});
selectedId = "A";
updateUI();
updatePathVisuals();
setStatus("Layout reset. All boxes are back in the staging area.");
showToast("Layout reset.", "good");
});
boxList.addEventListener("click", (event) => {
const card = event.target.closest("[data-id]");
if (card) selectBox(card.dataset.id);
});
compareList.addEventListener("click", (event) => {
const row = event.target.closest("[data-id]");
if (row) selectBox(row.dataset.id);
});
// ------------------------------------------------------------
// Selection raycasting
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickBox(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);
const hits = raycaster.intersectObjects(pickables, false);
if (hits.length) {
selectBox(hits[0].object.userData.boxId);
}
}
// ------------------------------------------------------------
// Custom camera controls — no external controls/addons
// ------------------------------------------------------------
let drag = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.focus();
renderer.domElement.setPointerCapture(event.pointerId);
drag = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
button: event.button,
moved: 0
};
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!drag || drag.pointerId !== event.pointerId) return;
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
drag.lastX = event.clientX;
drag.lastY = event.clientY;
drag.moved += Math.abs(dx) + Math.abs(dy);
const wantsPan =
drag.button === 2 ||
drag.button === 1 ||
event.shiftKey;
if (wantsPan) {
const right = new THREE.Vector3(
Math.cos(cameraSpherical.theta),
0,
-Math.sin(cameraSpherical.theta)
);
const forward = new THREE.Vector3(
-Math.sin(cameraSpherical.theta),
0,
-Math.cos(cameraSpherical.theta)
);
cameraTarget.addScaledVector(
right,
(-dx * 0.018) / cameraZoom
);
cameraTarget.addScaledVector(
forward,
(dy * 0.018) / cameraZoom
);
} else {
cameraSpherical.theta -= dx * 0.006;
cameraSpherical.phi = THREE.MathUtils.clamp(
cameraSpherical.phi + dy * 0.005,
0.35,
1.35
);
}
applyCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!drag || drag.pointerId !== event.pointerId) return;
if (
drag.button === 0 &&
!event.shiftKey &&
drag.moved < 6
) {
pickBox(event);
}
drag = null;
});
renderer.domElement.addEventListener("pointercancel", () => {
drag = null;
});
renderer.domElement.addEventListener(
"contextmenu",
(event) => event.preventDefault()
);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * Math.exp(-event.deltaY * 0.001),
0.65,
2.4
);
applyCamera();
},
{ passive: false }
);
function resetCamera() {
cameraTarget.set(0, 0.9, 0);
cameraSpherical.set(22, 0.83, 0.72);
cameraZoom = 1;
applyCamera();
}
document.querySelector("#cameraReset").addEventListener(
"click",
resetCamera
);
// ------------------------------------------------------------
// Keyboard shortcuts
// ------------------------------------------------------------
window.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA") return;
if (event.key === "1") selectBox("A");
if (event.key === "2") selectBox("B");
if (event.key === "3") selectBox("C");
if (event.key.toLowerCase() === "r") {
const box = getSelectedBox();
trySetYaw(
Math.round(THREE.MathUtils.radToDeg(box.yaw)) + 90
);
}
if (event.code === "Space") {
event.preventDefault();
moveButton.click();
}
if (event.key === "0") resetCamera();
});
// ------------------------------------------------------------
// Render loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
updateMotion(delta);
renderer.render(scene, camera);
}
updateUI();
updatePathVisuals();
applyCamera();
animate();
</script>
</body>
</html>
```