Prompt specification
Build or customize the Three.js 3D scene "Delivery Robot Finds an Empty Shelf" 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: Delivery Robot Finds an Empty Shelf
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/delivery-robot-finds-an-empty-shelf-x3522
Scene Description Prompt:
Animate a robot switching between searching, carrying, and waiting when supplies are absent. Show the transition condition and avoid continuing with nonexistent cargo. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Working Three.js Starter (delivery-robot-finds-an-empty-shelf-x3522):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Robot Supply State Machine</title>
<style>
:root {
--ink: #14242b;
--muted: #60747c;
--panel: rgba(247, 252, 251, 0.91);
--border: rgba(20, 36, 43, 0.12);
--search: #2b7a78;
--carry: #d27a27;
--wait: #8661a8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dbe9e6;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(26, 55, 56, 0.14);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#statusPanel {
top: 18px;
left: 18px;
width: min(370px, calc(100vw - 36px));
padding: 18px;
}
.eyebrow {
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.title-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 5px 0 15px;
}
h1 {
margin: 0;
font-size: 18px;
line-height: 1.2;
}
#stateBadge {
flex: 0 0 auto;
padding: 7px 10px;
border-radius: 999px;
color: white;
background: var(--search);
font-size: 11px;
font-weight: 900;
letter-spacing: 0.08em;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-bottom: 13px;
}
.metric {
min-width: 0;
padding: 10px;
border-radius: 12px;
background: rgba(25, 52, 58, 0.055);
}
.metric span {
display: block;
color: var(--muted);
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
overflow: hidden;
font-size: 16px;
text-overflow: ellipsis;
white-space: nowrap;
}
#conditionBox {
padding: 12px;
border-left: 4px solid var(--search);
border-radius: 10px;
background: rgba(43, 122, 120, 0.08);
}
#conditionMain {
margin-top: 5px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
font-weight: 800;
line-height: 1.45;
}
#conditionSub {
margin-top: 5px;
color: var(--muted);
font-size: 12px;
line-height: 1.4;
}
#integrity {
margin-top: 11px;
color: #28705d;
font-size: 12px;
font-weight: 700;
}
#autoLine {
margin-top: 8px;
color: var(--muted);
font-size: 11px;
}
#logicPanel {
top: 18px;
right: 18px;
width: min(340px, calc(100vw - 36px));
padding: 17px;
}
#logicPanel h2 {
margin: 0 0 12px;
font-size: 15px;
}
.logic-rule {
display: grid;
grid-template-columns: 92px 1fr;
gap: 8px;
padding: 9px 0;
border-top: 1px solid var(--border);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.45;
}
.logic-rule:first-of-type {
border-top: 0;
}
.logic-rule strong {
color: var(--search);
}
#events {
display: grid;
gap: 7px;
max-height: 185px;
margin-top: 13px;
overflow: hidden;
}
.event {
display: grid;
grid-template-columns: 112px 1fr;
gap: 8px;
padding: 8px;
border-radius: 9px;
background: rgba(25, 52, 58, 0.045);
font-size: 10px;
line-height: 1.35;
}
.event strong {
color: #245e63;
font-size: 10px;
}
#stateRail {
position: fixed;
z-index: 10;
bottom: 80px;
left: 50%;
display: flex;
gap: 7px;
padding: 7px;
border: 1px solid var(--border);
border-radius: 16px;
background: rgba(247, 252, 251, 0.88);
box-shadow: 0 12px 40px rgba(26, 55, 56, 0.12);
transform: translateX(-50%);
backdrop-filter: blur(12px);
}
.state-node {
min-width: 150px;
padding: 9px 12px;
border-radius: 10px;
opacity: 0.52;
transition: 160ms ease;
}
.state-node.active {
opacity: 1;
background: rgba(43, 122, 120, 0.11);
box-shadow: inset 0 0 0 2px rgba(43, 122, 120, 0.34);
}
.state-node[data-state="WAITING"].active {
background: rgba(134, 97, 168, 0.12);
box-shadow: inset 0 0 0 2px rgba(134, 97, 168, 0.4);
}
.state-node[data-state="CARRYING"].active {
background: rgba(210, 122, 39, 0.13);
box-shadow: inset 0 0 0 2px rgba(210, 122, 39, 0.42);
}
.state-node b {
display: block;
font-size: 11px;
letter-spacing: 0.06em;
}
.state-node span {
display: block;
margin-top: 3px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
#controls {
position: fixed;
z-index: 11;
bottom: 18px;
left: 50%;
display: flex;
gap: 8px;
transform: translateX(-50%);
}
button {
min-height: 40px;
padding: 0 15px;
border: 1px solid rgba(20, 36, 43, 0.16);
border-radius: 11px;
color: var(--ink);
background: rgba(250, 253, 252, 0.94);
box-shadow: 0 6px 18px rgba(26, 55, 56, 0.11);
cursor: pointer;
font-size: 12px;
font-weight: 800;
transition: transform 120ms ease, opacity 120ms ease;
}
button:hover {
transform: translateY(-2px);
}
button:active {
transform: translateY(0);
}
button:disabled {
cursor: default;
opacity: 0.45;
transform: none;
}
#addSupply {
border-color: transparent;
color: white;
background: #287a70;
}
#cameraHint {
position: fixed;
z-index: 9;
right: 18px;
bottom: 18px;
padding: 8px 11px;
border-radius: 9px;
color: rgba(20, 36, 43, 0.72);
background: rgba(247, 252, 251, 0.72);
font-size: 10px;
pointer-events: none;
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
color: #245e63;
background: #dbe9e6;
font-size: 14px;
font-weight: 800;
letter-spacing: 0.08em;
}
@media (max-width: 900px) {
#logicPanel {
display: none;
}
#cameraHint {
display: none;
}
#stateRail {
max-width: calc(100vw - 24px);
overflow-x: auto;
}
.state-node {
min-width: 132px;
}
}
@media (max-width: 520px) {
#statusPanel {
padding: 13px;
}
#statusPanel h1 {
font-size: 14px;
}
.metric {
padding: 8px;
}
.metric strong {
font-size: 13px;
}
#stateRail {
bottom: 72px;
}
.state-node {
min-width: 118px;
padding: 8px;
}
#controls {
width: calc(100vw - 24px);
justify-content: center;
}
button {
padding: 0 11px;
font-size: 11px;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<section id="statusPanel" class="panel">
<div class="eyebrow">Voxel logistics lab</div>
<div class="title-row">
<h1>Supply robot state machine</h1>
<span id="stateBadge">SEARCHING</span>
</div>
<div class="metrics">
<div class="metric">
<span>Source stock</span>
<strong id="stockMetric">0</strong>
</div>
<div class="metric">
<span>Robot cargo</span>
<strong id="cargoMetric">NONE</strong>
</div>
<div class="metric">
<span>Delivered</span>
<strong id="deliveredMetric">0</strong>
</div>
</div>
<div id="conditionBox">
<div class="eyebrow">Transition condition</div>
<div id="conditionMain">supplies > 0 → CARRYING</div>
<div id="conditionSub">supplies = 0 → WAITING</div>
</div>
<div id="integrity">✓ Cargo invariant: no phantom cargo</div>
<div id="autoLine">Auto-restock in 5.0s</div>
</section>
<aside id="logicPanel" class="panel">
<div class="eyebrow">Explicit state logic</div>
<h2>Only real cargo can be carried</h2>
<div class="logic-rule">
<strong>SEARCHING</strong>
<span>stock > 0 ? CARRYING : WAITING</span>
</div>
<div class="logic-rule">
<strong>WAITING</strong>
<span>stock > 0 ? CARRYING : WAITING</span>
</div>
<div class="logic-rule">
<strong>CARRYING</strong>
<span>cargo ? move : reset</span>
</div>
<div class="logic-rule">
<strong>DELIVERY</strong>
<span>detach cargo → SEARCHING</span>
</div>
<div class="eyebrow" style="margin-top: 15px">Event stream</div>
<div id="events"></div>
</aside>
<nav id="stateRail" aria-label="Robot states">
<div class="state-node active" data-state="SEARCHING">
<b>SEARCHING</b>
<span>stock ? carry : wait</span>
</div>
<div class="state-node" data-state="WAITING">
<b>WAITING</b>
<span>stock > 0 → carry</span>
</div>
<div class="state-node" data-state="CARRYING">
<b>CARRYING</b>
<span>cargo attached</span>
</div>
</nav>
<div id="controls">
<button id="addSupply">+ Add supply</button>
<button id="pauseButton">Pause</button>
<button id="resetButton">Reset</button>
</div>
<div id="cameraHint">Drag to orbit · Wheel to zoom</div>
<div id="loading">LOADING VOXEL SCENE…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM helpers
// -------------------------------------------------------------------------
const $ = (selector) => document.querySelector(selector);
const canvas = $("#scene");
const stateBadge = $("#stateBadge");
const stockMetric = $("#stockMetric");
const cargoMetric = $("#cargoMetric");
const deliveredMetric = $("#deliveredMetric");
const conditionMain = $("#conditionMain");
const conditionSub = $("#conditionSub");
const integrity = $("#integrity");
const autoLine = $("#autoLine");
const eventsElement = $("#events");
const addSupplyButton = $("#addSupply");
const pauseButton = $("#pauseButton");
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe9e6);
scene.fog = new THREE.Fog(0xdbe9e6, 25, 46);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
// Custom camera controls. No addons are imported.
const cameraControls = {
target: new THREE.Vector3(0, 0.8, 0),
yaw: 0.52,
pitch: 0.62,
radius: 17.5,
dragging: false,
lastX: 0,
lastY: 0
};
function updateCamera() {
const { target, yaw, pitch, radius } = cameraControls;
const horizontal = Math.cos(pitch) * radius;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
updateCamera();
canvas.addEventListener("pointerdown", (event) => {
cameraControls.dragging = true;
cameraControls.lastX = event.clientX;
cameraControls.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!cameraControls.dragging) return;
const dx = event.clientX - cameraControls.lastX;
const dy = event.clientY - cameraControls.lastY;
cameraControls.lastX = event.clientX;
cameraControls.lastY = event.clientY;
cameraControls.yaw -= dx * 0.006;
cameraControls.pitch = THREE.MathUtils.clamp(
cameraControls.pitch + dy * 0.005,
0.25,
1.18
);
updateCamera();
});
const stopCameraDrag = () => {
cameraControls.dragging = false;
};
canvas.addEventListener("pointerup", stopCameraDrag);
canvas.addEventListener("pointercancel", stopCameraDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControls.radius = THREE.MathUtils.clamp(
cameraControls.radius * Math.exp(event.deltaY * 0.001),
9,
27
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xf5fff8, 0x71858a, 2.0));
const sun = new THREE.DirectionalLight(0xfff5db, 3.0);
sun.position.set(-7, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.normalBias = 0.035;
scene.add(sun);
// -------------------------------------------------------------------------
// Shared materials and helpers
// -------------------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.0,
...options
});
}
const materials = {
groundBase: standardMaterial(0x617779),
road: standardMaterial(0x71898a),
dark: standardMaterial(0x263d42),
robot: standardMaterial(0xf3b83f),
robotLight: standardMaterial(0xffd879),
robotDark: standardMaterial(0x334a50),
joint: standardMaterial(0x6b8589),
eye: standardMaterial(0x9effe0, {
emissive: 0x39d9ad,
emissiveIntensity: 1.5
}),
shelf: standardMaterial(0x466d6c),
shelfEdge: standardMaterial(0x789b91),
platform: standardMaterial(0xb9cbc4),
delivery: standardMaterial(0x4d8074),
crate: standardMaterial(0xd88738),
crateBand: standardMaterial(0x69402c),
deliveredCrate: standardMaterial(0x68a982),
deliveredBand: standardMaterial(0x315b4b),
trunk: standardMaterial(0x72503c),
leaves: standardMaterial(0x4e8872),
leavesLight: standardMaterial(0x71a47d)
};
const boxCache = new Map();
function box(width, height, depth, material, x, y, z, parent = scene) {
const key = `${width},${height},${depth}`;
let geometry = boxCache.get(key);
if (!geometry) {
geometry = new THREE.BoxGeometry(width, height, depth);
boxCache.set(key, geometry);
}
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeSign(text, background = "#244c4c", foreground = "#f4fff9") {
const signCanvas = document.createElement("canvas");
signCanvas.width = 512;
signCanvas.height = 128;
const context = signCanvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, 512, 128);
context.fillStyle = foreground;
context.fillRect(0, 112, 512, 16);
context.font = "800 54px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 60);
const texture = new THREE.CanvasTexture(signCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(3.0, 0.75, 1);
sprite.renderOrder = 20;
return sprite;
}
// -------------------------------------------------------------------------
// Voxel terrain
// -------------------------------------------------------------------------
box(20, 0.42, 12, materials.groundBase, 0, -0.28, 0);
const tileGeometry = new THREE.BoxGeometry(0.96, 0.12, 0.96);
const tileMaterial = standardMaterial(0xffffff);
const tileCount = 19 * 11;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
const dummy = new THREE.Object3D();
const grassA = new THREE.Color(0x92b5a2);
const grassB = new THREE.Color(0x87aa99);
const roadColor = new THREE.Color(0x718b8b);
const pathColor = new THREE.Color(0xc7a955);
let tileIndex = 0;
for (let x = -9; x <= 9; x++) {
for (let z = -5; z <= 5; z++) {
dummy.position.set(x, 0.01, z);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
let color = (x + z) % 2 === 0 ? grassA : grassB;
if (Math.abs(z) <= 1 && Math.abs(x) <= 7) {
color = roadColor;
}
if (z === 0 && x >= -7 && x <= 7 && x % 2 !== 0) {
color = pathColor;
}
tiles.setColorAt(tileIndex, color);
tileIndex++;
}
}
tiles.receiveShadow = true;
scene.add(tiles);
function makeTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
box(0.45, 1.6, 0.45, materials.trunk, 0, 0.8, 0, group);
box(1.7, 0.85, 1.7, materials.leaves, 0, 1.85, 0, group);
box(1.25, 0.8, 1.25, materials.leavesLight, 0, 2.55, 0, group);
box(0.8, 0.65, 0.8, materials.leaves, 0.95, 1.95, 0.1, group);
scene.add(group);
}
makeTree(-7.8, 3.8, 1.05);
makeTree(7.8, 3.9, 0.9);
makeTree(-8.1, -3.6, 0.85);
makeTree(8.3, -3.4, 1.0);
// -------------------------------------------------------------------------
// Supply station
// -------------------------------------------------------------------------
const SOURCE_X = -3.75;
const DESTINATION_X = 4.25;
const MAX_STOCK = 5;
box(3.25, 0.28, 2.6, materials.platform, -5.15, 0.13, -1.25);
box(0.18, 2.45, 0.18, materials.shelf, -6.25, 1.3, -1.75);
box(0.18, 2.45, 0.18, materials.shelf, -4.05, 1.3, -1.75);
box(0.18, 2.45, 0.18, materials.shelf, -6.25, 1.3, -0.65);
box(0.18, 2.45, 0.18, materials.shelf, -4.05, 1.3, -0.65);
for (const y of [0.25, 1.05, 1.85]) {
box(2.55, 0.16, 1.35, materials.shelf, -5.15, y, -1.2);
box(2.58, 0.07, 0.07, materials.shelfEdge, -5.15, y + 0.1, -0.49);
}
const sourceSign = makeSign("SUPPLIES", "#426d68");
sourceSign.position.set(-5.15, 3.05, -1.35);
scene.add(sourceSign);
// -------------------------------------------------------------------------
// Delivery station
// -------------------------------------------------------------------------
box(3.25, 0.28, 2.9, materials.platform, 5.0, 0.13, 0.65);
box(3.0, 0.18, 0.65, materials.delivery, 5.0, 0.35, 1.45);
box(0.35, 1.6, 0.35, materials.delivery, 6.15, 0.95, 0.05);
box(0.35, 1.6, 0.35, materials.delivery, 3.85, 0.95, 0.05);
box(2.65, 0.35, 0.35, materials.delivery, 5.0, 1.7, 0.05);
const destinationSign = makeSign("DELIVERY", "#386c59");
destinationSign.position.set(5.0, 2.75, -0.1);
scene.add(destinationSign);
// -------------------------------------------------------------------------
// Shared voxel crate geometry
// -------------------------------------------------------------------------
const crateBodyGeometry = new THREE.BoxGeometry(0.68, 0.68, 0.68);
const crateBandGeometry = new THREE.BoxGeometry(0.73, 0.1, 0.73);
const crateFaceGeometry = new THREE.BoxGeometry(0.12, 0.65, 0.04);
const crateHighlightGeometry = new THREE.BoxGeometry(0.18, 0.12, 0.04);
function createCrate(delivered = false) {
const group = new THREE.Group();
const body = new THREE.Mesh(
crateBodyGeometry,
delivered ? materials.deliveredCrate : materials.crate
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const band = new THREE.Mesh(
crateBandGeometry,
delivered ? materials.deliveredBand : materials.crateBand
);
band.position.y = 0.12;
band.castShadow = true;
group.add(band);
const faceBand = new THREE.Mesh(
crateFaceGeometry,
delivered ? materials.deliveredBand : materials.crateBand
);
faceBand.position.set(0, 0, 0.35);
group.add(faceBand);
const highlight = new THREE.Mesh(
crateHighlightGeometry,
standardMaterial(delivered ? 0xa4d8ad : 0xf6bb64)
);
highlight.position.set(-0.17, 0.19, 0.37);
group.add(highlight);
return group;
}
// Actual stock meshes are driven directly by the stock count.
const supplyVisuals = [];
for (let i = 0; i < MAX_STOCK; i++) {
const crate = createCrate(false);
crate.scale.setScalar(0.67);
scene.add(crate);
supplyVisuals.push(crate);
}
const deliveryVisuals = [];
for (let i = 0; i < 10; i++) {
const crate = createCrate(true);
crate.scale.setScalar(0.7);
scene.add(crate);
deliveryVisuals.push(crate);
}
function renderInventory() {
for (let i = 0; i < supplyVisuals.length; i++) {
const crate = supplyVisuals[i];
const level = Math.floor(i / 2);
const column = i % 2;
crate.visible = i < stock;
crate.position.set(
-5.62 + column * 0.52,
0.53 + level * 0.8,
-1.22
);
}
}
function renderDelivered() {
for (let i = 0; i < deliveryVisuals.length; i++) {
const crate = deliveryVisuals[i];
const level = Math.floor(i / 5);
const column = i % 5;
crate.visible = i < delivered;
crate.position.set(
4.15 + column * 0.46,
0.48 + level * 0.51,
1.45
);
}
}
// -------------------------------------------------------------------------
// Voxel robot
// -------------------------------------------------------------------------
function makeRobot() {
const root = new THREE.Group();
root.position.x = 0;
const torso = box(
0.92, 0.88, 0.72,
materials.robot,
0, 1.08, 0,
root
);
box(
0.74, 0.25, 0.76,
materials.robotLight,
0, 1.26, 0,
root
);
box(
0.20, 0.45, 0.76,
materials.robotDark,
-0.43, 1.12, 0,
root
);
// Head pivot allows a visible searching scan.
const head = new THREE.Group();
head.position.set(0, 1.82, 0);
root.add(head);
box(
0.92, 0.70, 0.82,
materials.robotLight,
0, 0, 0,
head
);
box(
0.18, 0.24, 0.18,
materials.joint,
0, 0.47, 0,
head
);
box(
0.18, 0.18, 0.18,
materials.eye,
0, 0.66, 0,
head
);
const eyeA = box(
0.12, 0.18, 0.18,
materials.eye,
0.47, 0.04, -0.22,
head
);
const eyeB = box(
0.12, 0.18, 0.18,
materials.eye,
0.47, 0.04, 0.22,
head
);
box(
0.10, 0.18, 0.42,
materials.robotDark,
0.47, -0.11, 0,
head
);
// Arms are pivots so they can hold the crate.
const armA = new THREE.Group();
armA.position.set(0, 1.40, 0.57);
root.add(armA);
box(
0.28, 0.65, 0.28,
materials.robot,
0, -0.24, 0,
armA
);
box(
0.32, 0.25, 0.32,
materials.robotDark,
0, -0.61, 0,
armA
);
const armB = new THREE.Group();
armB.position.set(0, 1.40, -0.57);
root.add(armB);
box(
0.28, 0.65, 0.28,
materials.robot,
0, -0.24, 0,
armB
);
box(
0.32, 0.25, 0.32,
materials.robotDark,
0, -0.61, 0,
armB
);
const legA = new THREE.Group();
legA.position.set(0, 0.63, 0.24);
root.add(legA);
box(
0.28, 0.57, 0.29,
materials.joint,
0, -0.22, 0,
legA
);
box(
0.48, 0.20, 0.34,
materials.robotDark,
0.10, -0.49, 0,
legA
);
const legB = new THREE.Group();
legB.position.set(0, 0.63, -0.24);
root.add(legB);
box(
0.28, 0.57, 0.29,
materials.joint,
0, -0.22, 0,
legB
);
box(
0.48, 0.20, 0.34,
materials.robotDark,
0.10, -0.49, 0,
legB
);
scene.add(root);
return {
root,
torso,
head,
eyeA,
eyeB,
armA,
armB,
legA,
legB,
moving: false
};
}
const robot = makeRobot();
// -------------------------------------------------------------------------
// Robot state label
// -------------------------------------------------------------------------
const bubbleCanvas = document.createElement("canvas");
bubbleCanvas.width = 512;
bubbleCanvas.height = 128;
const bubbleContext = bubbleCanvas.getContext("2d");
const bubbleTexture = new THREE.CanvasTexture(bubbleCanvas);
bubbleTexture.colorSpace = THREE.SRGBColorSpace;
const bubbleMaterial = new THREE.SpriteMaterial({
map: bubbleTexture,
transparent: true,
depthTest: false
});
const stateBubble = new THREE.Sprite(bubbleMaterial);
stateBubble.position.set(0, 2.95, 0);
stateBubble.scale.set(2.55, 0.64, 1);
stateBubble.renderOrder = 30;
robot.root.add(stateBubble);
function drawStateBubble(label, color) {
bubbleContext.clearRect(0, 0, 512, 128);
bubbleContext.fillStyle = "rgba(250, 253, 252, 0.96)";
bubbleContext.fillRect(0, 0, 512, 128);
bubbleContext.fillStyle = color;
bubbleContext.fillRect(0, 0, 18, 128);
bubbleContext.strokeStyle = color;
bubbleContext.lineWidth = 9;
bubbleContext.strokeRect(4, 4, 504, 120);
bubbleContext.fillStyle = "#14242b";
bubbleContext.font = "900 49px system-ui, sans-serif";
bubbleContext.textAlign = "center";
bubbleContext.textBaseline = "middle";
bubbleContext.fillText(label, 266, 66);
bubbleTexture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Search scanner
// -------------------------------------------------------------------------
const scanMaterial = new THREE.MeshBasicMaterial({
color: 0x47c9b3,
transparent: true,
opacity: 0.16,
depthWrite: false
});
const scanField = new THREE.Mesh(
new THREE.BoxGeometry(2.15, 0.035, 2.15),
scanMaterial
);
scanField.position.set(SOURCE_X, 0.12, 0);
scene.add(scanField);
// -------------------------------------------------------------------------
// State machine
// -------------------------------------------------------------------------
const State = Object.freeze({
SEARCHING: "SEARCHING",
WAITING: "WAITING",
CARRYING: "CARRYING"
});
const stateColors = {
SEARCHING: "#2b7a78",
WAITING: "#8661a8",
CARRYING: "#d27a27"
};
let state = State.SEARCHING;
let stateTime = 0;
let searchScanTime = 0;
let waitCheckTime = 0;
let stock = 0;
let delivered = 0;
let cargo = null;
let paused = false;
let simulationTime = 0;
let autoSupplyIn = 5.0;
function addEvent(label, text) {
const row = document.createElement("div");
row.className = "event";
const strong = document.createElement("strong");
strong.textContent = label;
const span = document.createElement("span");
span.textContent = text;
row.append(strong, span);
eventsElement.prepend(row);
while (eventsElement.children.length > 6) {
eventsElement.lastElementChild.remove();
}
}
function transition(nextState, reason) {
const previous = state;
state = nextState;
stateTime = 0;
if (nextState === State.SEARCHING) searchScanTime = 0;
if (nextState === State.WAITING) waitCheckTime = 0;
drawStateBubble(nextState, stateColors[nextState]);
addEvent(`${previous} → ${nextState}`, reason);
refreshHUD();
}
function beginCarrying() {
// Guard: CARRYING cannot begin unless real inventory exists.
if (stock <= 0) {
addEvent("GUARD", "Refused to carry: no supply is available.");
return false;
}
// Guard: there can only be one physical cargo mesh.
if (cargo !== null) {
addEvent("GUARD", "Refused to carry: robot already has cargo.");
return false;
}
stock -= 1;
renderInventory();
// Create and attach a real crate before changing state.
cargo = createCrate(false);
cargo.position.set(1.02, 0.96, 0);
robot.root.add(cargo);
transition(
State.CARRYING,
`Condition stock > 0 was true; attached 1 physical crate. Stock now ${stock}.`
);
return true;
}
function completeDelivery() {
// Guard: delivery requires an attached cargo mesh.
if (cargo === null) {
transition(
State.SEARCHING,
"Safety reset: CARRYING had no cargo, so no delivery was continued."
);
return;
}
robot.root.remove(cargo);
cargo = null;
delivered += 1;
renderDelivered();
transition(
State.SEARCHING,
`Cargo delivered and detached. Delivered count is now ${delivered}.`
);
}
function dampAngle(current, target, lambda, dt) {
const difference = Math.atan2(
Math.sin(target - current),
Math.cos(target - current)
);
return current + difference * (1 - Math.exp(-lambda * dt));
}
function moveRobot(targetX, dt, speed) {
const difference = targetX - robot.root.position.x;
const distance = Math.abs(difference);
if (distance <= 0.025) {
robot.root.position.x = targetX;
robot.moving = false;
return true;
}
const amount = Math.min(distance, speed * dt);
robot.root.position.x += Math.sign(difference) * amount;
const targetRotation = difference > 0 ? 0 : Math.PI;
robot.root.rotation.y = dampAngle(
robot.root.rotation.y,
targetRotation,
9,
dt
);
robot.moving = true;
return false;
}
function updateSimulation(dt) {
stateTime += dt;
if (state === State.SEARCHING) {
const distanceToSource = Math.abs(
robot.root.position.x - SOURCE_X
);
if (distanceToSource > 0.035) {
robot.moving = moveRobot(SOURCE_X, dt, 1.55);
searchScanTime = 0;
} else {
robot.moving = false;
searchScanTime += dt;
if (searchScanTime >= 0.45 && stock > 0) {
beginCarrying();
} else if (searchScanTime >= 1.35 && stock === 0) {
transition(
State.WAITING,
"Condition stock = 0 was true; robot stays empty and enters WAITING."
);
}
}
} else if (state === State.WAITING) {
robot.moving = false;
waitCheckTime += dt;
if (waitCheckTime >= 0.25) {
waitCheckTime = 0;
// The waiting robot remains empty until real stock appears.
if (stock > 0) {
beginCarrying();
}
}
} else if (state === State.CARRYING) {
if (cargo === null) {
// This should never occur, but the state machine fails safely.
transition(
State.SEARCHING,
"Invariant repaired: cargo mesh was missing, so carrying was stopped."
);
return;
}
const arrived = moveRobot(DESTINATION_X, dt, 1.7);
if (arrived) {
robot.moving = false;
completeDelivery();
}
}
}
function updateSupplyClock(dt) {
if (stock >= MAX_STOCK) {
autoSupplyIn = 7.0;
return;
}
autoSupplyIn -= dt;
if (autoSupplyIn <= 0) {
stock += 1;
autoSupplyIn = 7.0;
renderInventory();
addEvent("RESTOCK", `One supply appeared at the source. Stock = ${stock}.`);
refreshHUD();
}
}
// -------------------------------------------------------------------------
// HUD
// -------------------------------------------------------------------------
function refreshHUD() {
stateBadge.textContent = state;
stateBadge.style.background = stateColors[state];
stockMetric.textContent = `${stock} / ${MAX_STOCK}`;
cargoMetric.textContent = cargo === null ? "NONE" : "1 crate";
deliveredMetric.textContent = delivered;
if (state === State.SEARCHING) {
conditionMain.textContent = "stock > 0 ? CARRYING : WAITING";
conditionSub.textContent =
stock > 0
? `Observed stock = ${stock}; the robot may pick up a crate.`
: `Observed stock = ${stock}; after scanning, the robot will wait.`;
} else if (state === State.WAITING) {
conditionMain.textContent = "stock > 0 → CARRYING";
conditionSub.textContent =
stock > 0
? "Supply is available; a crate will be attached before carrying."
: "No supply exists. Remain WAITING with cargo = NONE.";
} else {
conditionMain.textContent = "cargo !== null → keep carrying";
conditionSub.textContent =
"On arrival: remove the crate, increment delivery, then return to SEARCHING.";
}
integrity.textContent = cargo === null
? "✓ Cargo invariant: no phantom cargo"
: "✓ Cargo invariant: one physical crate is attached";
integrity.style.color = cargo === null ? "#28705d" : "#a25e20";
if (stock >= MAX_STOCK) {
autoLine.textContent = "Source shelf is full.";
addSupplyButton.disabled = true;
} else {
autoLine.textContent = `Auto-restock in ${Math.max(0, autoSupplyIn).toFixed(1)}s`;
addSupplyButton.disabled = false;
}
document.querySelectorAll(".state-node").forEach((node) => {
node.classList.toggle("active", node.dataset.state === state);
});
}
// -------------------------------------------------------------------------
// Robot animation
// -------------------------------------------------------------------------
let walkPhase = 0;
function animateRobot(dt) {
const visualDt = paused ? 0 : dt;
const moving = robot.moving;
walkPhase += visualDt * (moving ? 9 : 1.5);
const swing = moving ? Math.sin(walkPhase) : 0;
robot.legA.rotation.z = swing * 0.42;
robot.legB.rotation.z = -swing * 0.42;
if (state === State.CARRYING) {
robot.armA.rotation.z = 0.86;
robot.armB.rotation.z = -0.86;
} else if (moving) {
robot.armA.rotation.z = -swing * 0.62;
robot.armB.rotation.z = swing * 0.62;
} else if (state === State.WAITING) {
robot.armA.rotation.z = 0.10;
robot.armB.rotation.z = -0.10;
} else {
robot.armA.rotation.z = -0.08;
robot.armB.rotation.z = 0.08;
}
robot.torso.position.y =
1.08 + (moving ? Math.abs(Math.sin(walkPhase)) * 0.045 : 0);
const nearSource =
Math.abs(robot.root.position.x - SOURCE_X) < 0.12;
if (state === State.SEARCHING && nearSource) {
robot.head.rotation.y = Math.sin(simulationTime * 7.0) * 0.42;
} else if (state === State.WAITING) {
robot.head.rotation.y = Math.sin(simulationTime * 1.2) * 0.08;
} else if (state === State.CARRYING) {
robot.head.rotation.y = Math.sin(simulationTime * 2.0) * 0.035;
} else {
robot.head.rotation.y = 0;
}
// Small blinking animation.
const blink = simulationTime % 4.4 > 4.24 ? 0.12 : 1;
robot.eyeA.scale.y = blink;
robot.eyeB.scale.y = blink;
if (cargo !== null) {
cargo.position.y = 0.96 + Math.sin(simulationTime * 4.0) * 0.025;
}
const scanning =
state === State.SEARCHING &&
nearSource;
scanField.visible = scanning;
if (scanning) {
const pulse = 1 + Math.sin(simulationTime * 5.5) * 0.07;
scanField.scale.set(pulse, 1, pulse);
scanMaterial.opacity = 0.12 + Math.sin(simulationTime * 5.5) * 0.05;
}
}
// -------------------------------------------------------------------------
// Controls and reset
// -------------------------------------------------------------------------
addSupplyButton.addEventListener("click", () => {
if (stock >= MAX_STOCK) return;
stock += 1;
autoSupplyIn = 7.0;
renderInventory();
addEvent("SUPPLY +1", `Source stock increased to ${stock}.`);
refreshHUD();
});
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
function resetSimulation() {
if (cargo !== null) {
robot.root.remove(cargo);
cargo = null;
}
state = State.SEARCHING;
stateTime = 0;
searchScanTime = 0;
waitCheckTime = 0;
stock = 0;
delivered = 0;
paused = false;
simulationTime = 0;
autoSupplyIn = 5.0;
robot.root.position.set(0, 0, 0);
robot.root.rotation.set(0, 0, 0);
robot.moving = false;
pauseButton.textContent = "Pause";
renderInventory();
renderDelivered();
drawStateBubble(State.SEARCHING, stateColors[State.SEARCHING]);
eventsElement.replaceChildren();
addEvent("SYSTEM", "State machine reset. Source stock = 0.");
refreshHUD();
}
$("#resetButton").addEventListener("click", resetSimulation);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
let lastHudUpdate = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const now = performance.now();
if (!paused) {
simulationTime += dt;
updateSupplyClock(dt);
updateSimulation(dt);
}
animateRobot(dt);
if (now - lastHudUpdate > 80) {
refreshHUD();
lastHudUpdate = now;
}
renderer.render(scene, camera);
}
renderInventory();
renderDelivered();
drawStateBubble(State.SEARCHING, stateColors[State.SEARCHING]);
addEvent("SYSTEM", "State machine armed. Source stock = 0.");
refreshHUD();
$("#loading").style.display = "none";
animate();
</script>
</body>
</html>
```