Prompt specification
Build or customize the Three.js 3D scene "Interrupted Action Recovery" 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: Interrupted Action Recovery
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/interrupted-action-recovery-x3688
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts character animation states and interrupted actions. Create a character task where a new goal arrives during a carry animation. Transition to a valid safe pose, preserve the carried object's attachment, and resume without teleportation. Voxel style.
Working Three.js Starter (interrupted-action-recovery-x3688):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Task Interruption</title>
<style>
:root {
color-scheme: dark;
--bg: #101624;
--panel: rgba(19, 27, 43, 0.9);
--border: rgba(148, 163, 184, 0.2);
--text: #edf5ff;
--muted: #91a0b8;
--cyan: #58e0dc;
--amber: #ffbd59;
--green: #75e09b;
--pink: #ff6fae;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
}
#hud {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(390px, calc(100vw - 36px));
padding: 18px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
pointer-events: none;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 6px 0 3px;
font-size: 23px;
line-height: 1.1;
}
.subtitle {
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.state-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 16px;
}
#stateDot {
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 18px var(--cyan);
flex: 0 0 auto;
}
#stateName {
font-size: 14px;
font-weight: 800;
}
#stateDetail {
margin: 8px 0 0 20px;
min-height: 32px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
.metric {
padding: 10px 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
margin-top: 4px;
font-size: 12px;
font-weight: 700;
}
#attachmentValue {
color: var(--green);
}
.timeline {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 5px;
margin-top: 15px;
}
.phase {
height: 5px;
border-radius: 99px;
background: rgba(148, 163, 184, 0.16);
transition: background 180ms ease, box-shadow 180ms ease;
}
.phase.done {
background: rgba(88, 224, 220, 0.38);
}
.phase.active {
background: var(--cyan);
box-shadow: 0 0 12px rgba(88, 224, 220, 0.75);
}
.phase-labels {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 5px;
margin-top: 6px;
color: #75849a;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: center;
text-transform: uppercase;
}
#controls {
position: fixed;
z-index: 20;
right: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: calc(100vw - 36px);
}
button {
border: 1px solid var(--border);
border-radius: 11px;
padding: 11px 14px;
background: rgba(20, 29, 45, 0.92);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 800;
cursor: pointer;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(12px);
}
button:hover:not(:disabled) {
border-color: rgba(88, 224, 220, 0.55);
transform: translateY(-1px);
}
button.primary {
border-color: rgba(88, 224, 220, 0.48);
background: rgba(38, 113, 112, 0.78);
}
button.priority {
border-color: rgba(255, 111, 174, 0.55);
background: rgba(117, 38, 76, 0.8);
}
button:disabled {
cursor: default;
opacity: 0.4;
}
#toast {
position: fixed;
z-index: 30;
top: 24px;
left: 50%;
max-width: min(520px, calc(100vw - 32px));
padding: 13px 18px;
border: 1px solid rgba(255, 111, 174, 0.45);
border-radius: 12px;
background: rgba(52, 20, 40, 0.94);
color: #ffe9f3;
font-size: 13px;
font-weight: 750;
text-align: center;
box-shadow: 0 15px 50px rgba(0, 0, 0, 0.38);
transform: translate(-50%, -140%);
opacity: 0;
pointer-events: none;
transition:
transform 280ms cubic-bezier(0.2, 0.8, 0.2, 1),
opacity 280ms ease;
}
#toast.show {
transform: translate(-50%, 0);
opacity: 1;
}
.world-label {
position: fixed;
z-index: 8;
min-width: 110px;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 9px;
background: rgba(13, 19, 31, 0.86);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.25);
color: white;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
text-align: center;
text-transform: uppercase;
pointer-events: none;
transform: translate(-50%, -100%);
}
.world-label small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.1em;
}
#goalALabel {
border-color: rgba(255, 189, 89, 0.45);
}
#goalBLabel {
border-color: rgba(255, 111, 174, 0.55);
}
#crateLabel {
min-width: 135px;
border-color: rgba(117, 224, 155, 0.48);
color: var(--green);
}
#cameraHint {
position: fixed;
z-index: 10;
left: 18px;
bottom: 18px;
padding: 8px 10px;
border-radius: 8px;
background: rgba(15, 22, 35, 0.64);
color: #8190a6;
font-size: 10px;
pointer-events: none;
}
@media (max-width: 700px) {
#hud {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px;
}
h1 {
font-size: 19px;
}
.subtitle,
#stateDetail {
font-size: 11px;
}
.metrics {
margin-top: 10px;
}
#controls {
right: 10px;
bottom: 10px;
}
#cameraHint {
display: none;
}
}
</style>
</head>
<body>
<section id="hud">
<div class="eyebrow">Interrupt-aware locomotion</div>
<h1>Voxel Courier / Task 07</h1>
<div class="subtitle">
Carry the supply crate to Line A. A replacement order will arrive during
transit and safely redirect the character.
</div>
<div class="state-row">
<span id="stateDot"></span>
<span id="stateName">CARRYING TO LINE A</span>
</div>
<div id="stateDetail">
Continuous velocity is building while the crate remains attached to the
carry socket.
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">Crate attachment</div>
<div class="metric-value" id="attachmentValue">LOCKED TO SOCKET</div>
</div>
<div class="metric">
<div class="metric-label">Root velocity</div>
<div class="metric-value" id="velocityValue">0.00 m/s</div>
</div>
</div>
<div class="timeline">
<div class="phase" data-phase="0"></div>
<div class="phase" data-phase="1"></div>
<div class="phase" data-phase="2"></div>
<div class="phase" data-phase="3"></div>
<div class="phase" data-phase="4"></div>
</div>
<div class="phase-labels">
<span>Carry</span>
<span>Brake</span>
<span>Brace</span>
<span>Resume</span>
<span>Place</span>
</div>
</section>
<div id="controls">
<button id="pauseButton">Pause</button>
<button id="injectButton" class="priority">Inject New Request</button>
<button id="replayButton" class="primary">Replay</button>
</div>
<div id="toast"></div>
<div id="goalALabel" class="world-label">
Order 01
<small>Line A</small>
</div>
<div id="goalBLabel" class="world-label" style="display: none">
New Order 02
<small>Line B</small>
</div>
<div id="crateLabel" class="world-label">
Supply Crate
<small>Attachment locked</small>
</div>
<div id="cameraHint">Drag to orbit · Wheel to zoom · Double-click to reset view</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, and camera
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101624);
scene.fog = new THREE.Fog(0x101624, 13, 27);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
80
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbdd7ff, 0x283046, 2.2);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d8, 3.2);
sun.position.set(-5, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x58e0dc, 1.1);
rim.position.set(7, 5, -8);
scene.add(rim);
// Camera controls are implemented directly without Three.js addons.
const orbit = {
theta: 0.69,
phi: 1.03,
radius: 15.6,
target: new THREE.Vector3(-0.2, 0.75, -0.75)
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
updateCamera();
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
orbit.theta -= dx * 0.007;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.006, 0.35, 1.42);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (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();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.012,
8,
24
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
orbit.theta = 0.69;
orbit.phi = 1.03;
orbit.radius = 15.6;
orbit.target.set(-0.2, 0.75, -0.75);
updateCamera();
});
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
const materialCache = new Map();
function standardMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.05,
flatShading: true
})
);
}
return materialCache.get(color);
}
function addBox(parent, size, position, color, options = {}) {
const material =
options.material ||
(typeof color === "number"
? standardMaterial(color)
: color);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = options.castShadow !== false;
mesh.receiveShadow = options.receiveShadow !== false;
parent.add(mesh);
return mesh;
}
function damp(current, target, lambda, dt) {
return THREE.MathUtils.lerp(
current,
target,
1 - Math.exp(-lambda * dt)
);
}
function dampAngle(current, target, lambda, dt) {
const delta = Math.atan2(
Math.sin(target - current),
Math.cos(target - current)
);
return current + delta * (1 - Math.exp(-lambda * dt));
}
// -------------------------------------------------------------------------
// Environment
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(20, 16),
standardMaterial(0x263247)
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(20, 20, 0x52627a, 0x344158);
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
// Supply station.
addBox(scene, [2.8, 0.28, 2.1], [-5.4, 0.14, 1.3], 0x34435a);
addBox(scene, [2.2, 0.14, 1.55], [-5.4, 0.34, 1.3], 0x52647e);
addBox(scene, [0.18, 1.7, 0.18], [-6.5, 1.13, 0.45], 0x65758c);
addBox(scene, [0.18, 1.7, 0.18], [-4.3, 1.13, 0.45], 0x65758c);
addBox(scene, [2.4, 0.18, 1.3], [-5.4, 1.98, 0.45], 0x65758c);
// Voxel shelving at the back.
const shelf = new THREE.Group();
shelf.position.set(3.2, 0, -6.0);
scene.add(shelf);
addBox(shelf, [4.8, 0.18, 1.5], [0, 0.2, 0], 0x34435a);
addBox(shelf, [4.8, 0.18, 1.5], [0, 1.45, 0], 0x34435a);
addBox(shelf, [4.8, 0.18, 1.5], [0, 2.7, 0], 0x34435a);
addBox(shelf, [0.18, 3.0, 1.5], [-2.3, 1.5, 0], 0x4c5c73);
addBox(shelf, [0.18, 3.0, 1.5], [2.3, 1.5, 0], 0x4c5c73);
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 4; col++) {
const boxColor = [0x597d8b, 0xa87952, 0x776b91, 0x5d806c][
(row + col) % 4
];
addBox(
shelf,
[0.65, 0.6, 0.72],
[-1.65 + col * 1.1, 0.6 + row * 1.25, 0.12],
boxColor
);
}
}
// Decorative voxel blocks.
const decorColors = [0x48576d, 0x5b7184, 0x6b5e76];
for (let i = 0; i < 9; i++) {
const h = 0.3 + (i % 3) * 0.18;
addBox(
scene,
[0.55, h, 0.55],
[-7.6 + (i % 3) * 0.8, h / 2, -4.8 + Math.floor(i / 3) * 0.8],
decorColors[i % decorColors.length]
);
}
// -------------------------------------------------------------------------
// Goal pads
// -------------------------------------------------------------------------
function createGoal(position, color) {
const group = new THREE.Group();
group.position.copy(position);
scene.add(group);
const tileMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.75,
metalness: 0.08,
transparent: true,
opacity: 0.92,
emissive: color,
emissiveIntensity: 0.22
});
const beamMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.24,
depthWrite: false
});
const tile = addBox(
group,
[2.0, 0.08, 2.0],
[0, 0.045, 0],
0xffffff,
{ material: tileMaterial }
);
addBox(group, [2.18, 0.08, 0.10], [0, 0.095, -1.02], 0xffffff, {
material: beamMaterial
});
addBox(group, [2.18, 0.08, 0.10], [0, 0.095, 1.02], 0xffffff, {
material: beamMaterial
});
addBox(group, [0.10, 0.08, 2.18], [-1.02, 0.095, 0], 0xffffff, {
material: beamMaterial
});
addBox(group, [0.10, 0.08, 2.18], [1.02, 0.095, 0], 0xffffff, {
material: beamMaterial
});
const beacon = new THREE.Group();
group.add(beacon);
const beaconMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.16,
depthWrite: false
});
for (let i = 0; i < 5; i++) {
const beam = addBox(
beacon,
[0.11, 0.7, 0.11],
[0, 0.5 + i * 0.7, 0],
0xffffff,
{ material: beaconMaterial, castShadow: false }
);
beam.userData.baseY = beam.position.y;
beam.userData.phase = i * 0.6;
}
const point = new THREE.PointLight(color, 1.0, 4.5, 2);
point.position.y = 0.6;
group.add(point);
group.userData.tile = tile;
group.userData.tileMaterial = tileMaterial;
group.userData.beacon = beacon;
group.userData.beaconMaterial = beaconMaterial;
group.userData.point = point;
return group;
}
const goalA = createGoal(
new THREE.Vector3(2.8, 0, 1.3),
0xffbd59
);
const goalB = createGoal(
new THREE.Vector3(3.7, 0, -3.9),
0xff6fae
);
goalB.visible = false;
// -------------------------------------------------------------------------
// Voxel character
// -------------------------------------------------------------------------
const character = new THREE.Group();
scene.add(character);
const hips = new THREE.Group();
hips.position.y = 1.02;
character.add(hips);
addBox(hips, [0.72, 0.25, 0.42], [0, 0, 0], 0x26344c);
const torso = new THREE.Group();
torso.position.y = 1.12;
character.add(torso);
addBox(torso, [0.78, 0.82, 0.48], [0, 0.43, 0], 0xf08a4b);
addBox(torso, [0.79, 0.18, 0.49], [0, 0.22, 0], 0xffc16d);
addBox(torso, [0.58, 0.55, 0.22], [0, 0.47, -0.34], 0x334760);
addBox(torso, [0.16, 0.58, 0.04], [-0.19, 0.48, 0.255], 0xffe0a1);
addBox(torso, [0.16, 0.58, 0.04], [0.19, 0.48, 0.255], 0xffe0a1);
const head = new THREE.Group();
head.position.set(0, 1.02, 0);
torso.add(head);
addBox(head, [0.62, 0.58, 0.58], [0, 0.26, 0], 0xf2bd8f);
addBox(head, [0.66, 0.18, 0.61], [0, 0.55, -0.015], 0x253149);
addBox(head, [0.10, 0.10, 0.05], [-0.15, 0.29, 0.303], 0x172033);
addBox(head, [0.10, 0.10, 0.05], [0.15, 0.29, 0.303], 0x172033);
addBox(head, [0.16, 0.06, 0.04], [0, 0.15, 0.302], 0x9a5e50);
addBox(head, [0.66, 0.12, 0.18], [0, 0.57, 0.22], 0x34445e);
function createLeg(x) {
const pivot = new THREE.Group();
pivot.position.set(x, 1.0, 0);
character.add(pivot);
addBox(pivot, [0.28, 0.44, 0.30], [0, -0.22, 0], 0x34445f);
const knee = new THREE.Group();
knee.position.y = -0.44;
pivot.add(knee);
addBox(knee, [0.25, 0.42, 0.27], [0, -0.21, 0], 0x3f5270);
addBox(knee, [0.30, 0.16, 0.43], [0, -0.43, 0.08], 0x18243a);
return { pivot, knee };
}
const leftLeg = createLeg(-0.22);
const rightLeg = createLeg(0.22);
function createArm(x) {
const pivot = new THREE.Group();
pivot.position.set(x, 0.73, 0);
torso.add(pivot);
addBox(pivot, [0.24, 0.42, 0.27], [0, -0.21, 0], 0xf08a4b);
const elbow = new THREE.Group();
elbow.position.y = -0.42;
pivot.add(elbow);
addBox(elbow, [0.21, 0.38, 0.24], [0, -0.19, 0], 0xe67a40);
addBox(elbow, [0.22, 0.20, 0.24], [0, -0.43, 0], 0xf2bd8f);
return { pivot, elbow };
}
const leftArm = createArm(-0.52);
const rightArm = createArm(0.52);
// The carry socket is a child of the torso. The crate remains a direct
// child of this socket for the entire carry, interruption, and resume.
const carrySocket = new THREE.Group();
carrySocket.position.set(0, 0.34, 0.62);
torso.add(carrySocket);
const crate = new THREE.Group();
carrySocket.add(crate);
addBox(crate, [0.86, 0.72, 0.68], [0, 0, 0], 0x45b9ba);
addBox(crate, [0.12, 0.76, 0.72], [-0.26, 0, 0], 0x2d7f89);
addBox(crate, [0.12, 0.76, 0.72], [0.26, 0, 0], 0x2d7f89);
addBox(crate, [0.90, 0.10, 0.72], [0, 0.31, 0], 0x78d6cc);
addBox(crate, [0.90, 0.10, 0.72], [0, -0.31, 0], 0x78d6cc);
addBox(crate, [0.34, 0.12, 0.12], [0, 0.42, 0], 0x34465f);
// Small grip blocks visually belong to the crate and therefore remain
// attached to it even while the character changes pose.
addBox(crate, [0.16, 0.18, 0.30], [-0.51, -0.08, 0.04], 0xf2bd8f);
addBox(crate, [0.16, 0.18, 0.30], [0.51, -0.08, 0.04], 0xf2bd8f);
// Safe-pose footprint brackets.
const safeHalo = new THREE.Group();
safeHalo.position.y = 0.025;
safeHalo.visible = false;
character.add(safeHalo);
const safeMaterial = new THREE.MeshBasicMaterial({
color: 0x75e09b,
transparent: true,
opacity: 0.8
});
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
addBox(
safeHalo,
[0.38, 0.025, 0.07],
[sx * 0.67, 0, sz * 0.57],
0xffffff,
{ material: safeMaterial, castShadow: false }
);
addBox(
safeHalo,
[0.07, 0.025, 0.38],
[sx * 0.82, 0, sz * 0.42],
0xffffff,
{ material: safeMaterial, castShadow: false }
);
}
}
// Dotted root-motion trail makes continuity visible.
const trailDots = [];
const trailGeometry = new THREE.BoxGeometry(0.075, 0.018, 0.075);
const trailMaterial = new THREE.MeshBasicMaterial({
color: 0x58e0dc,
transparent: true,
opacity: 0.45
});
for (let i = 0; i < 100; i++) {
const dot = new THREE.Mesh(trailGeometry, trailMaterial);
dot.visible = false;
scene.add(dot);
trailDots.push(dot);
}
let trailIndex = 0;
let trailCount = 0;
let lastTrailPosition = new THREE.Vector3();
function addTrailPoint() {
if (lastTrailPosition.distanceTo(character.position) < 0.2) return;
const dot = trailDots[trailIndex];
dot.position.set(
character.position.x,
0.026,
character.position.z
);
dot.visible = true;
trailIndex = (trailIndex + 1) % trailDots.length;
trailCount++;
lastTrailPosition.copy(character.position);
}
// -------------------------------------------------------------------------
// Pose system
// -------------------------------------------------------------------------
const poses = {
carry: {
hipsY: 1.02,
torsoY: 1.12,
torsoX: 0,
headX: 0,
legL: 0,
legR: 0,
kneeL: 0,
kneeR: 0,
spread: 0,
shoulderL: -0.93,
shoulderR: -0.93,
elbowL: -0.10,
elbowR: -0.10,
socketX: 0,
socketY: 0.34,
socketZ: 0.62
},
brace: {
hipsY: 0.78,
torsoY: 0.89,
torsoX: -0.18,
headX: 0.08,
legL: -0.28,
legR: -0.28,
kneeL: 0.72,
kneeR: 0.72,
spread: 0.09,
shoulderL: -1.18,
shoulderR: -1.18,
elbowL: -0.24,
elbowR: -0.24,
socketX: 0,
socketY: 0.38,
socketZ: 0.48
},
place: {
hipsY: 0.84,
torsoY: 0.92,
torsoX: 0.20,
headX: -0.10,
legL: -0.40,
legR: -0.40,
kneeL: 0.88,
kneeR: 0.88,
spread: 0.07,
shoulderL: -1.35,
shoulderR: -1.35,
elbowL: -0.28,
elbowR: -0.28,
socketX: 0,
socketY: -0.38,
socketZ: 0.78
}
};
const poseCurrent = { ...poses.carry };
let walkPhase = 0;
function applyPose(poseName, dt, speed) {
const target = { ...poses[poseName] };
const walking =
(state === "CARRY_A" || state === "CARRY_B")
? THREE.MathUtils.clamp(speed / 1.3, 0, 1)
: 0;
if (walking > 0) {
const stride = Math.sin(walkPhase) * 0.55 * walking;
const oppositeStride = Math.sin(walkPhase + Math.PI) * 0.55 * walking;
target.legL += stride;
target.legR += oppositeStride;
target.kneeL += Math.max(0, -stride) * 0.7;
target.kneeR += Math.max(0, -oppositeStride) * 0.7;
target.shoulderL += oppositeStride * 0.07;
target.shoulderR += stride * 0.07;
}
for (const key of Object.keys(poseCurrent)) {
poseCurrent[key] = damp(poseCurrent[key], target[key], 10, dt);
}
const bob =
walking > 0
? Math.abs(Math.sin(walkPhase)) * 0.035 * walking
: 0;
hips.position.y = poseCurrent.hipsY + bob;
torso.position.y = poseCurrent.torsoY + bob;
torso.rotation.x = poseCurrent.torsoX;
head.rotation.x = poseCurrent.headX;
leftLeg.pivot.position.x = -0.22 - poseCurrent.spread;
rightLeg.pivot.position.x = 0.22 + poseCurrent.spread;
leftLeg.pivot.position.z = -0.05;
rightLeg.pivot.position.z = 0.05;
leftLeg.pivot.rotation.x = poseCurrent.legL;
rightLeg.pivot.rotation.x = poseCurrent.legR;
leftLeg.knee.rotation.x = poseCurrent.kneeL;
rightLeg.knee.rotation.x = poseCurrent.kneeR;
leftArm.pivot.rotation.x = poseCurrent.shoulderL;
rightArm.pivot.rotation.x = poseCurrent.shoulderR;
leftArm.elbow.rotation.x = poseCurrent.elbowL;
rightArm.elbow.rotation.x = poseCurrent.elbowR;
carrySocket.position.set(
poseCurrent.socketX,
poseCurrent.socketY,
poseCurrent.socketZ
);
}
// -------------------------------------------------------------------------
// State machine and continuous path following
// -------------------------------------------------------------------------
const stateOrder = {
CARRY_A: 0,
BRAKING: 1,
SAFE_POSE: 2,
CARRY_B: 3,
PLACE: 4,
DONE: 5
};
const stateCopy = {
CARRY_A: {
name: "CARRYING TO LINE A",
detail:
"Continuous velocity is building while the crate remains attached to the carry socket."
},
BRAKING: {
name: "INTERRUPT / BRAKING",
detail:
"A new request arrived. Horizontal velocity is decaying; the crate remains locked to the socket."
},
SAFE_POSE: {
name: "SAFE BRACE / STABILIZING",
detail:
"The character lowers into a wide braced stance and turns toward the replacement destination."
},
CARRY_B: {
name: "RESUMED / LINE B",
detail:
"The carry action resumes from the braced pose. Root position is integrated continuously with no teleport."
},
PLACE: {
name: "PLACING AT LINE B",
detail:
"The character lowers the crate while preserving its world transform, then releases it."
},
DONE: {
name: "TASK COMPLETE",
detail:
"The redirected task is complete. The original route was safely cancelled."
}
};
const stateNameElement = document.querySelector("#stateName");
const stateDetailElement = document.querySelector("#stateDetail");
const stateDot = document.querySelector("#stateDot");
const phaseElements = [...document.querySelectorAll(".phase")];
const velocityElement = document.querySelector("#velocityValue");
const attachmentElement = document.querySelector("#attachmentValue");
const injectButton = document.querySelector("#injectButton");
const pauseButton = document.querySelector("#pauseButton");
const replayButton = document.querySelector("#replayButton");
const toastElement = document.querySelector("#toast");
const goalALabel = document.querySelector("#goalALabel");
const goalBLabel = document.querySelector("#goalBLabel");
const crateLabel = document.querySelector("#crateLabel");
let state = "CARRY_A";
let stateTime = 0;
let paused = false;
let released = false;
let speed = 0;
let yaw = Math.PI / 2;
let routeA = [];
let routeB = [];
let routeAIndex = 0;
let routeBIndex = 0;
function setState(nextState) {
state = nextState;
stateTime = 0;
const index = stateOrder[state];
const info = stateCopy[state];
stateNameElement.textContent = info.name;
stateDetailElement.textContent = info.detail;
phaseElements.forEach((element, phaseIndex) => {
element.classList.toggle("active", phaseIndex === index);
element.classList.toggle("done", phaseIndex < index);
});
const color =
state === "SAFE_POSE"
? "#75e09b"
: state === "BRAKING"
? "#ff6fae"
: state === "DONE"
? "#75e09b"
: "#58e0dc";
stateDot.style.background = color;
stateDot.style.boxShadow = `0 0 18px ${color}`;
}
function showToast(message, duration = 3200) {
toastElement.textContent = message;
toastElement.classList.add("show");
window.clearTimeout(showToast.timer);
showToast.timer = window.setTimeout(() => {
toastElement.classList.remove("show");
}, duration);
}
function directionTo(route, index) {
const target = route[Math.min(index + 1, route.length - 1)];
return new THREE.Vector3(
target.x - character.position.x,
0,
target.z - character.position.z
);
}
function followRoute(route, index, distance) {
let remaining = distance;
while (
remaining > 0 &&
index < route.length - 1
) {
const target = route[index + 1];
const delta = new THREE.Vector3(
target.x - character.position.x,
0,
target.z - character.position.z
);
const length = delta.length();
if (length <= remaining) {
// This assignment is only reached after integrating the same distance;
// it does not create a discontinuous root-position jump.
character.position.x = target.x;
character.position.z = target.z;
remaining -= length;
index++;
} else {
delta.multiplyScalar(remaining / length);
character.position.add(delta);
remaining = 0;
}
}
return index;
}
function makeReplacementRoute() {
const start = character.position.clone();
const waypointA = start.clone().add(new THREE.Vector3(1.35, 0, -1.25));
const waypointB = start.clone().add(new THREE.Vector3(3.0, 0, -2.45));
const finish = goalB.position.clone();
// Avoid duplicate points if the route is resumed from a very early click.
return [start, waypointA, waypointB, finish].filter((point, index, array) => {
if (index === 0) return true;
return point.distanceTo(array[index - 1]) > 0.08;
});
}
function injectNewRequest() {
if (state !== "CARRY_A") return;
routeB = makeReplacementRoute();
routeBIndex = 0;
goalB.visible = true;
goalB.userData.tileMaterial.color.setHex(0xff6fae);
goalB.userData.tileMaterial.emissive.setHex(0xff6fae);
goalB.userData.beaconMaterial.color.setHex(0xff6fae);
goalB.userData.point.color.setHex(0xff6fae);
goalA.userData.tileMaterial.color.setHex(0x4b5565);
goalA.userData.tileMaterial.emissive.setHex(0x151b25);
goalA.userData.beaconMaterial.color.setHex(0x596476);
goalA.userData.point.color.setHex(0x596476);
goalALabel.innerHTML = "Order 01<small>Cancelled / safely redirected</small>";
goalBLabel.style.display = "block";
goalBLabel.innerHTML = "New Order 02<small>Replacement destination</small>";
injectButton.disabled = true;
setState("BRAKING");
showToast(
"NEW REQUEST — Braking into a braced pose. The crate stays attached."
);
}
function releaseCrate() {
if (released) return;
// Object3D.attach preserves the crate's current world transform while
// changing its parent. There is no visible snap at release.
scene.attach(crate);
released = true;
attachmentElement.textContent = "RELEASED SAFELY";
crateLabel.innerHTML = "Supply Crate<small>Placed at Line B</small>";
}
function updateSimulation(dt) {
stateTime += dt;
if (state === "CARRY_A") {
speed = damp(speed, 1.25, 4.5, dt);
const direction = directionTo(routeA, routeAIndex);
if (direction.lengthSq() > 0.0001) {
const desiredYaw = Math.atan2(direction.x, direction.z);
yaw = dampAngle(yaw, desiredYaw, 7, dt);
}
routeAIndex = followRoute(routeA, routeAIndex, speed * dt);
// The interruption deliberately occurs while the carry is underway.
if (stateTime >= 2.65) {
injectNewRequest();
return;
}
} else if (state === "BRAKING") {
// Continue moving for the current frame with the current integrated
// velocity, then exponentially reduce that velocity to zero.
speed = damp(speed, 0, 7.5, dt);
character.position.x += Math.sin(yaw) * speed * dt;
character.position.z += Math.cos(yaw) * speed * dt;
if (stateTime >= 0.58) {
setState("SAFE_POSE");
}
} else if (state === "SAFE_POSE") {
speed = 0;
const direction = directionTo(routeB, routeBIndex);
if (direction.lengthSq() > 0.0001) {
const desiredYaw = Math.atan2(direction.x, direction.z);
yaw = dampAngle(yaw, desiredYaw, 3.8, dt);
}
if (stateTime >= 1.15) {
// Rebuild the path from the exact current position. This avoids a
// hidden correction even though the path itself is continuous.
routeB = makeReplacementRoute();
routeBIndex = 0;
setState("CARRY_B");
}
} else if (state === "CARRY_B") {
speed = damp(speed, 1.32, 4.2, dt);
const direction = directionTo(routeB, routeBIndex);
if (direction.lengthSq() > 0.0001) {
const desiredYaw = Math.atan2(direction.x, direction.z);
yaw = dampAngle(yaw, desiredYaw, 6.5, dt);
}
routeBIndex = followRoute(routeB, routeBIndex, speed * dt);
if (routeBIndex >= routeB.length - 1) {
speed = 0;
setState("PLACE");
}
} else if (state === "PLACE") {
speed = 0;
if (stateTime >= 0.95) {
releaseCrate();
}
if (stateTime >= 1.25) {
goalB.userData.tileMaterial.color.setHex(0x75e09b);
goalB.userData.tileMaterial.emissive.setHex(0x75e09b);
goalB.userData.beaconMaterial.color.setHex(0x75e09b);
goalB.userData.point.color.setHex(0x75e09b);
goalBLabel.innerHTML = "Order 02<small>Complete</small>";
setState("DONE");
showToast("TASK COMPLETE — Redirected carry finished without a teleport.");
}
}
character.rotation.y = yaw;
walkPhase += dt * (4.2 + speed * 1.9);
addTrailPoint();
}
// -------------------------------------------------------------------------
// HUD and projected world labels
// -------------------------------------------------------------------------
function projectLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
element.style.display = visible ? "block" : "none";
if (!visible) return;
element.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
function updateLabels() {
projectLabel(
goalALabel,
goalA.position.clone().add(new THREE.Vector3(0, 1.3, 0))
);
projectLabel(
goalBLabel,
goalB.position.clone().add(new THREE.Vector3(0, 1.3, 0))
);
const crateWorldPosition = new THREE.Vector3();
crate.getWorldPosition(crateWorldPosition);
crateWorldPosition.y += 0.7;
projectLabel(crateLabel, crateWorldPosition);
}
injectButton.addEventListener("click", () => {
if (state === "CARRY_A") {
paused = false;
pauseButton.textContent = "Pause";
injectNewRequest();
}
});
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
replayButton.addEventListener("click", resetScenario);
function resetScenario() {
// Explicit reset is allowed to place the character at the starting pose.
state = "CARRY_A";
stateTime = 0;
paused = false;
released = false;
speed = 0;
yaw = Math.PI / 2;
character.position.set(-5.4, 0, 1.3);
character.rotation.y = yaw;
// Reattach and reset the crate for the replay.
carrySocket.add(crate);
crate.position.set(0, 0, 0);
crate.rotation.set(0, 0, 0);
crate.scale.set(1, 1, 1);
routeA = [
new THREE.Vector3(-5.4, 0, 1.3),
new THREE.Vector3(2.8, 0, 1.3)
];
routeAIndex = 0;
routeB = [];
routeBIndex = 0;
goalA.userData.tileMaterial.color.setHex(0xffbd59);
goalA.userData.tileMaterial.emissive.setHex(0xffbd59);
goalA.userData.beaconMaterial.color.setHex(0xffbd59);
goalA.userData.point.color.setHex(0xffbd59);
goalB.visible = false;
goalB.userData.tileMaterial.color.setHex(0xff6fae);
goalB.userData.tileMaterial.emissive.setHex(0xff6fae);
goalB.userData.beaconMaterial.color.setHex(0xff6fae);
goalB.userData.point.color.setHex(0xff6fae);
goalALabel.innerHTML = "Order 01<small>Line A</small>";
goalBLabel.innerHTML = "New Order 02<small>Line B</small>";
crateLabel.innerHTML = "Supply Crate<small>Attachment locked</small>";
attachmentElement.textContent = "LOCKED TO SOCKET";
injectButton.disabled = false;
pauseButton.textContent = "Pause";
for (const dot of trailDots) dot.visible = false;
trailIndex = 0;
trailCount = 0;
lastTrailPosition.copy(character.position);
Object.assign(poseCurrent, poses.carry);
setState("CARRY_A");
showToast("Scenario reset. The interruption will occur during the carry.");
}
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (!paused) {
updateSimulation(dt);
}
let poseName = "carry";
if (state === "BRAKING" || state === "SAFE_POSE") poseName = "brace";
if (state === "PLACE") poseName = "place";
applyPose(poseName, dt, speed);
safeHalo.visible = state === "BRAKING" || state === "SAFE_POSE";
safeMaterial.opacity = 0.55 + Math.sin(performance.now() * 0.006) * 0.2;
const pulse = 0.5 + Math.sin(performance.now() * 0.004) * 0.5;
goalB.userData.beacon.children.forEach((beam, index) => {
beam.position.y =
beam.userData.baseY +
Math.sin(performance.now() * 0.0025 + beam.userData.phase) * 0.12;
});
goalB.userData.beaconMaterial.opacity =
goalB.visible ? 0.12 + pulse * 0.18 : 0;
goalA.userData.beaconMaterial.opacity = 0.08 + pulse * 0.08;
const horizontalSpeed = Math.hypot(
Math.sin(yaw) * speed,
Math.cos(yaw) * speed
);
velocityElement.textContent = `${horizontalSpeed.toFixed(2)} m/s`;
updateLabels();
renderer.render(scene, camera);
}
resetScenario();
animate();
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
</script>
</body>
</html>
```