Prompt specification
Build or customize the Three.js 3D scene "Shop Assistant Task Cycle" 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: Shop Assistant Task Cycle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/shop-assistant-task-cycle-x3687
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts character animation states and interrupted actions. Build a small original shop scene where a character waits, walks, reaches, carries, and returns. Show the current state and prevent incompatible actions from running simultaneously. Voxel style.
Working Three.js Starter (shop-assistant-task-cycle-x3687):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Corner Shop — Animation State Machine</title>
<style>
:root {
--state: #7dd3fc;
--panel: rgba(15, 23, 42, 0.9);
--border: rgba(148, 163, 184, 0.25);
--text: #e5e7eb;
--muted: #94a3b8;
--green: #86efac;
--red: #fca5a5;
--amber: #fde68a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dbeafe;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: absolute;
z-index: 10;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
box-shadow: 0 18px 45px rgba(15, 23, 42, 0.22);
backdrop-filter: blur(12px);
}
#statePanel {
top: 18px;
left: 18px;
width: min(350px, calc(100vw - 36px));
padding: 16px;
}
.eyebrow {
margin: 0 0 5px;
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.state-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
#stateName {
color: var(--state);
font-size: 27px;
font-weight: 900;
letter-spacing: 0.04em;
line-height: 1.1;
}
#stateHint {
margin-top: 7px;
color: var(--muted);
font-size: 12px;
}
#lockPill {
flex: 0 0 auto;
padding: 6px 9px;
border: 1px solid rgba(134, 239, 172, 0.3);
border-radius: 999px;
background: rgba(134, 239, 172, 0.08);
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
white-space: nowrap;
}
#lockPill[data-locked="true"] {
border-color: rgba(253, 230, 138, 0.3);
background: rgba(253, 230, 138, 0.08);
color: var(--amber);
}
#timeline {
display: flex;
gap: 5px;
margin: 14px 0 12px;
}
.timeline-step {
flex: 1;
min-width: 0;
padding: 7px 3px;
border: 1px solid rgba(148, 163, 184, 0.15);
border-radius: 7px;
background: rgba(148, 163, 184, 0.06);
color: #64748b;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.03em;
text-align: center;
}
.timeline-step.passed {
color: #94a3b8;
background: rgba(148, 163, 184, 0.11);
}
.timeline-step.current {
border-color: var(--state);
color: var(--state);
background: color-mix(in srgb, var(--state) 12%, transparent);
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--state) 18%, transparent);
}
#message {
min-height: 40px;
padding: 10px 11px;
border-left: 3px solid #60a5fa;
border-radius: 6px;
background: rgba(96, 165, 250, 0.08);
color: #dbeafe;
font-size: 12px;
line-height: 1.45;
}
#message[data-tone="warn"] {
border-color: var(--amber);
background: rgba(253, 230, 138, 0.08);
color: #fef3c7;
}
#message[data-tone="error"] {
border-color: var(--red);
background: rgba(252, 165, 165, 0.08);
color: #fee2e2;
}
#message[data-tone="success"] {
border-color: var(--green);
background: rgba(134, 239, 172, 0.08);
color: #dcfce7;
}
#eventLog {
margin-top: 10px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
line-height: 1.55;
}
#eventLog div {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#eventLog div:first-child {
color: #cbd5e1;
}
#controlsPanel {
left: 50%;
bottom: 18px;
width: min(760px, calc(100vw - 36px));
padding: 12px;
transform: translateX(-50%);
}
.controls-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin: 0 3px 9px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
}
#buttons {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
gap: 7px;
}
button {
min-width: 0;
padding: 11px 7px;
border: 1px solid rgba(148, 163, 184, 0.22);
border-radius: 9px;
background: rgba(51, 65, 85, 0.72);
color: #cbd5e1;
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease,
opacity 120ms ease;
}
button:hover {
transform: translateY(-2px);
border-color: rgba(226, 232, 240, 0.42);
background: rgba(71, 85, 105, 0.9);
}
button:active {
transform: translateY(0);
}
button.allowed {
border-color: rgba(134, 239, 172, 0.5);
background: rgba(22, 101, 52, 0.52);
color: #dcfce7;
}
button.locked {
opacity: 0.43;
}
button[data-action="interrupt"].allowed {
border-color: rgba(252, 165, 165, 0.6);
background: rgba(127, 29, 29, 0.58);
color: #fee2e2;
}
button[data-action="auto"].allowed {
border-color: rgba(125, 211, 252, 0.6);
background: rgba(14, 116, 144, 0.5);
color: #cffafe;
}
#cameraHelp {
position: absolute;
right: 18px;
bottom: 18px;
z-index: 9;
padding: 8px 11px;
border: 1px solid rgba(15, 23, 42, 0.13);
border-radius: 9px;
background: rgba(255, 255, 255, 0.72);
color: #475569;
font-size: 10px;
font-weight: 700;
pointer-events: none;
}
#interruptFlash {
position: fixed;
inset: 0;
z-index: 30;
border: 0 solid rgba(248, 113, 113, 0);
pointer-events: none;
}
#interruptFlash.active {
animation: interruptFlash 650ms ease-out;
}
@keyframes interruptFlash {
0% {
border-width: 12px;
border-color: rgba(248, 113, 113, 0.75);
background: rgba(248, 113, 113, 0.08);
}
100% {
border-width: 0;
border-color: rgba(248, 113, 113, 0);
background: rgba(248, 113, 113, 0);
}
}
@media (max-width: 760px) {
#statePanel {
top: 10px;
left: 10px;
width: min(330px, calc(100vw - 20px));
padding: 12px;
}
#stateName {
font-size: 22px;
}
#eventLog {
display: none;
}
#controlsPanel {
bottom: 10px;
width: calc(100vw - 20px);
padding: 9px;
}
#buttons {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
button {
padding: 10px 4px;
font-size: 10px;
}
#cameraHelp {
display: none;
}
}
</style>
</head>
<body>
<div id="statePanel" class="panel">
<p class="eyebrow">Voxel Corner Shop</p>
<div class="state-row">
<div>
<div id="stateName">WAITING</div>
<div id="stateHint">Idle near the entrance</div>
</div>
<div id="lockPill" data-locked="false">Ready</div>
</div>
<div id="timeline" aria-label="Animation state timeline">
<div class="timeline-step" data-step="WAITING">WAIT</div>
<div class="timeline-step" data-step="WALKING">WALK</div>
<div class="timeline-step" data-step="REACHING">REACH</div>
<div class="timeline-step" data-step="CARRYING">CARRY</div>
<div class="timeline-step" data-step="RETURNING">RETURN</div>
</div>
<div id="message" data-tone="info" aria-live="polite">
Choose an action. Incompatible actions are blocked while another animation owns the timeline.
</div>
<div id="eventLog" aria-label="Recent events"></div>
</div>
<div id="controlsPanel" class="panel">
<div class="controls-title">
<span>ANIMATION CONTROLS</span>
<span>1–4 actions · X interrupt · R reset</span>
</div>
<div id="buttons">
<button data-action="walk">Walk</button>
<button data-action="reach">Reach</button>
<button data-action="carry">Pick Up</button>
<button data-action="return">Return</button>
<button data-action="interrupt">Interrupt</button>
<button data-action="auto">Auto Demo</button>
<button data-action="reset">Reset</button>
</div>
</div>
<div id="cameraHelp">Drag to orbit · Scroll to zoom</div>
<div id="interruptFlash"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, camera, and lights
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color("#dbeafe");
scene.fog = new THREE.Fog("#dbeafe", 17, 30);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
document.body.prepend(renderer.domElement);
const camera = new THREE.OrthographicCamera(-6, 6, 4, -4, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.85, -0.35);
let cameraYaw = 0.72;
let cameraPitch = 0.62;
const cameraRadius = 15;
function updateCamera() {
const horizontal = Math.cos(cameraPitch) * cameraRadius;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
updateCamera();
scene.add(new THREE.HemisphereLight("#f0f9ff", "#64748b", 2.1));
const sun = new THREE.DirectionalLight("#fff7d6", 3.1);
sun.position.set(6, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0006;
scene.add(sun);
const fill = new THREE.DirectionalLight("#bfdbfe", 0.9);
fill.position.set(-6, 5, -2);
scene.add(fill);
// -------------------------------------------------------------------------
// Small voxel construction helpers
// -------------------------------------------------------------------------
const materialCache = new Map();
function material(color) {
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0.0,
flatShading: true
})
);
}
return materialCache.get(color);
}
function box(parent, width, height, depth, color, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
typeof color === "number" ? new THREE.MeshStandardMaterial({ color }) : material(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Voxel shop interior
// -------------------------------------------------------------------------
const shop = new THREE.Group();
scene.add(shop);
box(shop, 10.3, 0.24, 8.3, "#334155", 0, -0.15, 0);
const tileColors = ["#d6d3d1", "#cbd5e1", "#e2e8f0", "#cbd5e1"];
for (let x = 0; x < 10; x++) {
for (let z = 0; z < 8; z++) {
const color = tileColors[(x * 3 + z * 5) % tileColors.length];
box(
shop,
0.97,
0.06,
0.97,
color,
-4.5 + x,
0,
-3.5 + z
);
}
}
// Back and left walls.
box(shop, 10.2, 4.1, 0.25, "#d7c7a5", 0, 2.02, -4.0);
box(shop, 0.25, 4.1, 8.0, "#cbb995", -5.0, 2.02, 0);
// Wall trim and decorative blocks.
box(shop, 9.7, 0.16, 0.12, "#8b5e3c", 0, 0.32, -3.84);
box(shop, 9.7, 0.13, 0.12, "#8b5e3c", 0, 3.68, -3.84);
box(shop, 0.12, 0.14, 7.7, "#8b5e3c", -4.84, 0.32, 0);
for (let x = -4; x <= 4; x += 1) {
box(shop, 0.94, 0.5, 0.055, x % 2 ? "#dfd0b3" : "#d4c29e", x, 0.73, -3.84);
}
// Counter.
box(shop, 4.6, 0.9, 1.1, "#8b5e3c", 0.55, 0.5, -2.55);
box(shop, 4.8, 0.16, 1.3, "#f1d4a3", 0.55, 1.08, -2.55);
for (let x = -1; x <= 2; x += 1) {
box(shop, 0.86, 0.67, 0.07, x % 2 ? "#a66c43" : "#966039", x, 0.53, -1.96);
}
// Counter register.
box(shop, 0.65, 0.35, 0.48, "#334155", 2.1, 1.34, -2.58);
box(shop, 0.5, 0.28, 0.08, "#7dd3fc", 2.1, 1.64, -2.75);
box(shop, 0.7, 0.08, 0.55, "#475569", 2.1, 1.2, -2.58);
// Shelves on the back wall.
box(shop, 3.5, 0.12, 0.55, "#8b5e3c", -2.75, 1.45, -3.58);
box(shop, 3.5, 0.12, 0.55, "#8b5e3c", -2.75, 2.45, -3.58);
const shelfColors = ["#f59e0b", "#34d399", "#60a5fa", "#fb7185", "#a78bfa"];
for (let row = 0; row < 2; row++) {
for (let i = 0; i < 6; i++) {
const height = 0.28 + ((i + row) % 3) * 0.08;
box(
shop,
0.34,
height,
0.32,
shelfColors[(i + row * 2) % shelfColors.length],
-4.1 + i * 0.52,
1.51 + row + height / 2,
-3.57
);
}
}
// Shop sign generated locally with a canvas texture.
const signCanvas = document.createElement("canvas");
signCanvas.width = 768;
signCanvas.height = 192;
const signContext = signCanvas.getContext("2d");
signContext.fillStyle = "#243447";
signContext.fillRect(0, 0, signCanvas.width, signCanvas.height);
signContext.fillStyle = "#f8d58a";
signContext.fillRect(16, 16, signCanvas.width - 32, signCanvas.height - 32);
signContext.fillStyle = "#243447";
signContext.textAlign = "center";
signContext.textBaseline = "middle";
signContext.font = "bold 66px monospace";
signContext.fillText("TINY GOODS", signCanvas.width / 2, 70);
signContext.font = "bold 27px monospace";
signContext.fillText("PICK / CARRY / RETURN", signCanvas.width / 2, 132);
const signTexture = new THREE.CanvasTexture(signCanvas);
signTexture.colorSpace = THREE.SRGBColorSpace;
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(3.5, 0.875),
new THREE.MeshBasicMaterial({ map: signTexture })
);
sign.position.set(0.35, 2.9, -3.82);
shop.add(sign);
// Entrance mat and delivery table.
box(shop, 1.65, 0.035, 1.15, "#0f766e", -3.2, 0.055, 2.55);
box(shop, 1.15, 0.12, 0.9, "#a66c43", -3.85, 0.37, 1.3);
box(shop, 0.16, 0.34, 0.16, "#6b4428", -4.25, 0.2, 1.05);
box(shop, 0.16, 0.34, 0.16, "#6b4428", -3.45, 0.2, 1.05);
box(shop, 0.16, 0.34, 0.16, "#6b4428", -4.25, 0.2, 1.55);
box(shop, 0.16, 0.34, 0.16, "#6b4428", -3.45, 0.2, 1.55);
// Plant.
box(shop, 0.55, 0.55, 0.55, "#c27649", 4.05, 0.3, -2.75);
box(shop, 0.12, 0.8, 0.12, "#4d7c0f", 4.05, 0.92, -2.75);
box(shop, 0.55, 0.22, 0.25, "#65a30d", 3.82, 1.25, -2.75);
box(shop, 0.48, 0.2, 0.22, "#84cc16", 4.26, 1.08, -2.75);
box(shop, 0.4, 0.18, 0.2, "#4d7c0f", 3.95, 1.47, -2.75);
// Small voxel stool.
box(shop, 0.7, 0.14, 0.7, "#f59e0b", 3.25, 0.72, -0.9);
box(shop, 0.12, 0.65, 0.12, "#92400e", 3.03, 0.37, -0.9);
box(shop, 0.12, 0.65, 0.12, "#92400e", 3.47, 0.37, -0.9);
box(shop, 0.12, 0.65, 0.12, "#92400e", 3.25, 0.37, -0.62);
box(shop, 0.12, 0.65, 0.12, "#92400e", 3.25, 0.37, -1.18);
// Hanging cube lamps.
for (const x of [-2.1, 2.1]) {
box(shop, 0.06, 0.9, 0.06, "#475569", x, 3.45, -0.2);
box(shop, 0.48, 0.28, 0.48, "#fbbf24", x, 2.9, -0.2);
box(shop, 0.3, 0.05, 0.3, "#fff7cc", x, 2.74, -0.2);
}
// -------------------------------------------------------------------------
// Parcel that moves between counter, hand, and delivery table
// -------------------------------------------------------------------------
const parcel = new THREE.Group();
box(parcel, 0.44, 0.34, 0.36, "#f97316");
box(parcel, 0.09, 0.355, 0.375, "#fde68a", 0, 0, 0);
box(parcel, 0.455, 0.07, 0.375, "#fde68a", 0, 0, 0);
const PARCEL_START = new THREE.Vector3(0.55, 1.31, -1.92);
const PARCEL_DELIVERY = new THREE.Vector3(-3.85, 0.56, 1.3);
parcel.position.copy(PARCEL_START);
parcel.rotation.y = 0.08;
shop.add(parcel);
function attachParcelToHand() {
if (parcel.parent !== characterRig.carryAnchor) {
characterRig.carryAnchor.add(parcel);
}
parcel.position.set(0, 0, 0);
parcel.rotation.set(0, 0, 0);
parcel.scale.setScalar(1);
}
function resetParcelToCounter() {
if (parcel.parent !== scene) {
scene.attach(parcel);
}
parcel.position.copy(PARCEL_START);
parcel.rotation.set(0, 0.08, 0);
parcel.scale.setScalar(1);
}
// -------------------------------------------------------------------------
// Voxel shopkeeper
// -------------------------------------------------------------------------
function createCharacter() {
const root = new THREE.Group();
const upper = new THREE.Group();
root.add(upper);
const leftLeg = new THREE.Group();
const rightLeg = new THREE.Group();
leftLeg.position.set(-0.18, 0.58, 0);
rightLeg.position.set(0.18, 0.58, 0);
root.add(leftLeg, rightLeg);
box(leftLeg, 0.23, 0.45, 0.25, "#334155", 0, -0.225, 0);
box(rightLeg, 0.23, 0.45, 0.25, "#334155", 0, -0.225, 0);
box(leftLeg, 0.27, 0.12, 0.38, "#111827", 0, -0.48, 0.055);
box(rightLeg, 0.27, 0.12, 0.38, "#111827", 0, -0.48, 0.055);
// Torso and apron.
box(upper, 0.68, 0.7, 0.4, "#38bdf8", 0, 0.94, 0);
box(upper, 0.54, 0.58, 0.08, "#f8fafc", 0, 0.82, 0.235);
box(upper, 0.16, 0.44, 0.03, "#fbbf24", 0, 0.99, 0.29);
box(upper, 0.7, 0.12, 0.43, "#0284c7", 0, 0.61, 0);
// Neck and head.
box(upper, 0.2, 0.15, 0.2, "#f2c6a0", 0, 1.35, 0);
box(upper, 0.58, 0.52, 0.52, "#f2c6a0", 0, 1.62, 0);
box(upper, 0.61, 0.16, 0.55, "#3f2d24", 0, 1.88, -0.01);
box(upper, 0.16, 0.25, 0.18, "#3f2d24", -0.27, 1.91, -0.03);
box(upper, 0.16, 0.25, 0.18, "#3f2d24", 0.27, 1.91, -0.03);
// Face points toward local +Z.
box(upper, 0.08, 0.09, 0.035, "#1e293b", -0.13, 1.66, 0.273);
box(upper, 0.08, 0.09, 0.035, "#1e293b", 0.13, 1.66, 0.273);
box(upper, 0.14, 0.06, 0.07, "#f59e0b", 0, 1.55, 0.28);
box(upper, 0.13, 0.045, 0.03, "#9a3412", 0, 1.46, 0.27);
// Arms.
const leftArm = new THREE.Group();
const rightArm = new THREE.Group();
leftArm.position.set(-0.43, 1.18, 0);
rightArm.position.set(0.43, 1.18, 0);
upper.add(leftArm, rightArm);
box(leftArm, 0.19, 0.48, 0.22, "#38bdf8", 0, -0.24, 0);
box(rightArm, 0.19, 0.48, 0.22, "#38bdf8", 0, -0.24, 0);
box(leftArm, 0.21, 0.17, 0.24, "#f2c6a0", 0, -0.52, 0);
box(rightArm, 0.21, 0.17, 0.24, "#f2c6a0", 0, -0.52, 0);
const carryAnchor = new THREE.Group();
carryAnchor.position.set(0.42, 0.98, 0.38);
upper.add(carryAnchor);
return {
root,
upper,
leftLeg,
rightLeg,
leftArm,
rightArm,
carryAnchor
};
}
const characterRig = createCharacter();
const character = characterRig.root;
scene.add(character);
const START_POSITION = new THREE.Vector3(-3.2, 0, 2.55);
const COUNTER_POSITION = new THREE.Vector3(0.55, 0, -1.1);
character.position.copy(START_POSITION);
character.rotation.y = 0.25;
// -------------------------------------------------------------------------
// Animation state machine
// -------------------------------------------------------------------------
const STATES = {
WAITING: {
label: "WAITING",
hint: "Idle near the entrance",
color: "#7dd3fc"
},
WALKING: {
label: "WALKING",
hint: "Moving toward the counter",
color: "#a7f3d0"
},
REACHING: {
label: "REACHING",
hint: "Arm extended toward the parcel",
color: "#fde68a"
},
CARRYING: {
label: "CARRYING",
hint: "Parcel secured in both hands",
color: "#fdba74"
},
RETURNING: {
label: "RETURNING",
hint: "Carrying the parcel back to the entrance",
color: "#f9a8d4"
}
};
const stateOrder = [
"WAITING",
"WALKING",
"REACHING",
"CARRYING",
"RETURNING"
];
const stateName = document.querySelector("#stateName");
const stateHint = document.querySelector("#stateHint");
const lockPill = document.querySelector("#lockPill");
const message = document.querySelector("#message");
const eventLog = document.querySelector("#eventLog");
const interruptFlash = document.querySelector("#interruptFlash");
const timelineSteps = [...document.querySelectorAll(".timeline-step")];
const buttons = [...document.querySelectorAll("button[data-action]")];
let currentState = "WAITING";
let busy = false;
let action = null;
let autoRunning = false;
let autoToken = 0;
function setState(nextState) {
currentState = nextState;
updateUI();
}
function say(text, tone = "info") {
message.textContent = text;
message.dataset.tone = tone;
const entry = document.createElement("div");
const time = new Date().toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
entry.textContent = `${time} ${text}`;
eventLog.prepend(entry);
while (eventLog.children.length > 4) {
eventLog.lastElementChild.remove();
}
}
function isActionAllowed(type) {
if (busy || autoRunning) return false;
switch (type) {
case "walk": return currentState === "WAITING";
case "reach": return currentState === "WALKING";
case "carry": return currentState === "REACHING";
case "return": return currentState === "CARRYING";
default: return false;
}
}
function updateUI() {
const meta = STATES[currentState];
document.documentElement.style.setProperty("--state", meta.color);
stateName.textContent = meta.label;
stateHint.textContent = meta.hint;
lockPill.dataset.locked = String(busy || autoRunning);
if (busy) {
lockPill.textContent = "Action locked";
} else if (autoRunning) {
lockPill.textContent = "Auto locked";
} else {
lockPill.textContent = "Ready";
}
const currentIndex = stateOrder.indexOf(currentState);
timelineSteps.forEach((step, index) => {
step.classList.toggle("current", index === currentIndex);
step.classList.toggle("passed", index < currentIndex);
});
buttons.forEach((button) => {
const type = button.dataset.action;
let allowed = false;
if (type === "interrupt") {
allowed = busy || autoRunning;
} else if (type === "auto") {
allowed = currentState === "WAITING" && !busy && !autoRunning;
} else if (type === "reset") {
allowed = true;
} else {
allowed = isActionAllowed(type);
}
button.classList.toggle("allowed", allowed);
button.classList.toggle("locked", !allowed);
button.setAttribute("aria-disabled", String(!allowed));
});
const autoButton = buttons.find((button) => button.dataset.action === "auto");
autoButton.textContent = autoRunning ? "Running…" : "Auto Demo";
}
function smoothstep(t) {
t = THREE.MathUtils.clamp(t, 0, 1);
return t * t * (3 - 2 * t);
}
function easeOutCubic(t) {
return 1 - Math.pow(1 - THREE.MathUtils.clamp(t, 0, 1), 3);
}
function lerpAngle(a, b, t) {
const difference = Math.atan2(Math.sin(b - a), Math.cos(b - a));
return a + difference * t;
}
function actionRequirement(type) {
switch (type) {
case "walk": return "WAITING";
case "reach": return "WALKING";
case "carry": return "REACHING";
case "return": return "CARRYING";
default: return "";
}
}
async function requestAction(type, fromAuto = false) {
if (!fromAuto && autoRunning) {
say("Blocked: the auto routine owns the timeline. Interrupt it first.", "warn");
return { completed: false };
}
if (busy) {
say(
`Blocked: a ${STATES[currentState].label.toLowerCase()} animation already owns the timeline.`,
"warn"
);
return { completed: false };
}
const requiredState = actionRequirement(type);
if (currentState !== requiredState) {
say(
`Blocked: ${type.toUpperCase()} requires ${requiredState}. Finish the previous action first.`,
"warn"
);
return { completed: false };
}
const snapshot = {
armR: characterRig.rightArm.rotation.x,
armL: characterRig.leftArm.rotation.x,
legR: characterRig.rightLeg.rotation.x,
legL: characterRig.leftLeg.rotation.x
};
busy = true;
if (type === "walk") {
const destination = COUNTER_POSITION.clone();
const direction = destination.clone().sub(character.position);
const targetYaw = Math.atan2(direction.x, direction.z);
action = {
type,
elapsed: 0,
duration: 2.45,
start: character.position.clone(),
target: destination,
startYaw: character.rotation.y,
targetYaw,
snapshot,
resolve: null
};
setState("WALKING");
say("Walking to the counter. Other actions are locked.", "info");
} else if (type === "reach") {
action = {
type,
elapsed: 0,
duration: 0.95,
snapshot,
resolve: null
};
setState("REACHING");
say("Reaching for the parcel. The timeline remains exclusively locked.", "info");
} else if (type === "carry") {
action = {
type,
elapsed: 0,
duration: 0.85,
snapshot,
attached: false,
resolve: null
};
setState("CARRYING");
say("Picking up the parcel and settling into the carrying pose.", "info");
} else if (type === "return") {
const destination = START_POSITION.clone();
const direction = destination.clone().sub(character.position);
const targetYaw = Math.atan2(direction.x, direction.z);
action = {
type,
elapsed: 0,
duration: 2.85,
start: character.position.clone(),
target: destination,
startYaw: character.rotation.y,
targetYaw,
snapshot,
deliveryStarted: false,
deliveryStart: new THREE.Vector3(),
resolve: null
};
setState("RETURNING");
say("Returning to the entrance while carrying the parcel.", "info");
}
updateUI();
return new Promise((resolve) => {
action.resolve = resolve;
});
}
function completeAction(currentAction) {
if (action !== currentAction) return;
if (currentAction.type === "walk") {
character.position.copy(currentAction.target);
character.position.y = 0;
character.rotation.y = currentAction.targetYaw;
characterRig.leftLeg.rotation.x = 0;
characterRig.rightLeg.rotation.x = 0;
setState("WALKING");
say("Walk complete. REACH is now available.", "success");
} else if (currentAction.type === "reach") {
characterRig.rightArm.rotation.x = -1.42;
setState("REACHING");
say("Reach complete. PICK UP is now available.", "success");
} else if (currentAction.type === "carry") {
attachParcelToHand();
characterRig.rightArm.rotation.x = -0.48;
characterRig.leftArm.rotation.x = -0.25;
setState("CARRYING");
say("Parcel secured. RETURN is now available.", "success");
} else if (currentAction.type === "return") {
character.position.copy(currentAction.target);
character.position.y = 0;
character.rotation.y = currentAction.targetYaw;
parcel.position.copy(PARCEL_DELIVERY);
parcel.rotation.set(0, 0.08, 0);
setState("WAITING");
say("Parcel delivered. The shopkeeper is waiting again.", "success");
}
action = null;
busy = false;
updateUI();
if (currentAction.resolve) {
currentAction.resolve({ completed: true });
}
}
function interruptAction() {
if (!busy && !autoRunning) {
say("Nothing is running, so there is no action to interrupt.", "info");
return;
}
const interrupted = action;
const interruptedType = interrupted?.type;
autoToken++;
autoRunning = false;
if (interrupted) {
action = null;
busy = false;
if (interruptedType === "walk") {
character.position.y = 0;
characterRig.leftLeg.rotation.x = 0;
characterRig.rightLeg.rotation.x = 0;
setState("WAITING");
} else if (interruptedType === "reach") {
setState("WALKING");
} else if (interruptedType === "carry") {
resetParcelToCounter();
setState("REACHING");
} else if (interruptedType === "return") {
attachParcelToHand();
setState("CARRYING");
}
if (interrupted.resolve) {
interrupted.resolve({ completed: false, interrupted: true });
}
}
interruptFlash.classList.remove("active");
void interruptFlash.offsetWidth;
interruptFlash.classList.add("active");
say(
"Interrupted safely. The current action was canceled and the state was recovered.",
"error"
);
updateUI();
}
function resetScene() {
const oldAction = action;
autoToken++;
autoRunning = false;
busy = false;
action = null;
if (oldAction?.resolve) {
oldAction.resolve({ completed: false, interrupted: true });
}
resetParcelToCounter();
character.position.copy(START_POSITION);
character.rotation.set(0, 0.25, 0);
characterRig.upper.position.y = 0;
characterRig.upper.rotation.x = 0;
characterRig.leftArm.rotation.x = 0;
characterRig.rightArm.rotation.x = 0;
characterRig.leftLeg.rotation.x = 0;
characterRig.rightLeg.rotation.x = 0;
setState("WAITING");
say("Scene reset. The character and parcel are back at their starting positions.");
}
async function playRoutine() {
if (busy || autoRunning || currentState !== "WAITING") {
say("Auto demo requires an idle WAITING state. Interrupt or reset first.", "warn");
return;
}
const token = ++autoToken;
autoRunning = true;
updateUI();
say("Auto routine started: walk → reach → carry → return.", "info");
const routine = ["walk", "reach", "carry", "return"];
for (const type of routine) {
const result = await requestAction(type, true);
if (!result.completed || token !== autoToken) break;
await new Promise((resolve) => setTimeout(resolve, 430));
if (token !== autoToken) break;
}
if (token === autoToken) {
autoRunning = false;
updateUI();
if (currentState === "WAITING") {
say("Auto routine complete. All five animation states were demonstrated.", "success");
} else {
say("Auto routine paused.", "warn");
}
}
}
buttons.forEach((button) => {
button.addEventListener("click", () => {
const type = button.dataset.action;
if (type === "interrupt") {
interruptAction();
} else if (type === "reset") {
resetScene();
} else if (type === "auto") {
playRoutine();
} else {
requestAction(type);
}
});
});
window.addEventListener("keydown", (event) => {
if (event.repeat) return;
const key = event.key.toLowerCase();
if (key === "1") requestAction("walk");
else if (key === "2") requestAction("reach");
else if (key === "3") requestAction("carry");
else if (key === "4") requestAction("return");
else if (key === "x") interruptAction();
else if (key === "r") resetScene();
});
// -------------------------------------------------------------------------
// Procedural animation
// -------------------------------------------------------------------------
function updateBasePose(delta, time) {
let targetArmR = 0;
let targetArmL = 0;
let targetUpperX = 0;
if (currentState === "REACHING") {
targetArmR = -1.42;
targetUpperX = 0.055;
} else if (currentState === "CARRYING" || currentState === "RETURNING") {
targetArmR = -0.48;
targetArmL = -0.25;
targetUpperX = 0.025;
}
const damping = 1 - Math.exp(-delta * 12);
characterRig.rightArm.rotation.x = THREE.MathUtils.lerp(
characterRig.rightArm.rotation.x,
targetArmR,
damping
);
characterRig.leftArm.rotation.x = THREE.MathUtils.lerp(
characterRig.leftArm.rotation.x,
targetArmL,
damping
);
characterRig.upper.rotation.x = THREE.MathUtils.lerp(
characterRig.upper.rotation.x,
targetUpperX,
damping
);
const idleBob =
currentState === "WAITING" && !busy
? Math.sin(time * 2.1) * 0.012
: 0;
characterRig.upper.position.y = THREE.MathUtils.lerp(
characterRig.upper.position.y,
idleBob,
damping
);
}
function updateAction(delta) {
if (!action) return;
const currentAction = action;
currentAction.elapsed += delta;
const progress = THREE.MathUtils.clamp(
currentAction.elapsed / currentAction.duration,
0,
1
);
if (currentAction.type === "walk") {
const eased = smoothstep(progress);
character.position.lerpVectors(currentAction.start, currentAction.target, eased);
const walkCycle = progress * Math.PI * 8;
character.position.y = Math.sin(walkCycle) * 0.035;
character.rotation.y = lerpAngle(
currentAction.startYaw,
currentAction.targetYaw,
eased
);
characterRig.leftLeg.rotation.x = Math.sin(walkCycle) * 0.56;
characterRig.rightLeg.rotation.x = -Math.sin(walkCycle) * 0.56;
characterRig.leftArm.rotation.x = -Math.sin(walkCycle) * 0.28;
characterRig.rightArm.rotation.x = Math.sin(walkCycle) * 0.28;
characterRig.upper.position.y = Math.abs(Math.sin(walkCycle)) * 0.025;
if (progress >= 1) completeAction(currentAction);
} else if (currentAction.type === "reach") {
const eased = easeOutCubic(progress);
characterRig.rightArm.rotation.x = THREE.MathUtils.lerp(
currentAction.snapshot.armR,
-1.42,
eased
);
characterRig.leftArm.rotation.x = THREE.MathUtils.lerp(
currentAction.snapshot.armL,
-0.08,
eased
);
characterRig.upper.rotation.x = Math.sin(progress * Math.PI) * 0.07;
if (progress >= 1) completeAction(currentAction);
} else if (currentAction.type === "carry") {
const eased = easeOutCubic(progress);
characterRig.rightArm.rotation.x = THREE.MathUtils.lerp(
currentAction.snapshot.armR,
-0.48,
eased
);
characterRig.leftArm.rotation.x = THREE.MathUtils.lerp(
currentAction.snapshot.armL,
-0.25,
eased
);
if (!currentAction.attached && progress > 0.3) {
currentAction.attached = true;
if (parcel.parent !== characterRig.carryAnchor) {
characterRig.carryAnchor.add(parcel);
}
parcel.position.set(0, 0, 0);
parcel.rotation.set(0, 0, 0);
parcel.scale.setScalar(0.35);
}
if (currentAction.attached) {
parcel.scale.setScalar(THREE.MathUtils.lerp(0.35, 1, eased));
}
if (progress >= 1) completeAction(currentAction);
} else if (currentAction.type === "return") {
const eased = smoothstep(progress);
character.position.lerpVectors(currentAction.start, currentAction.target, eased);
const walkCycle = progress * Math.PI * 8;
character.position.y = Math.sin(walkCycle) * 0.03;
character.rotation.y = lerpAngle(
currentAction.startYaw,
currentAction.targetYaw,
eased
);
characterRig.leftLeg.rotation.x = Math.sin(walkCycle) * 0.48;
characterRig.rightLeg.rotation.x = -Math.sin(walkCycle) * 0.48;
characterRig.upper.position.y = Math.abs(Math.sin(walkCycle)) * 0.022;
// Near the end, place the parcel onto the delivery table.
if (progress > 0.78) {
if (!currentAction.deliveryStarted) {
currentAction.deliveryStarted = true;
if (parcel.parent !== scene) {
scene.attach(parcel);
}
currentAction.deliveryStart.copy(parcel.position);
}
const deliveryProgress = smoothstep((progress - 0.78) / 0.22);
parcel.position.lerpVectors(
currentAction.deliveryStart,
PARCEL_DELIVERY,
deliveryProgress
);
parcel.rotation.y = THREE.MathUtils.lerp(0, 0.08, deliveryProgress);
}
if (progress >= 1) completeAction(currentAction);
}
}
// -------------------------------------------------------------------------
// Direct camera controls: no external controls addon
// -------------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(cameraPitch + deltaY * 0.005, 0.25, 1.2);
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.style.cursor = "grab";
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * (event.deltaY > 0 ? 0.9 : 1.1),
0.65,
1.7
);
camera.updateProjectionMatrix();
},
{ passive: false }
);
renderer.domElement.style.cursor = "grab";
renderer.domElement.addEventListener("dblclick", () => {
cameraYaw = 0.72;
cameraPitch = 0.62;
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
});
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
const verticalSize = aspect < 0.8 ? 9 : 6.8;
camera.left = (-verticalSize * aspect) / 2;
camera.right = (verticalSize * aspect) / 2;
camera.top = verticalSize / 2;
camera.bottom = -verticalSize / 2;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const time = clock.elapsedTime;
updateBasePose(delta, time);
updateAction(delta);
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
updateUI();
say("Ready. Try WALK, or select AUTO DEMO to run the complete routine.");
</script>
</body>
</html>
```