Prompt specification
Build or customize the Three.js 3D scene "Homework workstation arrangement" 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: Homework workstation arrangement
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/homework-workstation-arrangement-x0187
Scene Description Prompt:
Use Three.js from cdnjs to compose a desk with lamp, books, screen, and storage; users relocate frequently used objects and observe a simple arm rig reach them without crossing obstacles. Deliver one self-contained HTML file with stylized solid shapes.
Working Three.js Starter (homework-workstation-arrangement-x0187):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Desk Motion Lab</title>
<style>
:root {
--ink: #17282b;
--muted: #627174;
--paper: #f7f4ed;
--glass: rgba(248, 246, 239, 0.86);
--line: rgba(23, 40, 43, 0.13);
--teal: #0d8c87;
--coral: #e76f51;
--gold: #e9b949;
--red: #d84f45;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e6de;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button { font: inherit; }
#viewport, #labels {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#labels {
pointer-events: none;
overflow: hidden;
z-index: 2;
}
.object-label {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -50%);
padding: 5px 9px;
border: 1px solid rgba(255,255,255,.55);
border-radius: 999px;
background: rgba(247,244,237,.82);
box-shadow: 0 5px 18px rgba(23,40,43,.10);
color: var(--ink);
font-size: 9px;
font-weight: 800;
letter-spacing: .13em;
white-space: nowrap;
backdrop-filter: blur(8px);
transition: opacity .15s ease;
}
.object-label.draggable {
cursor: grab;
pointer-events: auto;
}
.object-label::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 6px;
border-radius: 50%;
background: var(--teal);
vertical-align: 1px;
}
.object-label.static::before { background: var(--muted); }
.ui {
position: fixed;
inset: 0;
z-index: 4;
pointer-events: none;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
border-radius: 13px;
background: var(--ink);
box-shadow: 0 10px 24px rgba(23,40,43,.18);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
border-radius: 4px;
background: var(--paper);
transform: rotate(-31deg);
}
.brand-mark::before {
width: 7px;
height: 25px;
left: 12px;
top: 10px;
}
.brand-mark::after {
width: 18px;
height: 7px;
left: 18px;
top: 9px;
}
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1;
font-weight: 850;
letter-spacing: .16em;
}
.brand p {
margin: 7px 0 0;
color: var(--muted);
font-size: 11px;
font-weight: 600;
letter-spacing: .04em;
}
.glass {
border: 1px solid rgba(255,255,255,.65);
background: var(--glass);
box-shadow: 0 16px 44px rgba(23,40,43,.10);
backdrop-filter: blur(14px) saturate(1.1);
}
.status-card {
width: 258px;
padding: 15px 17px;
border-radius: 16px;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
}
.status-label {
display: flex;
align-items: center;
gap: 8px;
font-size: 10px;
font-weight: 850;
letter-spacing: .13em;
text-transform: uppercase;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 5px rgba(13,140,135,.11);
animation: breathe 2s infinite;
}
@keyframes breathe {
50% { box-shadow: 0 0 0 8px rgba(13,140,135,0); }
}
#stateText {
color: var(--teal);
font-size: 10px;
font-weight: 850;
letter-spacing: .1em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 14px;
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: .1em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 13px;
font-weight: 800;
}
.progress {
height: 4px;
margin-top: 14px;
overflow: hidden;
border-radius: 999px;
background: rgba(23,40,43,.09);
}
#progressFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--teal), #55c8bd);
transition: width .08s linear;
}
.bottom-left {
position: absolute;
left: 24px;
bottom: 24px;
width: 330px;
max-width: calc(100vw - 48px);
padding: 17px 18px;
border-radius: 18px;
}
.eyebrow {
color: var(--teal);
font-size: 9px;
font-weight: 850;
letter-spacing: .16em;
text-transform: uppercase;
}
.bottom-left h2 {
margin: 7px 0 7px;
font-size: 18px;
line-height: 1.2;
letter-spacing: -.02em;
}
.bottom-left p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 13px;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.legend div {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.swatch {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--teal);
}
.swatch.gold { background: var(--gold); }
.swatch.coral { background: var(--coral); }
.actions {
position: absolute;
right: 24px;
bottom: 24px;
display: flex;
gap: 8px;
pointer-events: auto;
}
.action {
min-height: 42px;
padding: 0 16px;
border: 1px solid rgba(255,255,255,.7);
border-radius: 13px;
background: rgba(247,244,237,.88);
box-shadow: 0 10px 30px rgba(23,40,43,.10);
color: var(--ink);
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: .07em;
text-transform: uppercase;
backdrop-filter: blur(10px);
transition: transform .15s ease, background .15s ease;
}
.action:hover {
transform: translateY(-2px);
background: #fffdf8;
}
.action.primary {
background: var(--ink);
color: white;
}
.camera-hint {
position: absolute;
left: 50%;
bottom: 26px;
transform: translateX(-50%);
color: rgba(23,40,43,.62);
font-size: 10px;
font-weight: 650;
letter-spacing: .04em;
white-space: nowrap;
}
.camera-hint kbd {
padding: 3px 6px;
border: 1px solid rgba(23,40,43,.18);
border-radius: 5px;
background: rgba(255,255,255,.42);
font-family: inherit;
font-size: 9px;
font-weight: 800;
}
#loading {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
background: #ece9e1;
transition: opacity .35s ease, visibility .35s ease;
}
#loading.hidden {
opacity: 0;
visibility: hidden;
}
.loader {
display: flex;
align-items: center;
gap: 12px;
color: var(--muted);
font-size: 11px;
font-weight: 750;
letter-spacing: .12em;
text-transform: uppercase;
}
.loader i {
width: 16px;
height: 16px;
border: 2px solid rgba(13,140,135,.2);
border-top-color: var(--teal);
border-radius: 50%;
animation: spin .7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (max-width: 760px) {
.topbar { top: 14px; left: 14px; right: 14px; }
.brand p { display: none; }
.status-card { width: 190px; padding: 12px; }
.metrics { margin-top: 10px; }
.bottom-left { left: 14px; bottom: 68px; width: 280px; }
.bottom-left h2 { font-size: 15px; }
.bottom-left p { font-size: 10px; }
.legend { display: none; }
.actions { right: 14px; bottom: 14px; }
.camera-hint { display: none; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="labels"></div>
<div class="ui">
<div class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>DESK / MOTION LAB</h1>
<p>Relocate an object. Watch the arm find a clear route.</p>
</div>
</div>
<div class="status-card glass">
<div class="status-row">
<div class="status-label"><i class="status-dot"></i> Arm system</div>
<div id="stateText">Ready</div>
</div>
<div class="metrics">
<div class="metric">
<span>Target</span>
<strong id="targetText">Books</strong>
</div>
<div class="metric">
<span>Route</span>
<strong id="routeText">Direct</strong>
</div>
</div>
<div class="progress"><div id="progressFill"></div></div>
</div>
</div>
<div class="bottom-left glass">
<div class="eyebrow">Interaction</div>
<h2>Move what you use most.</h2>
<p>
Drag the lamp, books, mug, or phone. On release, the two-link arm plans
a collision-free path around the screen and storage.
</p>
<div class="legend">
<div><i class="swatch"></i> Draggable</div>
<div><i class="swatch gold"></i> Fixed obstacle</div>
<div><i class="swatch coral"></i> Reach path</div>
</div>
</div>
<div class="camera-hint">
<kbd>Drag item</kbd> move <kbd>Right drag</kbd> orbit
<kbd>Wheel</kbd> zoom <kbd>R</kbd> reset
</div>
<div class="actions">
<button class="action" id="resetButton">Reset layout</button>
<button class="action primary" id="sweepButton">Auto sweep</button>
</div>
</div>
<div id="loading">
<div class="loader"><i></i> Building the workspace</div>
</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 labelLayer = document.getElementById("labels");
const stateText = document.getElementById("stateText");
const targetText = document.getElementById("targetText");
const routeText = document.getElementById("routeText");
const progressFill = document.getElementById("progressFill");
const resetButton = document.getElementById("resetButton");
const sweepButton = document.getElementById("sweepButton");
const DESK_Y = 1.66;
const SHOULDER = new THREE.Vector3(0, DESK_Y + 0.58, -2.48);
const L1 = 3.70;
const L2 = 3.70;
const MAX_REACH = L1 + L2;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e6de);
scene.fog = new THREE.Fog(0xe9e6de, 18, 31);
const camera = new THREE.PerspectiveCamera(36, 1, 0.1, 80);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const orbit = {
yaw: 0.62,
pitch: 0.63,
radius: 15.2,
target: new THREE.Vector3(0, 1.05, 0)
};
function updateCamera() {
const c = Math.cos(orbit.pitch);
camera.position.set(
orbit.target.x + orbit.radius * Math.sin(orbit.yaw) * c,
orbit.target.y + orbit.radius * Math.sin(orbit.pitch),
orbit.target.z + orbit.radius * Math.cos(orbit.yaw) * c
);
camera.lookAt(orbit.target);
}
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", resize);
updateCamera();
const hemi = new THREE.HemisphereLight(0xfff8eb, 0x718083, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1d5, 3.3);
sun.position.set(-5, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -9;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 25;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rim = new THREE.DirectionalLight(0xbde6e4, 1.4);
rim.position.set(7, 5, -7);
scene.add(rim);
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.02,
flatShading: true,
...options
});
const mat = {
desk: material(0xc9a878),
deskEdge: material(0xa98259),
dark: material(0x243437),
cream: material(0xf4eddb),
white: material(0xfbf8ef),
teal: material(0x188f8b),
tealDark: material(0x116662),
coral: material(0xe76f51),
gold: material(0xe7b84f),
blue: material(0x466c82),
green: material(0x6f9075),
screen: material(0x16343a, { emissive: 0x0a2226, emissiveIntensity: 0.8 }),
screenGlow: material(0x67c8c0, { emissive: 0x2a7772, emissiveIntensity: 0.7 }),
black: material(0x11191b, { roughness: 0.5 }),
floor: material(0xd8d4ca),
rug: material(0xc8beb0),
mat: material(0x9caea5)
};
function mesh(geometry, m, parent = scene) {
const result = new THREE.Mesh(geometry, m);
result.castShadow = true;
result.receiveShadow = true;
parent.add(result);
return result;
}
function box(w, h, d, m, x = 0, y = 0, z = 0, parent = scene) {
const result = mesh(new THREE.BoxGeometry(w, h, d), m, parent);
result.position.set(x, y, z);
return result;
}
function cylinder(rt, rb, h, m, x = 0, y = 0, z = 0, parent = scene, segments = 24) {
const result = mesh(new THREE.CylinderGeometry(rt, rb, h, segments), m, parent);
result.position.set(x, y, z);
return result;
}
// Room and desk.
const floor = mesh(new THREE.PlaneGeometry(60, 60), mat.floor);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.025;
floor.castShadow = false;
const rug = mesh(new THREE.CircleGeometry(8.6, 64), mat.rug);
rug.rotation.x = -Math.PI / 2;
rug.position.set(0, -0.012, 0);
rug.castShadow = false;
box(10.2, 0.32, 6.2, mat.desk, 0, DESK_Y - 0.16, 0);
box(10.28, 0.13, 6.28, mat.deskEdge, 0, DESK_Y - 0.34, 0);
for (const x of [-4.35, 4.35]) {
for (const z of [-2.35, 2.35]) {
box(0.28, 1.42, 0.28, mat.dark, x, 0.69, z);
}
}
box(8.8, 0.15, 0.18, mat.dark, 0, 0.30, -2.35);
box(8.8, 0.15, 0.18, mat.dark, 0, 0.30, 2.35);
// Desk mat.
box(5.05, 0.018, 3.15, mat.mat, 0.55, DESK_Y + 0.009, 0.62);
// Monitor: fixed obstacle.
const screenRoot = new THREE.Group();
screenRoot.position.set(2.35, DESK_Y, -1.75);
scene.add(screenRoot);
box(0.78, 0.075, 0.42, mat.dark, 0, 0.04, 0, screenRoot);
box(0.11, 0.52, 0.11, mat.dark, 0, 0.31, 0, screenRoot);
box(2.15, 1.27, 0.13, mat.dark, 0, 1.11, 0, screenRoot);
box(1.98, 1.08, 0.026, mat.screen, 0, 1.11, 0.079, screenRoot);
box(0.72, 0.075, 0.014, mat.screenGlow, -0.40, 1.43, 0.098, screenRoot);
box(0.38, 0.065, 0.014, mat.cream, -0.57, 1.27, 0.099, screenRoot);
box(0.48, 0.065, 0.014, mat.cream, -0.52, 1.11, 0.099, screenRoot);
box(0.27, 0.065, 0.014, mat.gold, 0.56, 0.88, 0.099, screenRoot);
box(0.46, 0.065, 0.014, mat.teal, 0.47, 0.72, 0.099, screenRoot);
box(0.59, 0.065, 0.014, mat.coral, 0.40, 0.56, 0.099, screenRoot);
// Storage unit: fixed obstacle.
const storageRoot = new THREE.Group();
storageRoot.position.set(-2.70, DESK_Y, -1.75);
scene.add(storageRoot);
box(1.45, 1.08, 1.10, mat.cream, 0, 0.54, 0, storageRoot);
box(1.49, 0.09, 1.14, mat.tealDark, 0, 1.10, 0, storageRoot);
for (let i = 0; i < 3; i++) {
const y = 0.22 + i * 0.31;
box(1.29, 0.255, 0.045, i === 1 ? mat.teal : mat.white, 0, y, 0.565, storageRoot);
box(0.40, 0.035, 0.055, mat.dark, 0, y + 0.02, 0.605, storageRoot);
}
const staticObstacles = [
{
name: "Screen",
minX: 1.20, maxX: 3.50,
minZ: -2.18, maxZ: -1.32,
height: 2.2
},
{
name: "Storage",
minX: -3.48, maxX: -1.92,
minZ: -2.34, maxZ: -1.16,
height: 1.2
}
];
const draggableItems = [];
const labels = [];
function addLabel(text, root, offsetY, draggable = false) {
const el = document.createElement("div");
el.className = `object-label ${draggable ? "draggable" : "static"}`;
el.textContent = text;
labelLayer.appendChild(el);
labels.push({ el, root, offsetY });
if (draggable) {
el.addEventListener("pointerdown", event => {
event.stopPropagation();
beginItemDrag(event, root);
});
}
}
function makeDraggable(root, name, halfX, halfZ, initialX, initialZ, obstacle = false) {
root.position.set(initialX, DESK_Y, initialZ);
root.userData.item = true;
root.userData.name = name;
root.userData.halfX = halfX;
root.userData.halfZ = halfZ;
root.userData.home = new THREE.Vector2(initialX, initialZ);
root.userData.lastValid = new THREE.Vector2(initialX, initialZ);
root.userData.obstacle = obstacle;
root.traverse(child => {
if (child.isMesh) child.userData.dragRoot = root;
});
draggableItems.push(root);
addLabel(name.toUpperCase(), root, name === "Lamp" ? 1.65 : 0.65, true);
return root;
}
// Lamp.
const lamp = new THREE.Group();
scene.add(lamp);
cylinder(0.33, 0.39, 0.13, mat.dark, 0, 0.07, 0, lamp);
cylinder(0.045, 0.045, 1.25, mat.gold, 0, 0.69, 0, lamp);
const lampShade = mesh(
new THREE.CylinderGeometry(0.17, 0.39, 0.40, 28, 1, false),
mat.gold,
lamp
);
lampShade.position.set(0, 1.31, 0);
const bulb = mesh(new THREE.SphereGeometry(0.12, 16, 12), mat.cream, lamp);
bulb.position.set(0, 1.16, 0);
const lampLight = new THREE.PointLight(0xffd990, 1.4, 3.1, 2);
lampLight.position.set(0, 1.15, 0);
lamp.add(lampLight);
makeDraggable(lamp, "Lamp", 0.40, 0.40, -1.55, -0.52, true);
// Book stack.
const books = new THREE.Group();
scene.add(books);
box(1.05, 0.12, 0.72, mat.teal, 0, 0.07, 0, books);
box(0.93, 0.11, 0.64, mat.cream, 0.04, 0.185, 0.02, books);
box(0.82, 0.10, 0.57, mat.coral, -0.03, 0.29, -0.02, books);
box(0.60, 0.025, 0.43, mat.white, -0.03, 0.347, -0.02, books);
box(0.07, 0.32, 0.74, mat.blue, -0.43, 0.16, 0.02, books);
box(0.055, 0.32, 0.74, mat.gold, 0.43, 0.16, 0.02, books);
makeDraggable(books, "Books", 0.54, 0.39, 0.72, 0.82);
// Mug.
const mug = new THREE.Group();
scene.add(mug);
cylinder(0.25, 0.22, 0.42, mat.coral, 0, 0.21, 0, mug);
cylinder(0.20, 0.20, 0.014, mat.dark, 0, 0.425, 0, mug);
const handle = mesh(new THREE.TorusGeometry(0.16, 0.042, 10, 28), mat.coral, mug);
handle.position.set(0.27, 0.24, 0);
makeDraggable(mug, "Mug", 0.34, 0.27, 0.02, 1.68);
// Phone.
const phone = new THREE.Group();
scene.add(phone);
box(0.44, 0.075, 0.78, mat.black, 0, 0.04, 0, phone);
box(0.38, 0.014, 0.66, mat.screenGlow, 0, 0.085, 0, phone);
box(0.13, 0.018, 0.018, mat.dark, 0, 0.095, -0.29, phone);
makeDraggable(phone, "Phone", 0.27, 0.43, 2.62, 0.68);
addLabel("SCREEN", screenRoot, 2.10, false);
addLabel("STORAGE", storageRoot, 1.42, false);
// Arm.
const arm = new THREE.Group();
scene.add(arm);
cylinder(0.38, 0.45, 0.14, mat.dark, 0, DESK_Y + 0.07, -2.48, arm);
cylinder(0.23, 0.29, 0.25, mat.coral, 0, DESK_Y + 0.24, -2.48, arm);
const shoulderMesh = mesh(new THREE.SphereGeometry(0.19, 20, 14), mat.gold, arm);
shoulderMesh.position.copy(SHOULDER);
const upperArm = mesh(new THREE.CylinderGeometry(0.105, 0.115, 1, 18), mat.coral, arm);
const lowerArm = mesh(new THREE.CylinderGeometry(0.075, 0.095, 1, 18), mat.cream, arm);
const elbowMesh = mesh(new THREE.SphereGeometry(0.16, 18, 14), mat.dark, arm);
const gripper = new THREE.Group();
scene.add(gripper);
box(0.23, 0.08, 0.16, mat.dark, 0, 0, 0, gripper);
box(0.045, 0.22, 0.055, mat.gold, -0.09, -0.13, 0, gripper);
box(0.045, 0.22, 0.055, mat.gold, 0.09, -0.13, 0, gripper);
const selectionRing = mesh(
new THREE.RingGeometry(0.34, 0.405, 48),
new THREE.MeshBasicMaterial({
color: 0x0d8c87,
transparent: true,
opacity: 0.85,
side: THREE.DoubleSide,
depthWrite: false
})
);
selectionRing.rotation.x = -Math.PI / 2;
selectionRing.position.y = DESK_Y + 0.031;
selectionRing.visible = false;
selectionRing.castShadow = false;
const targetRing = mesh(
new THREE.RingGeometry(0.27, 0.325, 48),
new THREE.MeshBasicMaterial({
color: 0xe76f51,
transparent: true,
opacity: 0.65,
side: THREE.DoubleSide,
depthWrite: false
})
);
targetRing.rotation.x = -Math.PI / 2;
targetRing.position.y = DESK_Y + 0.034;
targetRing.visible = false;
targetRing.castShadow = false;
const pathLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0xe76f51,
dashSize: 0.13,
gapSize: 0.09,
transparent: true,
opacity: 0.62,
depthWrite: false
})
);
pathLine.visible = false;
scene.add(pathLine);
let lastElbow = new THREE.Vector3(-1.2, SHOULDER.y, -0.4);
const currentTarget = new THREE.Vector3(-0.38, SHOULDER.y, -1.18);
let motion = null;
let dragging = null;
let dragOffset = new THREE.Vector2();
let placementValid = true;
let sweepTimer = null;
const yAxis = new THREE.Vector3(0, 1, 0);
const tempA = new THREE.Vector3();
const tempB = new THREE.Vector3();
const tempDir = new THREE.Vector3();
function setSegment(object, a, b) {
tempDir.subVectors(b, a);
const length = tempDir.length();
object.position.copy(a).add(b).multiplyScalar(0.5);
object.quaternion.setFromUnitVectors(yAxis, tempDir.normalize());
object.scale.set(1, length, 1);
}
function getObstacles(excludedItem = null) {
const result = staticObstacles.slice();
for (const item of draggableItems) {
if (item.userData.obstacle && item !== excludedItem) {
result.push({
name: item.userData.name,
minX: item.position.x - item.userData.halfX,
maxX: item.position.x + item.userData.halfX,
minZ: item.position.z - item.userData.halfZ,
maxZ: item.position.z + item.userData.halfZ,
height: 1.6
});
}
}
return result;
}
function pointInObstacle(point, obstacles, pad = 0.11) {
return obstacles.some(o =>
point.x >= o.minX - pad && point.x <= o.maxX + pad &&
point.z >= o.minZ - pad && point.z <= o.maxZ + pad
);
}
function segmentHitsObstacles(a, b, obstacles, pad = 0.11) {
const length = Math.hypot(b.x - a.x, b.z - a.z);
const steps = Math.max(2, Math.ceil(length / 0.065));
for (let i = 0; i <= steps; i++) {
const t = i / steps;
tempA.set(
THREE.MathUtils.lerp(a.x, b.x, t),
SHOULDER.y,
THREE.MathUtils.lerp(a.z, b.z, t)
);
if (pointInObstacle(tempA, obstacles, pad)) return true;
}
return false;
}
function elbowCandidates(start, end) {
const dx = end.x - SHOULDER.x;
const dz = end.z - SHOULDER.z;
const distance = Math.hypot(dx, dz);
if (distance < 0.0001) {
return [
new THREE.Vector3(SHOULDER.x, SHOULDER.y, SHOULDER.z + L1),
new THREE.Vector3(SHOULDER.x, SHOULDER.y, SHOULDER.z - L1)
];
}
const dir = new THREE.Vector3(dx, 0, dz).normalize();
const along = (L1 * L1 - L2 * L2 + distance * distance) / (2 * distance);
const height = Math.sqrt(Math.max(0, L1 * L1 - along * along));
const perp = new THREE.Vector3(-dir.z, 0, dir.x);
const a = new THREE.Vector3(
SHOULDER.x + dir.x * along,
SHOULDER.y,
SHOULDER.z + dir.z * along
);
return [
a.clone().addScaledVector(perp, height),
a.clone().addScaledVector(perp, -height)
];
}
function armClear(start, end, obstacles) {
const distance = Math.hypot(end.x - SHOULDER.x, end.z - SHOULDER.z);
if (distance > MAX_REACH - 0.015) return false;
if (pointInObstacle(end, obstacles, 0.08)) return false;
return elbowCandidates(start, end).some(elbow =>
!segmentHitsObstacles(SHOULDER, elbow, obstacles) &&
!segmentHitsObstacles(elbow, end, obstacles)
);
}
function nearestGridNode(x, z, obstacles) {
const gx = THREE.MathUtils.clamp(Math.round((x - GRID.minX) / GRID.step), 0, GRID.nx - 1);
const gz = THREE.MathUtils.clamp(Math.round((z - GRID.minZ) / GRID.step), 0, GRID.nz - 1);
for (let ring = 0; ring < Math.max(GRID.nx, GRID.nz); ring++) {
let best = null;
let bestDistance = Infinity;
for (let dz = -ring; dz <= ring; dz++) {
for (let dx = -ring; dx <= ring; dx++) {
if (ring > 0 && Math.abs(dx) !== ring && Math.abs(dz) !== ring) continue;
const ix = gx + dx;
const iz = gz + dz;
if (ix < 0 || iz < 0 || ix >= GRID.nx || iz >= GRID.nz) continue;
const point = gridPoint(ix, iz);
if (pointInObstacle(point, obstacles, 0.08)) continue;
const distance = Math.hypot(point.x - x, point.z - z);
if (distance < bestDistance) {
bestDistance = distance;
best = { ix, iz };
}
}
}
if (best) return best;
}
return { ix: gx, iz: gz };
}
const GRID = {
minX: -4.65,
maxX: 4.65,
minZ: -2.72,
maxZ: 2.72,
step: 0.30,
nx: 32,
nz: 19
};
function gridPoint(ix, iz) {
return new THREE.Vector3(
GRID.minX + ix * GRID.step,
SHOULDER.y,
GRID.minZ + iz * GRID.step
);
}
function findPath(start, goal, obstacles) {
if (armClear(start, goal, obstacles)) return [start.clone(), goal.clone()];
const startNode = nearestGridNode(start.x, start.z, obstacles);
const goalNode = nearestGridNode(goal.x, goal.z, obstacles);
const count = GRID.nx * GRID.nz;
const index = (ix, iz) => iz * GRID.nx + ix;
const gScore = new Float32Array(count);
const fScore = new Float32Array(count);
const cameFrom = new Int32Array(count);
const closed = new Uint8Array(count);
const open = [];
gScore.fill(Infinity);
fScore.fill(Infinity);
cameFrom.fill(-1);
const startIndex = index(startNode.ix, startNode.iz);
const goalIndex = index(goalNode.ix, goalNode.iz);
const goalPoint = gridPoint(goalNode.ix, goalNode.iz);
const heuristic = (ix, iz) => {
const p = gridPoint(ix, iz);
return Math.hypot(p.x - goalPoint.x, p.z - goalPoint.z);
};
gScore[startIndex] = 0;
fScore[startIndex] = heuristic(startNode.ix, startNode.iz);
open.push(startIndex);
const directions = [
[1,0], [-1,0], [0,1], [0,-1],
[1,1], [1,-1], [-1,1], [-1,-1]
];
let found = false;
while (open.length) {
let bestOpen = 0;
for (let i = 1; i < open.length; i++) {
if (fScore[open[i]] < fScore[open[bestOpen]]) bestOpen = i;
}
const currentIndex = open.splice(bestOpen, 1)[0];
if (currentIndex === goalIndex) {
found = true;
break;
}
closed[currentIndex] = 1;
const cx = currentIndex % GRID.nx;
const cz = Math.floor(currentIndex / GRID.nx);
const currentPoint = gridPoint(cx, cz);
for (const [dx, dz] of directions) {
const nx = cx + dx;
const nz = cz + dz;
if (nx < 0 || nz < 0 || nx >= GRID.nx || nz >= GRID.nz) continue;
const nextIndex = index(nx, nz);
if (closed[nextIndex]) continue;
const nextPoint = gridPoint(nx, nz);
if (!armClear(currentPoint, nextPoint, obstacles)) continue;
const tentative = gScore[currentIndex] + currentPoint.distanceTo(nextPoint);
if (tentative < gScore[nextIndex]) {
cameFrom[nextIndex] = currentIndex;
gScore[nextIndex] = tentative;
fScore[nextIndex] = tentative + heuristic(nx, nz);
if (!open.includes(nextIndex)) open.push(nextIndex);
}
}
}
if (!found) return [start.clone(), goal.clone()];
const raw = [];
let cursor = goalIndex;
while (cursor !== -1) {
raw.push(gridPoint(cursor % GRID.nx, Math.floor(cursor / GRID.nx)));
if (cursor === startIndex) break;
cursor = cameFrom[cursor];
}
raw.reverse();
const withEndpoints = [start.clone(), ...raw];
if (armClear(raw[raw.length - 1], goal, obstacles)) withEndpoints.push(goal.clone());
// Remove unnecessary grid turns when the full arm remains clear.
const smooth = [];
let i = 0;
while (i < withEndpoints.length) {
let furthest = i + 1;
for (let j = withEndpoints.length - 1; j > i; j--) {
if (armClear(withEndpoints[i], withEndpoints[j], obstacles)) {
furthest = j;
break;
}
}
smooth.push(withEndpoints[furthest].clone());
i = furthest + 1;
}
if (!smooth.length) smooth.push(goal.clone());
return smooth;
}
function showPath(points) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map(p => new THREE.Vector3(p.x, DESK_Y + 0.052, p.z))
);
pathLine.geometry.dispose();
pathLine.geometry = geometry;
pathLine.computeLineDistances();
pathLine.visible = true;
pathLine.material.opacity = 0.62;
}
function planReach(item, quiet = false) {
const goal = new THREE.Vector3(item.position.x, SHOULDER.y, item.position.z);
const obstacles = getObstacles(item);
const points = findPath(currentTarget.clone(), goal, obstacles);
motion = {
item,
points,
segment: 0,
segmentT: 0,
totalLength: 0,
traveled: 0,
active: true,
detour: points.length > 2
};
for (let i = 0; i < points.length - 1; i++) {
motion.totalLength += points[i].distanceTo(points[i + 1]);
}
showPath(points);
targetText.textContent = item.userData.name;
routeText.textContent = motion.detour
? `Detour · ${points.length - 1}`
: "Direct";
stateText.textContent = quiet ? "Sweeping" : "Routing";
stateText.style.color = "var(--teal)";
}
function updateArm(target) {
const obstacles = getObstacles(motion?.item ?? null);
const candidates = elbowCandidates(currentTarget, target);
const scored = candidates.map(elbow => {
let hits = 0;
if (segmentHitsObstacles(SHOULDER, elbow, obstacles)) hits++;
if (segmentHitsObstacles(elbow, target, obstacles)) hits++;
return { elbow, hits };
});
const clear = scored.filter(c => c.hits === 0);
const pool = clear.length ? clear : scored;
pool.sort((a, b) => a.elbow.distanceToSquared(lastElbow) - b.elbow.distanceToSquared(lastElbow));
const elbow = pool[0].elbow;
lastElbow.copy(elbow);
setSegment(upperArm, SHOULDER, elbow);
setSegment(lowerArm, elbow, target);
elbowMesh.position.copy(elbow);
gripper.position.copy(target);
}
function updateMotion(delta) {
if (!motion || !motion.active) return;
if (motion.segment >= motion.points.length - 1) {
motion.active = false;
targetRing.visible = true;
stateText.textContent = "Reached";
stateText.style.color = "var(--teal)";
return;
}
const from = motion.points[motion.segment];
const to = motion.points[motion.segment + 1];
const length = from.distanceTo(to);
const speed = 2.25;
motion.segmentT += length > 0 ? (delta * speed) / length : 1;
const t = Math.min(1, motion.segmentT);
currentTarget.lerpVectors(from, to, t);
motion.traveled += length * delta * speed / Math.max(length, 0.0001);
if (motion.totalLength > 0) {
const progress = Math.min(1, motion.traveled / motion.totalLength);
progressFill.style.width = `${progress * 100}%`;
}
if (t >= 1) {
motion.traveled += length * (1 - (motion.segmentT - 1));
motion.segment++;
motion.segmentT = 0;
}
}
// Dragging and placement validation.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -DESK_Y);
const planePoint = new THREE.Vector3();
function setPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function itemOverlapsRect(item, x, z, rect) {
return (
x + item.userData.halfX > rect.minX &&
x - item.userData.halfX < rect.maxX &&
z + item.userData.halfZ > rect.minZ &&
z - item.userData.halfZ < rect.maxZ
);
}
function validatePlacement(item, x, z) {
const halfX = item.userData.halfX;
const halfZ = item.userData.halfZ;
if (
x - halfX < -4.72 || x + halfX > 4.72 ||
z - halfZ < -2.78 || z + halfZ > 2.78
) return false;
for (const obstacle of staticObstacles) {
if (itemOverlapsRect(item, x, z, obstacle)) return false;
}
for (const other of draggableItems) {
if (other === item) continue;
const overlapX = halfX + other.userData.halfX + 0.08;
const overlapZ = halfZ + other.userData.halfZ + 0.08;
if (
Math.abs(x - other.position.x) < overlapX &&
Math.abs(z - other.position.z) < overlapZ
) return false;
}
const reach = Math.hypot(x - SHOULDER.x, z - SHOULDER.z);
return reach <= MAX_REACH - 0.12;
}
function beginItemDrag(event, item) {
if (event.button !== 0) return;
setPointer(event);
if (!raycaster.ray.intersectPlane(dragPlane, planePoint)) return;
event.preventDefault();
event.stopPropagation();
dragging = item;
dragOffset.set(item.position.x - planePoint.x, item.position.z - planePoint.z);
selectionRing.visible = true;
selectionRing.position.set(item.position.x, DESK_Y + 0.031, item.position.z);
selectionRing.material.color.set(0x0d8c87);
renderer.domElement.style.cursor = "grabbing";
stateText.textContent = "Positioning";
stateText.style.color = "var(--teal)";
routeText.textContent = "Checking";
}
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0 && event.button !== 2) return;
if (event.button === 0) {
setPointer(event);
const hits = raycaster.intersectObjects(draggableItems, true);
if (hits.length) {
const item = hits[0].object.userData.dragRoot;
if (item) {
beginItemDrag(event, item);
return;
}
}
}
orbit.dragging = true;
orbit.pointerId = event.pointerId;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = event.button === 2 ? "grabbing" : "default";
});
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("pointermove", event => {
if (dragging) {
setPointer(event);
if (!raycaster.ray.intersectPlane(dragPlane, planePoint)) return;
const x = THREE.MathUtils.clamp(
planePoint.x + dragOffset.x,
-4.72 + dragging.userData.halfX,
4.72 - dragging.userData.halfX
);
const z = THREE.MathUtils.clamp(
planePoint.z + dragOffset.y,
-2.78 + dragging.userData.halfZ,
2.78 - dragging.userData.halfZ
);
dragging.position.x = x;
dragging.position.z = z;
placementValid = validatePlacement(dragging, x, z);
selectionRing.position.set(x, DESK_Y + 0.031, z);
selectionRing.material.color.set(placementValid ? 0x0d8c87 : 0xd84f45);
routeText.textContent = placementValid ? "Clear" : "Blocked";
stateText.textContent = placementValid ? "Positioning" : "Invalid spot";
stateText.style.color = placementValid ? "var(--teal)" : "var(--red)";
return;
}
if (!orbit.dragging) return;
const dx = event.clientX - orbit.lastX;
const dy = event.clientY - orbit.lastY;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(orbit.pitch + dy * 0.005, 0.34, 1.05);
updateCamera();
});
function endPointer(event) {
if (dragging) {
const item = dragging;
if (placementValid) {
item.userData.lastValid.set(item.position.x, item.position.z);
planReach(item);
} else {
item.position.x = item.userData.lastValid.x;
item.position.z = item.userData.lastValid.y;
stateText.textContent = "Ready";
stateText.style.color = "var(--teal)";
routeText.textContent = "Direct";
}
dragging = null;
selectionRing.visible = false;
}
if (orbit.dragging) {
orbit.dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.style.cursor = "default";
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.008,
9.5,
20
);
updateCamera();
}, { passive: false });
function resetLayout() {
stopSweep();
for (const item of draggableItems) {
item.position.x = item.userData.home.x;
item.position.z = item.userData.home.y;
item.userData.lastValid.copy(item.userData.home);
}
currentTarget.set(-0.38, SHOULDER.y, -1.18);
planReach(books);
}
let sweepIndex = 0;
function stopSweep() {
if (sweepTimer) clearInterval(sweepTimer);
sweepTimer = null;
sweepButton.textContent = "Auto sweep";
}
function toggleSweep() {
if (sweepTimer) {
stopSweep();
stateText.textContent = "Ready";
stateText.style.color = "var(--teal)";
return;
}
sweepButton.textContent = "Stop sweep";
sweepTimer = setInterval(() => {
planReach(draggableItems[sweepIndex % draggableItems.length], true);
sweepIndex++;
}, 2300);
}
resetButton.addEventListener("click", resetLayout);
sweepButton.addEventListener("click", toggleSweep);
addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") resetLayout();
if (event.code === "Space") {
event.preventDefault();
toggleSweep();
}
});
// Project simple DOM labels onto the 3D scene.
const projected = new THREE.Vector3();
function updateLabels() {
for (const label of labels) {
projected.copy(label.root.position);
projected.y += label.offsetY;
projected.project(camera);
const visible =
projected.z > -1 && projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
label.el.style.opacity = visible ? "1" : "0";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * innerWidth;
const y = (-projected.y * 0.5 + 0.5) * innerHeight;
label.el.style.left = `${x}px`;
label.el.style.top = `${y}px`;
}
}
const clock = new THREE.Clock();
let firstFrame = true;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
updateMotion(delta);
updateArm(currentTarget);
if (targetRing.visible) {
const pulse = 1 + Math.sin(performance.now() * 0.004) * 0.08;
targetRing.scale.setScalar(pulse);
targetRing.material.opacity = 0.46 + Math.sin(performance.now() * 0.004) * 0.12;
}
if (pathLine.visible && motion && !motion.active) {
pathLine.material.opacity = Math.max(0.12, pathLine.material.opacity - delta * 0.045);
}
updateLabels();
renderer.render(scene, camera);
if (firstFrame) {
firstFrame = false;
document.getElementById("loading").classList.add("hidden");
setTimeout(() => planReach(books), 550);
}
}
animate();
</script>
</body>
</html>
```