Prompt specification
Build or customize the Three.js 3D scene "Functional pocket placement workshop" 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: Functional pocket placement workshop
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/functional-pocket-placement-workshop-x0604
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Create a configurable apron with removable pocket modules and task objects; users choose placements that keep tools reachable without overlapping bending or sitting regions.
Working Three.js Starter (functional-pocket-placement-workshop-x0604):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Voxel Apron Studio</title>
<style>
:root {
--ink: #172127;
--muted: #6f7a7e;
--paper: rgba(250, 248, 243, 0.92);
--line: rgba(23, 33, 39, 0.12);
--orange: #c9703d;
--orange-dark: #8d4327;
--teal: #287a73;
--green: #47a879;
--red: #d95757;
--yellow: #e8b84d;
--shadow: 0 18px 50px rgba(25, 37, 41, 0.16);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8e4dc;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button {
border: 0;
cursor: pointer;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.sidebar {
position: fixed;
z-index: 10;
top: 16px;
left: 16px;
bottom: 16px;
width: 344px;
padding: 18px;
overflow: auto;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 22px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
scrollbar-width: thin;
}
.brand {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(3, 7px);
grid-template-rows: repeat(3, 7px);
gap: 3px;
padding: 10px;
border-radius: 12px;
background: var(--ink);
transform: rotate(-3deg);
}
.brand-mark i {
display: block;
border-radius: 1px;
background: #f4d6a2;
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(4),
.brand-mark i:nth-child(8) {
background: var(--orange);
}
.eyebrow {
margin: 0 0 3px;
color: var(--orange-dark);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 22px;
line-height: 1.05;
letter-spacing: -0.04em;
}
.version {
padding: 6px 9px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.intro {
margin: 0 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.section {
padding: 15px 0;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.section-title h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.section-title span {
color: var(--muted);
font-size: 10px;
}
.range-row {
margin: 11px 0;
}
.range-label {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
font-size: 11px;
font-weight: 650;
}
.range-label output {
color: var(--orange-dark);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--orange);
}
.swatches {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
}
.swatch {
width: 24px;
height: 24px;
padding: 0;
border: 2px solid transparent;
border-radius: 50%;
box-shadow: inset 0 0 0 1px rgba(0,0,0,.12);
}
.swatch.active {
border-color: var(--ink);
box-shadow: 0 0 0 2px white, 0 0 0 3px var(--ink);
}
.switch-row {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 32px;
font-size: 11px;
font-weight: 650;
}
.switch {
position: relative;
width: 36px;
height: 20px;
}
.switch input {
position: absolute;
opacity: 0;
}
.switch span {
position: absolute;
inset: 0;
border-radius: 999px;
background: #cdd1cf;
transition: .18s;
}
.switch span::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 14px;
height: 14px;
border-radius: 50%;
background: white;
box-shadow: 0 1px 4px rgba(0,0,0,.22);
transition: .18s;
}
.switch input:checked + span {
background: var(--teal);
}
.switch input:checked + span::after {
transform: translateX(16px);
}
.palette {
display: grid;
gap: 8px;
}
.palette-item {
position: relative;
display: grid;
grid-template-columns: 42px 1fr 28px;
align-items: center;
gap: 10px;
min-height: 58px;
padding: 8px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,.58);
cursor: grab;
user-select: none;
transition: transform .15s, border-color .15s, background .15s;
}
.palette-item:hover {
z-index: 1;
border-color: rgba(201,112,61,.45);
background: white;
transform: translateX(3px);
}
.palette-item:active { cursor: grabbing; }
.mini-icon {
display: grid;
place-items: center;
width: 42px;
height: 42px;
border-radius: 10px;
color: white;
background: var(--ink);
font-size: 20px;
font-weight: 800;
}
.mini-icon.module { background: #345d5a; }
.mini-icon.task { background: #b65f38; }
.palette-item strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
}
.palette-item small {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.add-btn {
display: grid;
place-items: center;
width: 26px;
height: 26px;
border-radius: 8px;
color: white;
background: var(--orange);
font-size: 18px;
line-height: 1;
}
.add-btn:hover { background: var(--orange-dark); }
.selection {
min-height: 92px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,.52);
}
.selection.empty {
display: grid;
place-items: center;
color: var(--muted);
text-align: center;
font-size: 11px;
line-height: 1.45;
}
.selection strong {
display: block;
margin-bottom: 5px;
font-size: 12px;
}
.selection p {
margin: 0 0 10px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.selection-actions {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.small-btn {
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--ink);
background: white;
font-size: 10px;
font-weight: 700;
}
.small-btn:hover { border-color: var(--orange); }
.small-btn.danger {
color: #a23d3d;
background: #fff3f1;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.primary-btn, .secondary-btn {
min-height: 38px;
border-radius: 10px;
font-size: 11px;
font-weight: 800;
}
.primary-btn {
color: white;
background: var(--ink);
}
.secondary-btn {
border: 1px solid var(--line);
color: var(--ink);
background: rgba(255,255,255,.7);
}
.scene-hud {
position: fixed;
z-index: 5;
top: 18px;
right: 18px;
display: flex;
align-items: center;
gap: 12px;
padding: 10px 13px;
border: 1px solid rgba(255,255,255,.75);
border-radius: 14px;
background: rgba(250,248,243,.82);
box-shadow: 0 10px 30px rgba(25,37,41,.12);
backdrop-filter: blur(14px);
}
.health {
display: flex;
align-items: center;
gap: 7px;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: .06em;
}
.health i {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(71,168,121,.15);
}
.health.warn i {
background: var(--red);
box-shadow: 0 0 0 4px rgba(217,87,87,.15);
}
.hint {
padding-left: 12px;
border-left: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
}
.legend {
position: fixed;
z-index: 5;
right: 18px;
bottom: 18px;
display: flex;
gap: 12px;
padding: 10px 13px;
border: 1px solid rgba(255,255,255,.75);
border-radius: 14px;
background: rgba(250,248,243,.84);
box-shadow: 0 10px 30px rgba(25,37,41,.1);
backdrop-filter: blur(14px);
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.legend i {
width: 9px;
height: 9px;
border-radius: 3px;
background: var(--green);
}
.legend .bend { background: var(--red); }
.legend .sit { background: var(--yellow); }
.legend .reach { background: #60a6aa; }
.toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 24px;
max-width: min(440px, calc(100vw - 40px));
padding: 11px 15px;
border-radius: 11px;
color: white;
background: #172127;
box-shadow: 0 12px 30px rgba(0,0,0,.22);
font-size: 11px;
font-weight: 650;
opacity: 0;
transform: translate(-50%, 15px);
pointer-events: none;
transition: .22s;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.error { background: #9d4040; }
.toast.success { background: #26715f; }
@media (max-width: 780px) {
.sidebar {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 47vh;
border-radius: 18px;
}
.brand { margin-bottom: 10px; }
.intro { display: none; }
.scene-hud { top: 10px; right: 10px; left: 10px; }
.hint { display: none; }
.legend { display: none; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<aside class="sidebar">
<header class="brand">
<div style="display:flex;align-items:center;gap:11px">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i>
</div>
<div>
<p class="eyebrow">Voxel Workwear</p>
<h1>Apron Studio</h1>
</div>
</div>
<span class="version">3D / 01</span>
</header>
<p class="intro">
Drag modules onto the apron, then drop tools into pockets. Clearances and
reach are checked in real time.
</p>
<section class="section">
<div class="section-title">
<h2>Apron setup</h2>
<span>Fabric + fit</span>
</div>
<div class="range-row">
<label class="range-label" for="widthRange">
<span>Apron width</span>
<output id="widthOutput">112 cm</output>
</label>
<input id="widthRange" type="range" min="92" max="132" value="112" />
</div>
<div class="range-row">
<label class="range-label" for="heightRange">
<span>Apron length</span>
<output id="heightOutput">94 cm</output>
</label>
<input id="heightRange" type="range" min="72" max="116" value="94" />
</div>
<div class="swatches" aria-label="Apron color">
<button class="swatch active" data-color="#b96f42" style="background:#b96f42" aria-label="Terracotta"></button>
<button class="swatch" data-color="#425d61" style="background:#425d61" aria-label="Slate teal"></button>
<button class="swatch" data-color="#6d7652" style="background:#6d7652" aria-label="Olive"></button>
<button class="swatch" data-color="#34383d" style="background:#34383d" aria-label="Charcoal"></button>
<button class="swatch" data-color="#d5b573" style="background:#d5b573" aria-label="Sand"></button>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Safety overlays</h2>
<span>Live validation</span>
</div>
<label class="switch-row">
Bending clearance
<span class="switch">
<input id="zonesToggle" type="checkbox" checked />
<span></span>
</span>
</label>
<label class="switch-row">
Reach envelope
<span class="switch">
<input id="reachToggle" type="checkbox" checked />
<span></span>
</span>
</label>
</section>
<section class="section">
<div class="section-title">
<h2>Pocket modules</h2>
<span>Drag onto apron</span>
</div>
<div class="palette">
<div class="palette-item" draggable="true" data-drag-kind="module" data-type="loop">
<div class="mini-icon module">▥</div>
<div>
<strong>Tool loop</strong>
<small>Compact · 1 tool</small>
</div>
<button class="add-btn" data-add-module="loop" aria-label="Add tool loop">+</button>
</div>
<div class="palette-item" draggable="true" data-drag-kind="module" data-type="pouch">
<div class="mini-icon module">▣</div>
<div>
<strong>Deep pouch</strong>
<small>Wide · 2 tools</small>
</div>
<button class="add-btn" data-add-module="pouch" aria-label="Add deep pouch">+</button>
</div>
<div class="palette-item" draggable="true" data-drag-kind="module" data-type="mesh">
<div class="mini-icon module">⌗</div>
<div>
<strong>Mesh sleeve</strong>
<small>Lightweight · 1 tool</small>
</div>
<button class="add-btn" data-add-module="mesh" aria-label="Add mesh sleeve">+</button>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Task objects</h2>
<span>Drop into a pocket</span>
</div>
<div class="palette">
<div class="palette-item" draggable="true" data-drag-kind="task" data-type="driver">
<div class="mini-icon task">╱</div>
<div><strong>Screwdriver</strong><small>Slender hand tool</small></div>
<button class="add-btn" data-add-task="driver" aria-label="Add screwdriver">+</button>
</div>
<div class="palette-item" draggable="true" data-drag-kind="task" data-type="pliers">
<div class="mini-icon task">⋈</div>
<div><strong>Pliers</strong><small>Two-hand tool</small></div>
<button class="add-btn" data-add-task="pliers" aria-label="Add pliers">+</button>
</div>
<div class="palette-item" draggable="true" data-drag-kind="task" data-type="wrench">
<div class="mini-icon task">⚒</div>
<div><strong>Wrench</strong><small>Adjustable tool</small></div>
<button class="add-btn" data-add-task="wrench" aria-label="Add wrench">+</button>
</div>
<div class="palette-item" draggable="true" data-drag-kind="task" data-type="brush">
<div class="mini-icon task">▰</div>
<div><strong>Wire brush</strong><small>Cleaning tool</small></div>
<button class="add-btn" data-add-task="brush" aria-label="Add wire brush">+</button>
</div>
<div class="palette-item" draggable="true" data-drag-kind="task" data-type="tape">
<div class="mini-icon task">◎</div>
<div><strong>Tape measure</strong><small>Compact accessory</small></div>
<button class="add-btn" data-add-task="tape" aria-label="Add tape measure">+</button>
</div>
<div class="palette-item" draggable="true" data-drag-kind="task" data-type="radio">
<div class="mini-icon task">▥</div>
<div><strong>Radio</strong><small>Rectangular device</small></div>
<button class="add-btn" data-add-task="radio" aria-label="Add radio">+</button>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Selection</h2>
<span>Click an object</span>
</div>
<div id="selectionDetails" class="selection empty">
Select a pocket or task to inspect it.
</div>
</section>
<div class="actions">
<button id="exampleButton" class="primary-btn">Load example</button>
<button id="resetButton" class="secondary-btn">Reset scene</button>
</div>
</aside>
<div class="scene-hud">
<div id="health" class="health"><i></i><span id="healthText">Layout ready</span></div>
<div class="hint">Drag to orbit · Shift-drag to pan · Scroll to zoom</div>
</div>
<div class="legend">
<span><i></i>Valid</span>
<span><i class="bend"></i>Bend zone</span>
<span><i class="sit"></i>Sit zone</span>
<span><i class="reach"></i>Reach</span>
</div>
<div id="toast" class="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const selectionDetails = document.getElementById("selectionDetails");
const health = document.getElementById("health");
const healthText = document.getElementById("healthText");
const toastElement = document.getElementById("toast");
const MODULE_DEFS = {
loop: {
label: "Tool loop",
w: 0.24,
h: 0.26,
capacity: 1,
color: "#d2914e"
},
pouch: {
label: "Deep pouch",
w: 0.28,
h: 0.28,
capacity: 2,
color: "#3f7772"
},
mesh: {
label: "Mesh sleeve",
w: 0.25,
h: 0.24,
capacity: 1,
color: "#687b72"
}
};
const TASK_DEFS = {
driver: { label: "Screwdriver", w: 0.065, h: 0.21, color: "#cf5b43" },
pliers: { label: "Pliers", w: 0.13, h: 0.19, color: "#d39738" },
wrench: { label: "Wrench", w: 0.10, h: 0.22, color: "#9ea7a8" },
brush: { label: "Wire brush", w: 0.10, h: 0.20, color: "#95633d" },
tape: { label: "Tape measure", w: 0.13, h: 0.11, color: "#e0b948" },
radio: { label: "Radio", w: 0.14, h: 0.18, color: "#3e4d58" }
};
const state = {
width: 1.12,
height: 0.94,
color: "#b96f42",
showZones: true,
showReach: true,
pockets: [],
tasks: [],
selected: null,
nextModule: 1,
nextTask: 1
};
const APRON_BOTTOM = 0.88;
const APRON_Z = 0.64;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#e8e4dc");
scene.fog = new THREE.Fog("#e8e4dc", 7, 16);
const camera = new THREE.PerspectiveCamera(42, 1, 0.05, 50);
const cameraTarget = new THREE.Vector3(0, 1.32, 0.24);
const spherical = new THREE.Spherical(4.45, 1.22, 0.31);
camera.position.setFromSpherical(spherical).add(cameraTarget);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.06;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight("#fff7e7", "#69777a", 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight("#fff1d7", 3.3);
keyLight.position.set(3.5, 6, 5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -4;
keyLight.shadow.camera.right = 4;
keyLight.shadow.camera.top = 5;
keyLight.shadow.camera.bottom = -2;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight("#a9d7da", 1.5);
rimLight.position.set(-4, 3, -2);
scene.add(rimLight);
const apronRoot = new THREE.Group();
apronRoot.position.set(0, APRON_BOTTOM + state.height / 2, APRON_Z);
scene.add(apronRoot);
const panelGroup = new THREE.Group();
const zonesGroup = new THREE.Group();
const guidesGroup = new THREE.Group();
const modulesGroup = new THREE.Group();
const tasksGroup = new THREE.Group();
apronRoot.add(panelGroup, guidesGroup, zonesGroup, modulesGroup, tasksGroup);
const fabricTexture = createFabricTexture();
fabricTexture.userData.persistent = true;
function createFabricTexture() {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#e8e4dd";
ctx.fillRect(0, 0, 128, 128);
for (let i = 0; i < 128; i += 4) {
ctx.strokeStyle = i % 8 === 0 ? "rgba(70,55,42,.055)" : "rgba(255,255,255,.24)";
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i + 32, 128);
ctx.stroke();
ctx.strokeStyle = "rgba(70,55,42,.035)";
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(128, i + 20);
ctx.stroke();
}
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(4, 4);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function disposeGroup(group) {
group.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material) ? object.material : [object.material];
for (const material of materials) {
if (material.map && !material.map.userData.persistent) material.map.dispose();
material.dispose();
}
}
});
group.clear();
}
function cylinderBetween(a, b, radius, material, radialSegments = 10) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(radius, radius, length, radialSegments);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
return mesh;
}
function createEnvironment() {
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({ color: "#d8d4cb", roughness: 0.96 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = 0;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(12, 24, "#b9b8b1", "#cac8c1");
grid.position.y = 0.006;
grid.material.transparent = true;
grid.material.opacity = 0.26;
scene.add(grid);
const mannequin = new THREE.Group();
scene.add(mannequin);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: "#45535a",
roughness: 0.82,
metalness: 0.03
});
const jointMaterial = new THREE.MeshStandardMaterial({
color: "#26353b",
roughness: 0.72
});
const torso = new THREE.Mesh(new THREE.BoxGeometry(0.72, 0.78, 0.33), bodyMaterial);
torso.position.set(0, 1.42, 0.22);
torso.castShadow = true;
torso.receiveShadow = true;
mannequin.add(torso);
const pelvis = new THREE.Mesh(new THREE.BoxGeometry(0.60, 0.28, 0.31), bodyMaterial);
pelvis.position.set(0, 0.91, 0.18);
pelvis.castShadow = true;
mannequin.add(pelvis);
const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.10, 0.11, 0.18, 12), jointMaterial);
neck.position.set(0, 1.90, 0.20);
neck.castShadow = true;
mannequin.add(neck);
const head = new THREE.Mesh(new THREE.SphereGeometry(0.19, 20, 16), bodyMaterial);
head.position.set(0, 2.11, 0.20);
head.castShadow = true;
mannequin.add(head);
const leftUpper = cylinderBetween(
new THREE.Vector3(-0.41, 1.69, 0.20),
new THREE.Vector3(-0.59, 1.19, 0.27),
0.085, bodyMaterial
);
const leftLower = cylinderBetween(
new THREE.Vector3(-0.59, 1.19, 0.27),
new THREE.Vector3(-0.67, 0.87, 0.32),
0.073, jointMaterial
);
const rightUpper = cylinderBetween(
new THREE.Vector3(0.41, 1.69, 0.20),
new THREE.Vector3(0.59, 1.19, 0.27),
0.085, bodyMaterial
);
const rightLower = cylinderBetween(
new THREE.Vector3(0.59, 1.19, 0.27),
new THREE.Vector3(0.67, 0.87, 0.32),
0.073, jointMaterial
);
mannequin.add(leftUpper, leftLower, rightUpper, rightLower);
const leftLeg = cylinderBetween(
new THREE.Vector3(-0.19, 0.83, 0.17),
new THREE.Vector3(-0.22, 0.13, 0.12),
0.10, bodyMaterial
);
const rightLeg = cylinderBetween(
new THREE.Vector3(0.19, 0.83, 0.17),
new THREE.Vector3(0.22, 0.13, 0.12),
0.10, bodyMaterial
);
mannequin.add(leftLeg, rightLeg);
const stoolMaterial = new THREE.MeshStandardMaterial({
color: "#8c745c",
roughness: 0.88
});
const stool = new THREE.Group();
stool.position.set(0.96, 0, -0.02);
const seat = new THREE.Mesh(new THREE.BoxGeometry(0.48, 0.08, 0.42), stoolMaterial);
seat.position.set(0, 0.68, 0.10);
seat.castShadow = true;
stool.add(seat);
for (const x of [-0.17, 0.17]) {
for (const z of [-0.12, 0.28]) {
const leg = cylinderBetween(
new THREE.Vector3(x, 0.03, z),
new THREE.Vector3(x * 0.82, 0.66, z),
0.025, stoolMaterial, 8
);
stool.add(leg);
}
}
scene.add(stool);
}
createEnvironment();
function panelPolygon(width = state.width, height = state.height) {
return [
[-width / 2, -height / 2],
[ width / 2, -height / 2],
[ width / 2, height * 0.18],
[ width * 0.42, height / 2],
[-width * 0.42, height / 2],
[-width / 2, height * 0.18]
];
}
function pointInPolygon(x, y, polygon = panelPolygon()) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const [xi, yi] = polygon[i];
const [xj, yj] = polygon[j];
const intersects = ((yi > y) !== (yj > y)) &&
(x < (xj - xi) * (y - yi) / ((yj - yi) || 1e-8) + xi);
if (intersects) inside = !inside;
}
return inside;
}
function rectangleCorners(x, y, w, h) {
return [
[x - w / 2, y - h / 2],
[x + w / 2, y - h / 2],
[x + w / 2, y + h / 2],
[x - w / 2, y + h / 2]
];
}
function rectanglesOverlap(a, b) {
return Math.abs(a.x - b.x) < (a.w + b.w) / 2 &&
Math.abs(a.y - b.y) < (a.h + b.h) / 2;
}
function pointInRectangle(x, y, rect) {
return Math.abs(x - rect.x) <= rect.w / 2 &&
Math.abs(y - rect.y) <= rect.h / 2;
}
function getZones() {
return [
{
id: "bend",
label: "BEND CLEARANCE",
x: 0,
y: state.height / 2 - 0.18,
w: Math.min(0.50, state.width * 0.48),
h: 0.26,
color: "#d95757"
},
{
id: "sit",
label: "SIT CLEARANCE",
x: 0,
y: -state.height / 2 + 0.23,
w: Math.min(0.60, state.width * 0.56),
h: 0.34,
color: "#e5b449"
}
];
}
function reachMetrics() {
return {
x: 0,
y: state.height / 2 - 0.04,
rx: state.width * 0.72,
ry: state.height * 0.95
};
}
function validateModule(type, x, y, ignoreId = null) {
const def = MODULE_DEFS[type];
if (!def) return { valid: false, reason: "Unknown module" };
const corners = rectangleCorners(x, y, def.w, def.h);
if (!corners.every(([cx, cy]) => pointInPolygon(cx, cy))) {
return { valid: false, reason: "Module extends beyond the apron" };
}
const rect = { x, y, w: def.w, h: def.h };
for (const zone of getZones()) {
if (rectanglesOverlap(rect, zone)) {
return { valid: false, reason: `Overlaps ${zone.id === "bend" ? "bending" : "sitting"} clearance` };
}
}
const reach = reachMetrics();
const outsideReach = corners.some(([cx, cy]) => {
const nx = (cx - reach.x) / reach.rx;
const ny = (cy - reach.y) / reach.ry;
return nx * nx + ny * ny > 1;
});
if (outsideReach) {
return { valid: false, reason: "Outside the comfortable reach envelope" };
}
for (const pocket of state.pockets) {
if (pocket.id === ignoreId) continue;
const other = {
x: pocket.x,
y: pocket.y,
w: MODULE_DEFS[pocket.type].w,
h: MODULE_DEFS[pocket.type].h
};
if (rectanglesOverlap(rect, other)) {
return { valid: false, reason: "Overlaps another pocket module" };
}
}
return { valid: true, reason: "Reachable and clear" };
}
function validateTask(type, pocketId, ignoreTaskId = null) {
const def = TASK_DEFS[type];
const pocket = state.pockets.find(item => item.id === pocketId);
if (!pocket) return { valid: false, reason: "Drop the tool into a pocket" };
const pocketDef = MODULE_DEFS[pocket.type];
const taskCount = state.tasks.filter(
task => task.pocketId === pocketId && task.id !== ignoreTaskId
).length;
if (taskCount >= pocketDef.capacity) {
return { valid: false, reason: "That pocket is already full" };
}
if (def.w > pocketDef.w - 0.025 || def.h > pocketDef.h - 0.025) {
return { valid: false, reason: "The tool is too large for this pocket" };
}
const taskRect = { x: pocket.x, y: pocket.y, w: def.w, h: def.h };
for (const zone of getZones()) {
if (rectanglesOverlap(taskRect, zone)) {
return { valid: false, reason: "Tool overlaps a clearance zone" };
}
}
return { valid: true, reason: "Task is reachable" };
}
function buildPanel() {
disposeGroup(panelGroup);
const shape = new THREE.Shape();
const polygon = panelPolygon();
shape.moveTo(polygon[0][0], polygon[0][1]);
for (let i = 1; i < polygon.length; i++) {
shape.lineTo(polygon[i][0], polygon[i][1]);
}
shape.closePath();
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: 0.04,
bevelEnabled: true,
bevelSegments: 2,
steps: 1,
bevelSize: 0.012,
bevelThickness: 0.012
});
const material = new THREE.MeshStandardMaterial({
color: state.color,
map: fabricTexture,
roughness: 0.94,
metalness: 0
});
const panel = new THREE.Mesh(geometry, material);
panel.castShadow = true;
panel.receiveShadow = true;
panelGroup.add(panel);
const outlinePoints = polygon.map(([x, y]) => new THREE.Vector3(x, y, 0.057));
outlinePoints.push(outlinePoints[0].clone());
const outline = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(outlinePoints),
new THREE.LineBasicMaterial({ color: "#704633", transparent: true, opacity: 0.55 })
);
panelGroup.add(outline);
const strapMaterial = new THREE.MeshStandardMaterial({
color: state.color,
roughness: 0.93
});
const leftStrap = cylinderBetween(
new THREE.Vector3(-state.width * 0.34, state.height * 0.43, 0.015),
new THREE.Vector3(-0.29, state.height * 0.70, -0.20),
0.026, strapMaterial, 8
);
const rightStrap = cylinderBetween(
new THREE.Vector3(state.width * 0.34, state.height * 0.43, 0.015),
new THREE.Vector3(0.29, state.height * 0.70, -0.20),
0.026, strapMaterial, 8
);
panelGroup.add(leftStrap, rightStrap);
const rivetMaterial = new THREE.MeshStandardMaterial({
color: "#d5b16b",
metalness: 0.65,
roughness: 0.32
});
for (const x of [-state.width * 0.34, state.width * 0.34]) {
const rivet = new THREE.Mesh(new THREE.SphereGeometry(0.026, 12, 8), rivetMaterial);
rivet.position.set(x, state.height * 0.42, 0.065);
panelGroup.add(rivet);
}
}
function makeLabelSprite(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 112;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255,255,255,.86)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = color;
ctx.fillRect(0, 0, 12, canvas.height);
ctx.fillStyle = "#253036";
ctx.font = "700 30px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2 + 5, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
opacity: 0.9
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.54, 0.118, 1);
sprite.renderOrder = 30;
return sprite;
}
function buildZones() {
disposeGroup(zonesGroup);
zonesGroup.visible = state.showZones;
if (!state.showZones) return;
for (const zone of getZones()) {
const fill = new THREE.Mesh(
new THREE.PlaneGeometry(zone.w, zone.h),
new THREE.MeshBasicMaterial({
color: zone.color,
transparent: true,
opacity: 0.18,
depthWrite: false,
depthTest: false,
side: THREE.DoubleSide
})
);
fill.position.set(zone.x, zone.y, 0.073);
fill.renderOrder = 12;
zonesGroup.add(fill);
const points = [
new THREE.Vector3(zone.x - zone.w / 2, zone.y - zone.h / 2, 0.079),
new THREE.Vector3(zone.x + zone.w / 2, zone.y - zone.h / 2, 0.079),
new THREE.Vector3(zone.x + zone.w / 2, zone.y + zone.h / 2, 0.079),
new THREE.Vector3(zone.x - zone.w / 2, zone.y + zone.h / 2, 0.079),
new THREE.Vector3(zone.x - zone.w / 2, zone.y - zone.h / 2, 0.079)
];
const border = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineDashedMaterial({
color: zone.color,
dashSize: 0.045,
gapSize: 0.026,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
border.computeLineDistances();
border.renderOrder = 13;
zonesGroup.add(border);
const label = makeLabelSprite(zone.label, zone.color);
label.position.set(zone.x, zone.y, 0.11);
zonesGroup.add(label);
}
}
function buildReachGuide() {
disposeGroup(guidesGroup);
guidesGroup.visible = state.showReach;
if (!state.showReach) return;
const reach = reachMetrics();
const fill = new THREE.Mesh(
new THREE.CircleGeometry(1, 64),
new THREE.MeshBasicMaterial({
color: "#58a4aa",
transparent: true,
opacity: 0.045,
depthWrite: false,
side: THREE.DoubleSide
})
);
fill.position.set(reach.x, reach.y, 0.057);
fill.scale.set(reach.rx, reach.ry, 1);
fill.renderOrder = 5;
guidesGroup.add(fill);
const points = [];
for (let i = 0; i <= 72; i++) {
const angle = i / 72 * Math.PI * 2;
points.push(new THREE.Vector3(
reach.x + Math.cos(angle) * reach.rx,
reach.y + Math.sin(angle) * reach.ry,
0.063
));
}
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineDashedMaterial({
color: "#4b969c",
dashSize: 0.055,
gapSize: 0.04,
transparent: true,
opacity: 0.68,
depthTest: false
})
);
line.computeLineDistances();
line.renderOrder = 6;
guidesGroup.add(line);
}
function buildModules() {
disposeGroup(modulesGroup);
for (const pocket of state.pockets) {
const def = MODULE_DEFS[pocket.type];
const group = new THREE.Group();
group.position.set(pocket.x, pocket.y, 0);
group.userData.pocketId = pocket.id;
const bodyMaterial = new THREE.MeshStandardMaterial({
color: def.color,
roughness: pocket.type === "mesh" ? 0.76 : 0.9,
metalness: 0.02
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(def.w, def.h, 0.075),
bodyMaterial
);
body.position.z = 0.071;
body.castShadow = true;
body.receiveShadow = true;
body.userData.role = "body";
body.userData.pocketId = pocket.id;
group.add(body);
const lipMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(def.color).multiplyScalar(0.76),
roughness: 0.82
});
const lip = new THREE.Mesh(
new THREE.BoxGeometry(def.w * 0.91, 0.035, 0.092),
lipMaterial
);
lip.position.set(0, def.h * 0.38, 0.093);
lip.castShadow = true;
lip.userData.pocketId = pocket.id;
group.add(lip);
if (pocket.type === "mesh") {
const gridPoints = [];
for (let x = -def.w * 0.36; x <= def.w * 0.36; x += 0.045) {
gridPoints.push(
new THREE.Vector3(x, -def.h * 0.36, 0.112),
new THREE.Vector3(x, def.h * 0.36, 0.112)
);
}
for (let y = -def.h * 0.34; y <= def.h * 0.34; y += 0.045) {
gridPoints.push(
new THREE.Vector3(-def.w * 0.36, y, 0.112),
new THREE.Vector3(def.w * 0.36, y, 0.112)
);
}
const grid = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(gridPoints),
new THREE.LineBasicMaterial({
color: "#d9ded3",
transparent: true,
opacity: 0.78
})
);
group.add(grid);
} else {
const stitchPoints = [
new THREE.Vector3(-def.w * 0.36, -def.h * 0.36, 0.112),
new THREE.Vector3(def.w * 0.36, -def.h * 0.36, 0.112)
];
const stitch = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(stitchPoints),
new THREE.LineDashedMaterial({
color: "#f5dfbd",
dashSize: 0.018,
gapSize: 0.012,
transparent: true,
opacity: 0.8
})
);
stitch.computeLineDistances();
group.add(stitch);
}
const selectionGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(def.w + 0.025, def.h + 0.025, 0.085)
);
const selection = new THREE.LineSegments(
selectionGeometry,
new THREE.LineBasicMaterial({ color: "#fff0a6", depthTest: false })
);
selection.position.z = 0.073;
selection.visible = false;
selection.renderOrder = 25;
selection.userData.role = "selection";
group.add(selection);
modulesGroup.add(group);
}
}
function createTaskModel(type) {
const def = TASK_DEFS[type];
const group = new THREE.Group();
const metal = new THREE.MeshStandardMaterial({
color: "#b8c0c0",
metalness: 0.72,
roughness: 0.3
});
const accent = new THREE.MeshStandardMaterial({
color: def.color,
roughness: 0.64,
metalness: 0.08
});
const dark = new THREE.MeshStandardMaterial({
color: "#30383c",
roughness: 0.66
});
const add = (geometry, material, x = 0, y = 0, z = 0) => {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
group.add(mesh);
return mesh;
};
if (type === "driver") {
add(new THREE.CylinderGeometry(0.025, 0.025, 0.085, 10), accent, 0, 0.045, 0);
add(new THREE.CylinderGeometry(0.008, 0.008, 0.12, 8), metal, 0, -0.055, 0);
add(new THREE.BoxGeometry(0.025, 0.018, 0.012), metal, 0, -0.12, 0);
} else if (type === "pliers") {
const left = add(new THREE.BoxGeometry(0.032, 0.12, 0.035), accent, -0.025, -0.028, 0);
left.rotation.z = -0.15;
const right = add(new THREE.BoxGeometry(0.032, 0.12, 0.035), accent, 0.025, -0.028, 0);
right.rotation.z = 0.15;
const jawLeft = add(new THREE.BoxGeometry(0.024, 0.09, 0.03), metal, -0.018, 0.065, 0);
jawLeft.rotation.z = -0.08;
const jawRight = add(new THREE.BoxGeometry(0.024, 0.09, 0.03), metal, 0.018, 0.065, 0);
jawRight.rotation.z = 0.08;
} else if (type === "wrench") {
add(new THREE.BoxGeometry(0.035, 0.16, 0.028), metal, 0, -0.015, 0);
add(new THREE.TorusGeometry(0.045, 0.011, 6, 16, Math.PI * 1.55), metal, 0, 0.084, 0);
add(new THREE.BoxGeometry(0.075, 0.018, 0.03), accent, 0, -0.098, 0);
} else if (type === "brush") {
add(new THREE.CylinderGeometry(0.018, 0.022, 0.13, 10), accent, 0, 0.025, 0);
add(new THREE.BoxGeometry(0.09, 0.065, 0.04), dark, 0, -0.065, 0);
for (let i = 0; i < 5; i++) {
add(
new THREE.BoxGeometry(0.008, 0.055, 0.006),
metal,
-0.032 + i * 0.016,
-0.108,
0.024
);
}
} else if (type === "tape") {
add(new THREE.BoxGeometry(0.13, 0.105, 0.055), accent, 0, 0, 0);
const reel = add(new THREE.CylinderGeometry(0.031, 0.031, 0.06, 16), dark, 0.015, 0, 0);
reel.rotation.x = Math.PI / 2;
} else if (type === "radio") {
add(new THREE.BoxGeometry(0.14, 0.18, 0.06), accent, 0, 0, 0);
add(new THREE.BoxGeometry(0.10, 0.045, 0.012), dark, 0, 0.025, 0.037);
for (let i = 0; i < 4; i++) {
add(new THREE.BoxGeometry(0.065, 0.008, 0.014), metal, 0, 0.052 - i * 0.017, 0.04);
}
const antenna = add(new THREE.CylinderGeometry(0.005, 0.005, 0.09, 7), dark, 0.048, 0.12, 0);
antenna.rotation.z = -0.22;
}
return group;
}
function buildTasks() {
disposeGroup(tasksGroup);
for (const task of state.tasks) {
const group = createTaskModel(task.type);
group.userData.taskId = task.id;
group.traverse(object => {
object.userData.taskId = task.id;
});
tasksGroup.add(group);
}
positionTasks();
}
function positionTasks() {
const occupied = new Map();
for (const task of state.tasks) {
const group = tasksGroup.children.find(
object => object.userData.taskId === task.id
);
if (!group) continue;
const pocket = state.pockets.find(item => item.id === task.pocketId);
if (!pocket) continue;
const index = occupied.get(pocket.id) || 0;
occupied.set(pocket.id, index + 1);
const pocketDef = MODULE_DEFS[pocket.type];
let offset = 0;
if (pocketDef.capacity > 1) {
offset = index === 0 ? -pocketDef.w * 0.21 : pocketDef.w * 0.21;
}
group.position.set(pocket.x + offset, pocket.y, 0.17);
group.scale.setScalar(
state.selected?.type === "task" && state.selected.id === task.id ? 1.08 : 1
);
}
}
function updateModuleColors(previewId = null, previewValid = false) {
for (const pocket of state.pockets) {
const group = modulesGroup.children.find(
object => object.userData.pocketId === pocket.id
);
if (!group) continue;
const body = group.children.find(object => object.userData.role === "body");
const selection = group.children.find(object => object.userData.role === "selection");
const base = MODULE_DEFS[pocket.type].color;
const invalid = !validateModule(pocket.type, pocket.x, pocket.y, pocket.id).valid;
body.material.color.set(base);
if (invalid) body.material.color.set("#d75c55");
if (previewId === pocket.id) {
body.material.color.set(previewValid ? "#49b77c" : "#df5656");
}
selection.visible = state.selected?.type === "pocket" &&
state.selected.id === pocket.id;
}
}
function rebuildAll() {
apronRoot.position.y = APRON_BOTTOM + state.height / 2;
buildPanel();
buildZones();
buildReachGuide();
buildModules();
buildTasks();
updateModuleColors();
updateUI();
}
function findModuleSpot(type) {
const candidates = [
[-state.width * 0.36, 0.09],
[ state.width * 0.36, 0.09],
[-state.width * 0.34, 0.09],
[ state.width * 0.34, 0.09],
[-state.width * 0.35, -0.12],
[ state.width * 0.35, -0.12],
[0, 0.09]
];
for (const [x, y] of candidates) {
if (validateModule(type, x, y).valid) return { x, y };
}
for (let y = state.height * 0.27; y > -state.height * 0.38; y -= 0.045) {
for (let x = -state.width * 0.38; x <= state.width * 0.38; x += 0.045) {
if (validateModule(type, x, y).valid) return { x, y };
}
}
return null;
}
function addModule(type, x, y) {
const validation = validateModule(type, x, y);
if (!validation.valid) {
showToast(validation.reason, "error");
return null;
}
const pocket = {
id: `m${state.nextModule++}`,
type,
x,
y
};
state.pockets.push(pocket);
state.selected = { type: "pocket", id: pocket.id };
buildModules();
buildTasks();
updateModuleColors();
updateUI();
showToast(`${MODULE_DEFS[type].label} added`, "success");
return pocket;
}
function addTask(type, pocketId) {
const validation = validateTask(type, pocketId);
if (!validation.valid) {
showToast(validation.reason, "error");
return null;
}
const task = {
id: `t${state.nextTask++}`,
type,
pocketId
};
state.tasks.push(task);
state.selected = { type: "task", id: task.id };
buildTasks();
updateUI();
showToast(`${TASK_DEFS[type].label} placed in pocket`, "success");
return task;
}
function findPocketAt(point) {
return state.pockets.find(pocket => {
const def = MODULE_DEFS[pocket.type];
return pointInRectangle(point.x, point.y, {
x: pocket.x,
y: pocket.y,
w: def.w,
h: def.h
});
});
}
function removeSelected() {
if (!state.selected) return;
if (state.selected.type === "pocket") {
const id = state.selected.id;
state.tasks = state.tasks.filter(task => task.pocketId !== id);
state.pockets = state.pockets.filter(pocket => pocket.id !== id);
showToast("Pocket module removed");
} else {
const id = state.selected.id;
state.tasks = state.tasks.filter(task => task.id !== id);
showToast("Task object removed");
}
state.selected = null;
buildModules();
buildTasks();
updateModuleColors();
updateUI();
}
function clearSelectedPocket() {
if (state.selected?.type !== "pocket") return;
const id = state.selected.id;
state.tasks = state.tasks.filter(task => task.pocketId !== id);
buildTasks();
updateUI();
showToast("Pocket emptied");
}
function selectEntity(type, id) {
state.selected = { type, id };
updateModuleColors();
positionTasks();
updateUI();
}
function updateUI() {
document.getElementById("widthOutput").textContent = `${Math.round(state.width * 100)} cm`;
document.getElementById("heightOutput").textContent = `${Math.round(state.height * 100)} cm`;
const invalid = state.pockets.filter(
pocket => !validateModule(pocket.type, pocket.x, pocket.y, pocket.id).valid
).length;
health.classList.toggle("warn", invalid > 0);
healthText.textContent = invalid > 0
? `${invalid} placement${invalid === 1 ? "" : "s"} need review`
: "Layout ready";
if (!state.selected) {
selectionDetails.className = "selection empty";
selectionDetails.textContent = "Select a pocket or task to inspect it.";
return;
}
selectionDetails.className = "selection";
if (state.selected.type === "pocket") {
const pocket = state.pockets.find(item => item.id === state.selected.id);
if (!pocket) {
state.selected = null;
updateUI();
return;
}
const def = MODULE_DEFS[pocket.type];
const tasks = state.tasks.filter(task => task.pocketId === pocket.id);
const validation = validateModule(pocket.type, pocket.x, pocket.y, pocket.id);
selectionDetails.innerHTML = `
<strong>${def.label}</strong>
<p>
${tasks.length}/${def.capacity} tools · ${Math.round(def.w * 100)} × ${Math.round(def.h * 100)} cm<br>
${validation.valid ? "Clear of safety zones and within reach." : validation.reason}
</p>
<div class="selection-actions">
<button class="small-btn" id="emptyPocket">Empty pocket</button>
<button class="small-btn danger" id="removePocket">Remove module</button>
</div>
`;
document.getElementById("emptyPocket").onclick = clearSelectedPocket;
document.getElementById("removePocket").onclick = removeSelected;
} else {
const task = state.tasks.find(item => item.id === state.selected.id);
if (!task) {
state.selected = null;
updateUI();
return;
}
const def = TASK_DEFS[task.type];
const pocket = state.pockets.find(item => item.id === task.pocketId);
selectionDetails.innerHTML = `
<strong>${def.label}</strong>
<p>
Stored in ${MODULE_DEFS[pocket.type].label}<br>
Drag it directly to another compatible pocket.
</p>
<div class="selection-actions">
<button class="small-btn danger" id="removeTask">Remove task</button>
</div>
`;
document.getElementById("removeTask").onclick = removeSelected;
}
}
let toastTimer;
function showToast(message, type = "info") {
toastElement.textContent = message;
toastElement.className = `toast show ${type}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toastElement.className = "toast";
}, 2400);
}
document.querySelectorAll(".swatch").forEach(button => {
button.addEventListener("click", () => {
state.color = button.dataset.color;
document.querySelectorAll(".swatch").forEach(item => item.classList.remove("active"));
button.classList.add("active");
buildPanel();
});
});
document.getElementById("widthRange").addEventListener("input", event => {
const oldWidth = state.width;
state.width = Number(event.target.value) / 100;
for (const pocket of state.pockets) pocket.x *= state.width / oldWidth;
rebuildAll();
});
document.getElementById("heightRange").addEventListener("input", event => {
const oldHeight = state.height;
state.height = Number(event.target.value) / 100;
for (const pocket of state.pockets) pocket.y *= state.height / oldHeight;
rebuildAll();
});
document.getElementById("zonesToggle").addEventListener("change", event => {
state.showZones = event.target.checked;
buildZones();
});
document.getElementById("reachToggle").addEventListener("change", event => {
state.showReach = event.target.checked;
buildReachGuide();
});
document.querySelectorAll("[data-add-module]").forEach(button => {
button.addEventListener("click", event => {
event.stopPropagation();
const type = button.dataset.addModule;
const spot = findModuleSpot(type);
if (!spot) {
showToast("No clear reachable location is available", "error");
return;
}
addModule(type, spot.x, spot.y);
});
});
document.querySelectorAll("[data-add-task]").forEach(button => {
button.addEventListener("click", event => {
event.stopPropagation();
const type = button.dataset.addTask;
let target = null;
if (state.selected?.type === "pocket") {
target = state.pockets.find(pocket => pocket.id === state.selected.id);
}
if (!target || !validateTask(type, target.id).valid) {
target = state.pockets.find(pocket => validateTask(type, pocket.id).valid);
}
if (!target) {
showToast("Add or select a compatible pocket first", "error");
return;
}
addTask(type, target.id);
});
});
document.getElementById("exampleButton").addEventListener("click", () => {
state.pockets = [];
state.tasks = [];
state.selected = null;
const left = { id: "m1", type: "loop", x: -state.width * 0.36, y: 0.09 };
const right = { id: "m2", type: "pouch", x: state.width * 0.36, y: 0.09 };
if (validateModule(left.type, left.x, left.y).valid) state.pockets.push(left);
if (validateModule(right.type, right.x, right.y).valid) state.pockets.push(right);
if (state.pockets[0]) {
state.tasks.push({ id: "t1", type: "driver", pocketId: state.pockets[0].id });
}
if (state.pockets[1]) {
state.tasks.push({ id: "t2", type: "tape", pocketId: state.pockets[1].id });
}
rebuildAll();
showToast("Example layout loaded", "success");
});
document.getElementById("resetButton").addEventListener("click", () => {
state.pockets = [];
state.tasks = [];
state.selected = null;
state.nextModule = 1;
state.nextTask = 1;
rebuildAll();
showToast("Scene reset");
});
// Raycasting and manual camera controls.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const apronPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -APRON_Z);
const canvas = renderer.domElement;
let cameraDrag = false;
let cameraMode = "orbit";
let lastPointer = { x: 0, y: 0 };
let moduleDrag = null;
let taskDrag = null;
let palettePayload = null;
let ghost = null;
function setRayFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function getApronPoint(event) {
setRayFromEvent(event);
const worldPoint = new THREE.Vector3();
if (!raycaster.ray.intersectPlane(apronPlane, worldPoint)) return null;
return apronRoot.worldToLocal(worldPoint.clone());
}
function findObjectId(object, key) {
let current = object;
while (current) {
if (current.userData[key]) return current.userData[key];
current = current.parent;
}
return null;
}
function updateCamera() {
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
function panCamera(dx, dy) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const distance = camera.position.distanceTo(cameraTarget);
cameraTarget.addScaledVector(right, -dx * distance * 0.0012);
cameraTarget.addScaledVector(up, dy * distance * 0.0012);
cameraTarget.y = THREE.MathUtils.clamp(cameraTarget.y, 0.55, 2.5);
}
canvas.addEventListener("pointerdown", event => {
canvas.focus();
canvas.setPointerCapture(event.pointerId);
const taskHit = raycaster.intersectObjects(tasksGroup.children, true)[0];
if (taskHit && event.button === 0) {
const taskId = findObjectId(taskHit.object, "taskId");
const task = state.tasks.find(item => item.id === taskId);
if (task) {
selectEntity("task", task.id);
taskDrag = {
id: task.id,
originalPocketId: task.pocketId,
targetId: null,
valid: false
};
return;
}
}
const pocketHit = raycaster.intersectObjects(modulesGroup.children, true)[0];
if (pocketHit && event.button === 0) {
const pocketId = findObjectId(pocketHit.object, "pocketId");
const pocket = state.pockets.find(item => item.id === pocketId);
if (pocket) {
selectEntity("pocket", pocket.id);
const point = getApronPoint(event);
const group = modulesGroup.children.find(item => item.userData.pocketId === pocket.id);
moduleDrag = {
id: pocket.id,
originalX: pocket.x,
originalY: pocket.y,
offsetX: point ? point.x - pocket.x : 0,
offsetY: point ? point.y - pocket.y : 0,
valid: true,
reason: ""
};
return;
}
}
cameraDrag = true;
cameraMode = event.shiftKey || event.button === 2 ? "pan" : "orbit";
lastPointer = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener("pointermove", event => {
if (moduleDrag) {
const point = getApronPoint(event);
if (!point) return;
const pocket = state.pockets.find(item => item.id === moduleDrag.id);
const group = modulesGroup.children.find(item => item.userData.pocketId === moduleDrag.id);
if (!pocket || !group) return;
pocket.x = point.x - moduleDrag.offsetX;
pocket.y = point.y - moduleDrag.offsetY;
const validation = validateModule(pocket.type, pocket.x, pocket.y, pocket.id);
moduleDrag.valid = validation.valid;
moduleDrag.reason = validation.reason;
group.position.set(pocket.x, pocket.y, 0);
updateModuleColors(pocket.id, validation.valid);
positionTasks();
return;
}
if (taskDrag) {
const point = getApronPoint(event);
if (!point) return;
const target = findPocketAt(point);
taskDrag.targetId = target?.id || null;
if (target) {
const validation = validateTask(
state.tasks.find(task => task.id === taskDrag.id).type,
target.id,
taskDrag.id
);
taskDrag.valid = validation.valid;
taskDrag.reason = validation.reason;
updateModuleColors(target.id, validation.valid);
} else {
taskDrag.valid = false;
taskDrag.reason = "Drop the tool into a pocket";
updateModuleColors();
}
const group = tasksGroup.children.find(item => item.userData.taskId === taskDrag.id);
if (group) group.position.set(point.x, point.y, 0.22);
return;
}
if (cameraDrag) {
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
lastPointer = { x: event.clientX, y: event.clientY };
if (cameraMode === "pan") {
panCamera(dx, dy);
} else {
spherical.theta -= dx * 0.006;
spherical.phi = THREE.MathUtils.clamp(spherical.phi - dy * 0.005, 0.35, 1.48);
}
updateCamera();
}
});
function finishPointerInteraction(event) {
if (moduleDrag) {
const pocket = state.pockets.find(item => item.id === moduleDrag.id);
if (pocket && !moduleDrag.valid) {
pocket.x = moduleDrag.originalX;
pocket.y = moduleDrag.originalY;
showToast(moduleDrag.reason, "error");
}
moduleDrag = null;
updateModuleColors();
positionTasks();
updateUI();
}
if (taskDrag) {
const task = state.tasks.find(item => item.id === taskDrag.id);
if (task) {
if (taskDrag.targetId && taskDrag.valid) {
task.pocketId = taskDrag.targetId;
} else {
showToast(taskDrag.reason || "Invalid task placement", "error");
}
}
taskDrag = null;
updateModuleColors();
positionTasks();
updateUI();
}
cameraDrag = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
}
canvas.addEventListener("pointerup", finishPointerInteraction);
canvas.addEventListener("pointercancel", finishPointerInteraction);
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
spherical.radius = THREE.MathUtils.clamp(
spherical.radius * Math.exp(event.deltaY * 0.001),
2.6,
7.2
);
updateCamera();
}, { passive: false });
window.addEventListener("keydown", event => {
if (event.key === "Delete" || event.key === "Backspace") {
if (document.activeElement === canvas) {
event.preventDefault();
removeSelected();
}
}
if (event.key === "Escape") {
state.selected = null;
updateModuleColors();
positionTasks();
updateUI();
}
});
// HTML palette drag-and-drop.
function createGhost(kind, type) {
removeGhost();
const def = kind === "module" ? MODULE_DEFS[type] : TASK_DEFS[type];
const geometry = new THREE.BoxGeometry(
kind === "module" ? def.w : def.w * 0.75,
kind === "module" ? def.h : def.h * 0.75,
0.035
);
const material = new THREE.MeshBasicMaterial({
color: "#55b98a",
transparent: true,
opacity: 0.28,
depthTest: false
});
ghost = new THREE.Mesh(geometry, material);
ghost.position.z = 0.22;
ghost.renderOrder = 40;
apronRoot.add(ghost);
}
function removeGhost() {
if (!ghost) return;
apronRoot.remove(ghost);
ghost.geometry.dispose();
ghost.material.dispose();
ghost = null;
}
document.querySelectorAll("[data-drag-kind]").forEach(card => {
card.addEventListener("dragstart", event => {
palettePayload = {
kind: card.dataset.dragKind,
type: card.dataset.type
};
event.dataTransfer.effectAllowed = "copy";
event.dataTransfer.setData("text/plain", JSON.stringify(palettePayload));
createGhost(palettePayload.kind, palettePayload.type);
});
card.addEventListener("dragend", () => {
palettePayload = null;
removeGhost();
updateModuleColors();
});
});
canvas.addEventListener("dragover", event => {
event.preventDefault();
if (!palettePayload) return;
event.dataTransfer.dropEffect = "copy";
const point = getApronPoint(event);
if (!point) return;
if (palettePayload.kind === "module") {
const validation = validateModule(palettePayload.type, point.x, point.y);
ghost.position.set(point.x, point.y, 0.22);
ghost.material.color.set(validation.valid ? "#49b77c" : "#df5656");
} else {
const target = findPocketAt(point);
if (target) {
const validation = validateTask(palettePayload.type, target.id);
ghost.position.set(target.x, target.y, 0.23);
ghost.material.color.set(validation.valid ? "#49b77c" : "#df5656");
updateModuleColors(target.id, validation.valid);
} else {
ghost.position.set(point.x, point.y, 0.23);
ghost.material.color.set("#df5656");
updateModuleColors();
}
}
});
canvas.addEventListener("drop", event => {
event.preventDefault();
if (!palettePayload) return;
const point = getApronPoint(event);
if (!point) return;
if (palettePayload.kind === "module") {
addModule(palettePayload.type, point.x, point.y);
} else {
const target = findPocketAt(point);
if (!target) {
showToast("Drop the task into a pocket module", "error");
} else {
addTask(palettePayload.type, target.id);
}
}
palettePayload = null;
removeGhost();
updateModuleColors();
});
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
rebuildAll();
updateCamera();
renderer.setAnimationLoop(() => renderer.render(scene, camera));
</script>
</body>
</html>
```