Prompt specification
Build or customize the Three.js 3D scene "Flexible-arm object-transfer puzzle" 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: Flexible-arm object-transfer puzzle
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/flexible-arm-object-transfer-puzzle-x0700
Scene Description Prompt:
Flexible-arm object-transfer puzzle. Create an educational octopus-inspired manipulator game with reachable objects and obstacles; users select arm paths while the interface labels the motion as scripted biomimicry rather than animal cognition simulation. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (flexible-arm-object-transfer-puzzle-x0700):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OctoMotion — Scripted Biomimicry Arm Lab</title>
<style>
:root {
--ink: #173246;
--muted: #607887;
--panel: rgba(250, 254, 255, 0.96);
--line: #cde2e7;
--teal: #087f83;
--teal-light: #dff4f0;
--purple: #7057a8;
--coral: #ec765f;
--amber: #f2b84b;
--shadow: 0 18px 50px rgba(19, 67, 78, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dcefeb;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
.app {
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
width: 100%;
height: 100%;
}
.sidebar {
position: relative;
z-index: 10;
padding: 22px 20px 18px;
overflow-y: auto;
background:
radial-gradient(circle at 100% 0%, rgba(112, 87, 168, 0.13), transparent 38%),
var(--panel);
border-right: 1px solid rgba(118, 157, 166, 0.3);
box-shadow: var(--shadow);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 18px;
}
.brand-mark {
position: relative;
width: 48px;
height: 48px;
flex: 0 0 auto;
border-radius: 15px;
background: linear-gradient(145deg, #8169bd, #4ca6a1);
box-shadow: inset 0 1px rgba(255, 255, 255, 0.4);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: #f3fffd;
border-radius: 50%;
}
.brand-mark::before {
width: 9px;
height: 9px;
top: 12px;
left: 12px;
box-shadow: 17px 1px 0 #f3fffd;
}
.brand-mark::after {
width: 18px;
height: 9px;
left: 15px;
bottom: 10px;
transform: rotate(-9deg);
border-radius: 12px 12px 8px 8px;
}
.brand-name {
font-size: 18px;
font-weight: 850;
letter-spacing: -0.02em;
}
.brand-sub {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.badge {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
margin-bottom: 11px;
color: #4f3c80;
background: #eee8fb;
border: 1px solid #d8caef;
border-radius: 999px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.badge::before {
content: "";
width: 7px;
height: 7px;
background: var(--purple);
border-radius: 50%;
box-shadow: 0 0 0 4px rgba(112, 87, 168, 0.12);
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 32px);
line-height: 1.08;
letter-spacing: -0.045em;
}
.intro {
margin: 11px 0 15px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.disclaimer {
margin-bottom: 16px;
padding: 11px 12px;
color: #4f5264;
background: #f2f0f8;
border-left: 3px solid var(--purple);
border-radius: 4px 10px 10px 4px;
font-size: 11px;
line-height: 1.5;
}
.disclaimer strong {
color: #42365f;
}
.objective {
padding: 14px;
color: #f3fffd;
background: linear-gradient(135deg, #176d73, #284c68);
border-radius: 15px;
box-shadow: 0 10px 24px rgba(28, 87, 95, 0.18);
}
.objective-kicker {
opacity: 0.72;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.objective-title {
margin-top: 5px;
font-size: 15px;
font-weight: 800;
line-height: 1.35;
}
.objective-status {
margin-top: 7px;
color: #c9eeea;
font-size: 12px;
line-height: 1.45;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 13px 0;
}
.stat {
padding: 10px 8px;
text-align: center;
background: #f2f8f8;
border: 1px solid var(--line);
border-radius: 11px;
}
.stat-value {
display: block;
font-size: 15px;
font-weight: 850;
line-height: 1.1;
}
.stat-label {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 17px 0 9px;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.04em;
}
.section-title span {
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.map-wrap {
position: relative;
overflow: hidden;
border: 1px solid #bdd8de;
border-radius: 13px;
background: #e9f5f2;
box-shadow: inset 0 0 0 4px rgba(255, 255, 255, 0.45);
}
#minimap {
display: block;
width: 100%;
height: auto;
cursor: crosshair;
touch-action: none;
}
.map-caption {
padding: 8px 10px;
color: var(--muted);
background: rgba(255, 255, 255, 0.78);
border-top: 1px solid #d5e7e8;
font-size: 10px;
line-height: 1.4;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px 14px;
margin-top: 9px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
}
.dot.arm { background: var(--purple); }
.dot.item { background: var(--amber); }
.dot.goal { background: var(--teal); }
.dot.wall { background: var(--coral); }
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
button {
width: 100%;
padding: 10px 11px;
color: var(--ink);
background: #f7fbfb;
border: 1px solid #c9dfe3;
border-radius: 10px;
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition: transform 0.15s, background 0.15s, border-color 0.15s, opacity 0.15s;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
background: #eaf6f4;
border-color: #8fc4c4;
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: not-allowed;
opacity: 0.42;
}
button.primary {
color: white;
background: var(--teal);
border-color: var(--teal);
}
button.primary:hover:not(:disabled) {
background: #066c70;
border-color: #066c70;
}
button.goal {
color: #17666b;
background: #e3f5f1;
border-color: #b7ded7;
}
.wide {
grid-column: 1 / -1;
}
details {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
summary {
cursor: pointer;
font-size: 12px;
font-weight: 850;
}
.lesson {
display: grid;
gap: 9px;
margin-top: 12px;
}
.lesson-item {
display: grid;
grid-template-columns: 27px 1fr;
gap: 9px;
align-items: start;
}
.lesson-number {
display: grid;
width: 27px;
height: 27px;
place-items: center;
color: white;
background: #6887a3;
border-radius: 8px;
font-size: 10px;
font-weight: 850;
}
.lesson-item strong {
display: block;
font-size: 11px;
}
.lesson-item p {
margin: 2px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
#hintText {
display: none;
margin-top: 9px;
padding: 10px;
color: #665027;
background: #fff5d9;
border: 1px solid #efd898;
border-radius: 9px;
font-size: 10px;
line-height: 1.5;
}
#hintText.visible {
display: block;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #dcefeb;
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.stage-top {
position: absolute;
z-index: 4;
top: 18px;
left: 20px;
pointer-events: none;
}
.stage-top h2 {
margin: 0;
color: #204557;
font-size: 15px;
letter-spacing: -0.02em;
}
.stage-top p {
margin: 4px 0 0;
color: #56727f;
font-size: 11px;
}
.mode-pill {
position: absolute;
z-index: 4;
top: 18px;
right: 20px;
display: flex;
align-items: center;
gap: 7px;
padding: 8px 11px;
color: #315061;
background: rgba(255, 255, 255, 0.78);
border: 1px solid rgba(255, 255, 255, 0.9);
border-radius: 999px;
box-shadow: 0 8px 24px rgba(33, 79, 87, 0.1);
backdrop-filter: blur(10px);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.04em;
pointer-events: none;
}
.mode-pill::before {
content: "";
width: 7px;
height: 7px;
background: #2ea99a;
border-radius: 50%;
box-shadow: 0 0 0 4px rgba(46, 169, 154, 0.14);
}
.view-help {
position: absolute;
z-index: 4;
left: 20px;
bottom: 18px;
padding: 9px 12px;
color: #365766;
background: rgba(255, 255, 255, 0.78);
border: 1px solid rgba(255, 255, 255, 0.9);
border-radius: 10px;
box-shadow: 0 8px 24px rgba(33, 79, 87, 0.1);
backdrop-filter: blur(10px);
font-size: 10px;
line-height: 1.5;
pointer-events: none;
}
.view-help strong {
color: #194b5b;
}
#toast {
position: absolute;
z-index: 8;
left: 50%;
bottom: 66px;
max-width: min(460px, calc(100% - 40px));
padding: 10px 15px;
color: white;
background: rgba(30, 63, 76, 0.92);
border-radius: 999px;
box-shadow: 0 10px 30px rgba(20, 54, 64, 0.24);
backdrop-filter: blur(8px);
font-size: 11px;
font-weight: 700;
text-align: center;
opacity: 0;
transform: translate(-50%, 10px);
transition: opacity 0.2s, transform 0.2s;
pointer-events: none;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.warning {
background: rgba(164, 75, 55, 0.94);
}
#toast.success {
background: rgba(18, 111, 104, 0.94);
}
#hoverLabel {
position: absolute;
z-index: 7;
padding: 6px 9px;
color: white;
background: rgba(31, 58, 70, 0.9);
border-radius: 7px;
font-size: 10px;
font-weight: 750;
opacity: 0;
transform: translate(12px, 12px);
pointer-events: none;
}
.success-card {
position: absolute;
z-index: 9;
top: 50%;
left: 50%;
width: min(350px, calc(100% - 40px));
padding: 25px;
color: #244a51;
background: rgba(251, 255, 253, 0.95);
border: 1px solid rgba(255, 255, 255, 0.95);
border-radius: 20px;
box-shadow: 0 22px 70px rgba(20, 65, 73, 0.25);
text-align: center;
opacity: 0;
transform: translate(-50%, -45%) scale(0.94);
transition: opacity 0.3s, transform 0.3s;
pointer-events: none;
backdrop-filter: blur(14px);
}
.success-card.visible {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
pointer-events: auto;
}
.success-icon {
display: grid;
width: 54px;
height: 54px;
margin: 0 auto 12px;
place-items: center;
color: white;
background: linear-gradient(145deg, #2ca99a, #167379);
border-radius: 17px;
font-size: 25px;
box-shadow: 0 10px 24px rgba(25, 124, 117, 0.22);
}
.success-card h3 {
margin: 0;
font-size: 22px;
letter-spacing: -0.03em;
}
.success-card p {
margin: 8px 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
@media (max-width: 860px) {
html,
body {
overflow: auto;
}
.app {
grid-template-columns: 1fr;
grid-template-rows: minmax(470px, 60vh) auto;
height: auto;
min-height: 100%;
}
.stage {
grid-row: 1;
}
.sidebar {
grid-row: 2;
border-right: 0;
border-top: 1px solid var(--line);
}
.mode-pill {
display: none;
}
}
@media (max-width: 480px) {
.stage-top {
top: 12px;
left: 13px;
}
.view-help {
left: 12px;
right: 12px;
bottom: 12px;
}
.sidebar {
padding: 18px 14px;
}
}
</style>
</head>
<body>
<div class="app">
<aside class="sidebar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<div class="brand-name">OctoMotion</div>
<div class="brand-sub">Flexible arm laboratory</div>
</div>
</div>
<div class="badge">Scripted biomimicry</div>
<h1>Shape a safer path.</h1>
<p class="intro">
Plan a flexible arm route, avoid a reef ridge, and transfer the amber seed
into the reef socket.
</p>
<div class="disclaimer">
<strong>Not animal cognition.</strong>
Every bend is a user-authored kinematic waypoint. This educational model
demonstrates scripted biomimicry, not perception, intention, learning, or
decision-making in an animal.
</div>
<section class="objective" aria-live="polite">
<div class="objective-kicker">Current objective</div>
<div class="objective-title" id="objectiveTitle">Collect the amber seed</div>
<div class="objective-status" id="objectiveStatus">
Select the source or click “Plan to source.”
</div>
</section>
<div class="stats">
<div class="stat">
<span class="stat-value" id="reachStat">0.0 m</span>
<span class="stat-label">Reach</span>
</div>
<div class="stat">
<span class="stat-value" id="waypointStat">0</span>
<span class="stat-label">Waypoints</span>
</div>
<div class="stat">
<span class="stat-value" id="transferStat">0 / 1</span>
<span class="stat-label">Transfer</span>
</div>
</div>
<div class="section-title">
Top-down route planner
<span>Click to place a point</span>
</div>
<div class="map-wrap">
<canvas
id="minimap"
width="600"
height="360"
aria-label="Interactive top-down map for adding arm waypoints"
></canvas>
<div class="map-caption">
Click the map or the 3D reef floor to add waypoints. The arm follows the
planned centerline.
</div>
</div>
<div class="legend">
<span class="legend-item"><i class="dot arm"></i>Manipulator</span>
<span class="legend-item"><i class="dot item"></i>Amber seed</span>
<span class="legend-item"><i class="dot goal"></i>Reef socket</span>
<span class="legend-item"><i class="dot wall"></i>Obstacle</span>
</div>
<div class="buttons">
<button id="sourceButton" class="primary">Plan to source</button>
<button id="targetButton" class="goal" disabled>Plan to socket</button>
<button id="undoButton" disabled>Undo point</button>
<button id="pauseButton">Pause motion</button>
<button id="resetButton" class="wide">Reset arm & task</button>
</div>
<details open>
<summary>What this model teaches</summary>
<div class="lesson">
<div class="lesson-item">
<div class="lesson-number">1</div>
<div>
<strong>Flexible reach</strong>
<p>
A segmented centerline bends through selected waypoints inside a
circular reach envelope.
</p>
</div>
</div>
<div class="lesson-item">
<div class="lesson-number">2</div>
<div>
<strong>Obstacle clearance</strong>
<p>
New segments are rejected if they cross the reef ridge or its
0.30 m safety buffer.
</p>
</div>
</div>
<div class="lesson-item">
<div class="lesson-number">3</div>
<div>
<strong>Scripted motion</strong>
<p>
The sequence is deterministic: the programmed route drives the
joints without representing animal intent.
</p>
</div>
</div>
</div>
</details>
<button id="hintButton" class="wide">Show a route hint</button>
<div id="hintText">
A clear route goes north of the reef ridge. On the map, try a waypoint near
x = 0, z = −2.3 before selecting the reef socket. The socket is inside the
10.2 m reach envelope, but the direct segment is blocked.
</div>
</aside>
<main class="stage">
<div id="viewport"></div>
<div class="stage-top">
<h2>Reef manipulation bay</h2>
<p>Low-poly kinematic demonstration</p>
</div>
<div class="mode-pill">USER-AUTHORED KINEMATIC PATH</div>
<div class="view-help">
<strong>Controls:</strong> drag to orbit · wheel/pinch to zoom ·
click a waypoint location · Space: pause · U: undo · R: reset
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="hoverLabel"></div>
<div class="success-card" id="successCard">
<div class="success-icon">✓</div>
<h3>Transfer complete</h3>
<p>
The scripted arm carried the amber seed through a clear centerline and
placed it in the reef socket.
</p>
<button id="playAgainButton" class="primary">Try another route</button>
</div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const minimap = document.getElementById("minimap");
const mapContext = minimap.getContext("2d");
const sourceButton = document.getElementById("sourceButton");
const targetButton = document.getElementById("targetButton");
const undoButton = document.getElementById("undoButton");
const pauseButton = document.getElementById("pauseButton");
const resetButton = document.getElementById("resetButton");
const hintButton = document.getElementById("hintButton");
const hintText = document.getElementById("hintText");
const playAgainButton = document.getElementById("playAgainButton");
const objectiveTitle = document.getElementById("objectiveTitle");
const objectiveStatus = document.getElementById("objectiveStatus");
const reachStat = document.getElementById("reachStat");
const waypointStat = document.getElementById("waypointStat");
const transferStat = document.getElementById("transferStat");
const toast = document.getElementById("toast");
const hoverLabel = document.getElementById("hoverLabel");
const successCard = document.getElementById("successCard");
const WORLD = {
minX: -6.5,
maxX: 6.5,
minZ: -4.3,
maxZ: 4.3
};
const BASE = new THREE.Vector3(-5.0, 1.05, 2.1);
const SOURCE = new THREE.Vector3(-2.6, 0.66, 1.4);
const TARGET = new THREE.Vector3(3.6, 0.24, -1.4);
const MAX_REACH = 10.2;
const ARM_SPEED = 2.55;
const CLEARANCE = 0.30;
const ARM_Y = 1.05;
const obstacles = [
{
name: "Reef ridge",
x: 0,
z: 0.8,
width: 0.65,
depth: 4.8,
height: 1.8
}
];
const state = {
routePlan: [BASE.clone()],
legIndex: 1,
legProgress: 0,
carried: false,
complete: false,
paused: false,
selected: "source"
};
let toastTimer = 0;
function showToast(message, type = "") {
toast.textContent = message;
toast.className = `visible ${type}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.className = "";
}, 2800);
}
// ---------------------------------------------------------------------
// Renderer and scene
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdcefeb);
scene.fog = new THREE.Fog(0xdcefeb, 18, 34);
const camera = new THREE.PerspectiveCamera(
43,
viewport.clientWidth / viewport.clientHeight,
0.1,
80
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(viewport.clientWidth, viewport.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xe9ffff, 0x668177, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff5df, 3.1);
sun.position.set(-5, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0006;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x87c9df, 1.2);
fill.position.set(8, 5, -7);
scene.add(fill);
const floor = new THREE.Mesh(
new THREE.BoxGeometry(13.6, 0.3, 9.0),
new THREE.MeshStandardMaterial({
color: 0xbcded5,
roughness: 0.95,
metalness: 0,
flatShading: true
})
);
floor.position.y = -0.15;
floor.receiveShadow = true;
scene.add(floor);
// A restrained custom grid keeps the low-poly scene readable.
const gridPositions = [];
for (let x = -6; x <= 6; x += 1) {
gridPositions.push(x, 0.012, -4.2, x, 0.012, 4.2);
}
for (let z = -4; z <= 4; z += 1) {
gridPositions.push(-6.3, 0.012, z, 6.3, 0.012, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x83b9b0,
transparent: true,
opacity: 0.19
})
);
scene.add(grid);
const boundaryPoints = [
new THREE.Vector3(-6.3, 0.025, -4.2),
new THREE.Vector3(6.3, 0.025, -4.2),
new THREE.Vector3(6.3, 0.025, 4.2),
new THREE.Vector3(-6.3, 0.025, 4.2),
new THREE.Vector3(-6.3, 0.025, -4.2)
];
const boundary = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(boundaryPoints),
new THREE.LineBasicMaterial({ color: 0x4d9893, transparent: true, opacity: 0.42 })
);
scene.add(boundary);
// Reach envelope.
const reachPoints = [];
for (let i = 0; i <= 128; i++) {
const angle = (i / 128) * Math.PI * 2;
reachPoints.push(
new THREE.Vector3(
BASE.x + Math.cos(angle) * MAX_REACH,
0.03,
BASE.z + Math.sin(angle) * MAX_REACH
)
);
}
const reachRing = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(reachPoints),
new THREE.LineDashedMaterial({
color: 0x268f88,
dashSize: 0.26,
gapSize: 0.16,
transparent: true,
opacity: 0.28
})
);
reachRing.computeLineDistances();
scene.add(reachRing);
// Stylized low-poly octopus-inspired base.
const baseGroup = new THREE.Group();
baseGroup.position.set(BASE.x, 0, BASE.z);
scene.add(baseGroup);
const body = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.88, 1),
new THREE.MeshStandardMaterial({
color: 0x7560aa,
roughness: 0.8,
flatShading: true
})
);
body.position.y = 0.72;
body.scale.set(1.05, 0.82, 1.05);
body.castShadow = true;
baseGroup.add(body);
const collar = new THREE.Mesh(
new THREE.CylinderGeometry(0.55, 0.72, 0.22, 8),
new THREE.MeshStandardMaterial({
color: 0x4d8f95,
roughness: 0.8,
flatShading: true
})
);
collar.position.y = 0.35;
collar.castShadow = true;
baseGroup.add(collar);
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0x152b37,
roughness: 0.35,
flatShading: true
});
for (const dx of [-0.26, 0.26]) {
const eye = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.105, 0),
eyeMaterial
);
eye.position.set(dx, 0.96, 0.67);
eye.castShadow = true;
baseGroup.add(eye);
}
// Decorative short tentacles.
const decorativeTentacleMaterial = new THREE.MeshStandardMaterial({
color: 0x68529c,
roughness: 0.88,
flatShading: true
});
for (let i = 0; i < 4; i++) {
const angle = (i / 4) * Math.PI * 2 + Math.PI / 4;
const length = 0.85 + (i % 2) * 0.2;
const tentacle = new THREE.Mesh(
new THREE.CylinderGeometry(0.11, 0.04, length, 6),
decorativeTentacleMaterial
);
tentacle.position.set(
Math.cos(angle) * 0.58,
0.22,
Math.sin(angle) * 0.58
);
tentacle.rotation.z = Math.cos(angle) * 0.65;
tentacle.rotation.x = Math.sin(angle) * 0.65;
tentacle.castShadow = true;
baseGroup.add(tentacle);
}
// Obstacle.
for (const obstacle of obstacles) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(
obstacle.width,
obstacle.height,
obstacle.depth
),
new THREE.MeshStandardMaterial({
color: 0xc95e58,
roughness: 0.92,
flatShading: true
})
);
mesh.position.set(obstacle.x, obstacle.height / 2, obstacle.z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
// Angular reef caps.
for (let i = 0; i < 6; i++) {
const cap = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.28 + (i % 3) * 0.04, 0),
new THREE.MeshStandardMaterial({
color: i % 2 ? 0xe18368 : 0xb94f54,
roughness: 0.95,
flatShading: true
})
);
cap.position.set(
obstacle.x + (i % 2 ? 0.08 : -0.08),
obstacle.height + 0.05,
obstacle.z - obstacle.depth / 2 + 0.45 + i * 0.78
);
cap.rotation.set(i * 0.3, i * 0.7, i * 0.2);
cap.castShadow = true;
scene.add(cap);
}
}
// Source pedestal and object.
const sourcePedestal = new THREE.Mesh(
new THREE.CylinderGeometry(0.52, 0.64, 0.34, 10),
new THREE.MeshStandardMaterial({
color: 0x4f9e98,
roughness: 0.85,
flatShading: true
})
);
sourcePedestal.position.set(SOURCE.x, 0.17, SOURCE.z);
sourcePedestal.castShadow = true;
sourcePedestal.receiveShadow = true;
scene.add(sourcePedestal);
const sourceMaterial = new THREE.MeshStandardMaterial({
color: 0xf2b84b,
emissive: 0x6b3900,
emissiveIntensity: 0.22,
roughness: 0.42,
metalness: 0.08,
flatShading: true
});
const sourceMesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.39, 0),
sourceMaterial
);
sourceMesh.position.copy(SOURCE);
sourceMesh.castShadow = true;
sourceMesh.userData.action = "source";
scene.add(sourceMesh);
const sourceRing = new THREE.Mesh(
new THREE.RingGeometry(0.48, 0.56, 24),
new THREE.MeshBasicMaterial({
color: 0xf2b84b,
transparent: true,
opacity: 0.58,
side: THREE.DoubleSide
})
);
sourceRing.rotation.x = -Math.PI / 2;
sourceRing.position.set(SOURCE.x, 0.035, SOURCE.z);
scene.add(sourceRing);
// Target socket.
const targetMaterial = new THREE.MeshStandardMaterial({
color: 0x3b9691,
emissive: 0x0a3f3e,
emissiveIntensity: 0.16,
roughness: 0.7,
flatShading: true
});
const targetMesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.82, 0.94, 0.24, 12),
targetMaterial
);
targetMesh.position.set(TARGET.x, 0.12, TARGET.z);
targetMesh.castShadow = true;
targetMesh.receiveShadow = true;
targetMesh.userData.action = "target";
scene.add(targetMesh);
const targetRing = new THREE.Mesh(
new THREE.RingGeometry(0.91, 1.02, 32),
new THREE.MeshBasicMaterial({
color: 0x2caaa0,
transparent: true,
opacity: 0.55,
side: THREE.DoubleSide
})
);
targetRing.rotation.x = -Math.PI / 2;
targetRing.position.set(TARGET.x, 0.035, TARGET.z);
scene.add(targetRing);
// Canvas-textured labels; no additional Three.js modules are used.
function createLabel(text, color) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.fillStyle = "rgba(247, 253, 251, 0.9)";
context.fillRect(4, 10, 504, 108);
context.strokeStyle = color;
context.lineWidth = 7;
context.strokeRect(5, 11, 502, 106);
context.fillStyle = color;
context.font = "800 34px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(2.35, 0.59, 1);
return sprite;
}
const sourceLabel = createLabel("AMBER SEED", "#c38220");
sourceLabel.position.set(SOURCE.x, 2.15, SOURCE.z);
scene.add(sourceLabel);
const targetLabel = createLabel("REEF SOCKET", "#197a75");
targetLabel.position.set(TARGET.x, 2.15, TARGET.z);
scene.add(targetLabel);
const obstacleLabel = createLabel("REEF RIDGE", "#a84849");
obstacleLabel.position.set(0, 2.55, 0.8);
obstacleLabel.scale.set(2.1, 0.52, 1);
scene.add(obstacleLabel);
// Low-poly environmental details.
const decorMaterial = new THREE.MeshStandardMaterial({
color: 0x629f94,
roughness: 0.95,
flatShading: true
});
for (const [x, z, scale] of [
[-6.0, -3.6, 0.6],
[5.9, 3.5, 0.7],
[5.8, -3.5, 0.45],
[-5.9, 3.7, 0.45]
]) {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(scale, 0),
decorMaterial
);
rock.position.set(x, scale * 0.35, z);
rock.rotation.set(0.4, x, 0.2);
rock.castShadow = true;
scene.add(rock);
}
for (const [x, z, height] of [
[-5.8, -1.1, 0.8],
[5.7, 0.4, 0.95],
[4.9, 3.5, 0.65]
]) {
const plant = new THREE.Mesh(
new THREE.ConeGeometry(0.22, height, 5),
new THREE.MeshStandardMaterial({
color: 0x3e8e83,
roughness: 0.95,
flatShading: true
})
);
plant.position.set(x, height / 2, z);
plant.rotation.z = x * 0.04;
plant.castShadow = true;
scene.add(plant);
}
// ---------------------------------------------------------------------
// Flexible segmented arm
// ---------------------------------------------------------------------
const ARM_SEGMENTS = 24;
const armMeshes = [];
const jointMeshes = [];
const suckerMeshes = [];
const segmentGeometry = new THREE.CylinderGeometry(1, 1, 1, 6, 1, false);
const jointGeometry = new THREE.IcosahedronGeometry(1, 0);
const suckerGeometry = new THREE.IcosahedronGeometry(0.052, 0);
const purple = new THREE.Color(0x7056a6);
const turquoise = new THREE.Color(0x55b4a7);
for (let i = 0; i < ARM_SEGMENTS; i++) {
const t = i / (ARM_SEGMENTS - 1);
const material = new THREE.MeshStandardMaterial({
color: purple.clone().lerp(turquoise, t),
roughness: 0.78,
metalness: 0.03,
flatShading: true
});
const segment = new THREE.Mesh(segmentGeometry, material);
segment.castShadow = true;
segment.receiveShadow = true;
scene.add(segment);
armMeshes.push(segment);
const joint = new THREE.Mesh(
jointGeometry,
new THREE.MeshStandardMaterial({
color: purple.clone().lerp(turquoise, t),
roughness: 0.8,
flatShading: true
})
);
joint.castShadow = true;
scene.add(joint);
jointMeshes.push(joint);
if (i > 1 && i % 2 === 0) {
const sucker = new THREE.Mesh(
suckerGeometry,
new THREE.MeshStandardMaterial({
color: 0xd8f4e8,
roughness: 0.95,
flatShading: true
})
);
sucker.castShadow = true;
scene.add(sucker);
suckerMeshes.push({ mesh: sucker, index: i });
}
}
const gripper = new THREE.Group();
const gripperCore = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.18, 0),
new THREE.MeshStandardMaterial({
color: 0x9de3d2,
roughness: 0.6,
flatShading: true
})
);
gripperCore.castShadow = true;
gripper.add(gripperCore);
const clawGeometry = new THREE.ConeGeometry(0.105, 0.34, 5);
const clawMaterial = new THREE.MeshStandardMaterial({
color: 0x4d918e,
roughness: 0.72,
flatShading: true
});
for (const side of [-1, 1]) {
const claw = new THREE.Mesh(clawGeometry, clawMaterial);
claw.position.set(side * 0.12, 0.18, 0);
claw.rotation.z = side * -0.28;
claw.castShadow = true;
gripper.add(claw);
}
scene.add(gripper);
// Planned route line and waypoint markers.
const routeLinePositions = new Float32Array(64 * 3);
const routeLineGeometry = new THREE.BufferGeometry();
routeLineGeometry.setAttribute(
"position",
new THREE.BufferAttribute(routeLinePositions, 3)
);
const routeLine = new THREE.Line(
routeLineGeometry,
new THREE.LineBasicMaterial({
color: 0x2b9b91,
transparent: true,
opacity: 0.75
})
);
scene.add(routeLine);
const markerGeometry = new THREE.OctahedronGeometry(0.12, 0);
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xf4d071,
emissive: 0x8c5d0c,
emissiveIntensity: 0.18,
roughness: 0.55,
flatShading: true
});
const markerGroup = new THREE.Group();
scene.add(markerGroup);
function updateRouteVisuals() {
const count = Math.min(state.routePlan.length, 64);
for (let i = 0; i < count; i++) {
const point = state.routePlan[i];
routeLinePositions[i * 3] = point.x;
routeLinePositions[i * 3 + 1] = 0.075;
routeLinePositions[i * 3 + 2] = point.z;
}
routeLineGeometry.attributes.position.needsUpdate = true;
routeLineGeometry.setDrawRange(0, count);
routeLineGeometry.computeBoundingSphere();
while (markerGroup.children.length) {
markerGroup.remove(markerGroup.children[0]);
}
for (let i = 1; i < state.routePlan.length; i++) {
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
const point = state.routePlan[i];
marker.position.set(point.x, 0.13, point.z);
marker.castShadow = true;
markerGroup.add(marker);
}
}
// ---------------------------------------------------------------------
// Path planning and obstacle validation
// ---------------------------------------------------------------------
function segmentIntersectsExpandedRectangle(a, b, obstacle) {
const minX = obstacle.x - obstacle.width / 2 - CLEARANCE;
const maxX = obstacle.x + obstacle.width / 2 + CLEARANCE;
const minZ = obstacle.z - obstacle.depth / 2 - CLEARANCE;
const maxZ = obstacle.z + obstacle.depth / 2 + CLEARANCE;
let tMin = 0;
let tMax = 1;
const axes = [
[a.x, b.x - a.x, minX, maxX],
[a.z, b.z - a.z, minZ, maxZ]
];
for (const [origin, direction, min, max] of axes) {
if (Math.abs(direction) < 1e-8) {
if (origin < min || origin > max) {
return false;
}
continue;
}
let t1 = (min - origin) / direction;
let t2 = (max - origin) / direction;
if (t1 > t2) {
[t1, t2] = [t2, t1];
}
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMin > tMax) {
return false;
}
}
return true;
}
function routeCrossesObstacle(a, b) {
return obstacles.some((obstacle) =>
segmentIntersectsExpandedRectangle(a, b, obstacle)
);
}
function addWaypoint(x, z, purpose = "manual") {
if (state.complete) {
showToast("The task is complete. Reset to try another route.", "warning");
return false;
}
if (
x < WORLD.minX ||
x > WORLD.maxX ||
z < WORLD.minZ ||
z > WORLD.maxZ
) {
showToast("Place waypoints inside the marked reef bay.", "warning");
return false;
}
const radialReach = Math.hypot(x - BASE.x, z - BASE.z);
if (radialReach > MAX_REACH) {
showToast(
`That point exceeds the ${MAX_REACH.toFixed(1)} m reach envelope.`,
"warning"
);
return false;
}
if (state.routePlan.length >= 64) {
showToast("The route is limited to 63 waypoints.", "warning");
return false;
}
const candidate = new THREE.Vector3(x, ARM_Y, z);
const previous = state.routePlan[state.routePlan.length - 1];
if (routeCrossesObstacle(previous, candidate)) {
showToast(
"Segment blocked by the reef ridge or its 0.30 m safety buffer.",
"warning"
);
return false;
}
state.routePlan.push(candidate);
updateRouteVisuals();
updateInterface();
if (purpose === "source") {
state.selected = "source";
showToast("Source waypoint added. The arm is following the plan.");
} else if (purpose === "target") {
state.selected = "target";
showToast("Socket waypoint added. Completing the transfer…", "success");
} else {
showToast("Waypoint added to the scripted route.");
}
return true;
}
function undoWaypoint() {
if (state.routePlan.length <= 1) {
showToast("There are no waypoints to undo.");
return;
}
const removed = state.routePlan.pop();
if (state.legIndex >= state.routePlan.length) {
state.legIndex = Math.max(1, state.routePlan.length - 1);
state.legProgress = 1;
}
updateRouteVisuals();
updateInterface();
showToast("Last waypoint removed.");
}
function resetTask() {
state.routePlan = [BASE.clone()];
state.legIndex = 1;
state.legProgress = 0;
state.carried = false;
state.complete = false;
state.paused = false;
state.selected = "source";
sourceMesh.position.copy(SOURCE);
sourceMesh.rotation.set(0, 0, 0);
sourceMesh.visible = true;
targetMaterial.color.setHex(0x3b9691);
targetMaterial.emissive.setHex(0x0a3f3e);
targetMaterial.emissiveIntensity = 0.16;
successCard.classList.remove("visible");
pauseButton.textContent = "Pause motion";
updateRouteVisuals();
updateInterface();
showToast("Task reset. The scripted arm is ready for a new plan.");
}
// ---------------------------------------------------------------------
// Motion and arm deformation
// ---------------------------------------------------------------------
function currentTip() {
if (state.legIndex < state.routePlan.length) {
const a = state.routePlan[state.legIndex - 1];
const b = state.routePlan[state.legIndex];
return a.clone().lerp(b, state.legProgress);
}
return state.routePlan[state.routePlan.length - 1].clone();
}
function updateMotion(dt) {
if (state.paused || state.complete) {
return;
}
let remainingDistance = ARM_SPEED * dt;
while (
remainingDistance > 0 &&
state.legIndex < state.routePlan.length
) {
const a = state.routePlan[state.legIndex - 1];
const b = state.routePlan[state.legIndex];
const distance = a.distanceTo(b);
if (distance < 1e-6) {
state.legIndex += 1;
state.legProgress = 0;
continue;
}
const fraction = Math.min(1, remainingDistance / distance);
state.legProgress += fraction;
remainingDistance -= distance * fraction;
if (state.legProgress >= 0.999999) {
state.legProgress = 0;
state.legIndex += 1;
} else {
break;
}
}
}
function resamplePolyline(points, count) {
if (points.length === 0) {
return Array.from({ length: count }, () => BASE.clone());
}
if (points.length === 1) {
return Array.from({ length: count }, () => points[0].clone());
}
const distances = [0];
let total = 0;
for (let i = 1; i < points.length; i++) {
total += points[i].distanceTo(points[i - 1]);
distances.push(total);
}
const samples = [];
let segmentIndex = 1;
for (let i = 0; i < count; i++) {
const targetDistance = total * (i / (count - 1));
while (
segmentIndex < points.length - 1 &&
distances[segmentIndex] < targetDistance
) {
segmentIndex += 1;
}
const startDistance = distances[segmentIndex - 1];
const endDistance = distances[segmentIndex];
const segmentLength = endDistance - startDistance;
const t =
segmentLength > 1e-8
? (targetDistance - startDistance) / segmentLength
: 0;
samples.push(
points[segmentIndex - 1].clone().lerp(points[segmentIndex], t)
);
}
return samples;
}
const upAxis = new THREE.Vector3(0, 1, 0);
const segmentDirection = new THREE.Vector3();
const segmentQuaternion = new THREE.Quaternion();
function updateArm(time) {
const tip = currentTip();
const path = state.routePlan
.slice(0, Math.min(state.legIndex, state.routePlan.length))
.map((point) => point.clone());
if (state.legIndex < state.routePlan.length) {
path.push(tip);
} else if (path.length === 0 || !path[path.length - 1].equals(tip)) {
path.push(tip);
}
const spine = resamplePolyline(path, ARM_SEGMENTS + 1);
for (let i = 0; i < ARM_SEGMENTS; i++) {
const a = spine[i];
const b = spine[i + 1];
const t = i / (ARM_SEGMENTS - 1);
const radius = THREE.MathUtils.lerp(0.205, 0.105, t);
segmentDirection.subVectors(b, a);
const length = Math.max(segmentDirection.length(), 0.001);
segmentDirection.normalize();
segmentQuaternion.setFromUnitVectors(upAxis, segmentDirection);
const segment = armMeshes[i];
segment.position.copy(a).add(b).multiplyScalar(0.5);
segment.quaternion.copy(segmentQuaternion);
segment.scale.set(radius, length, radius);
const joint = jointMeshes[i];
joint.position.copy(a);
joint.scale.setScalar(radius * 0.78);
}
for (const sucker of suckerMeshes) {
const radius = THREE.MathUtils.lerp(
0.205,
0.105,
sucker.index / (ARM_SEGMENTS - 1)
);
sucker.mesh.position.copy(spine[sucker.index]);
sucker.mesh.position.y -= radius * 0.72;
sucker.mesh.scale.setScalar(1);
}
const lastDirection = spine[spine.length - 1]
.clone()
.sub(spine[spine.length - 2])
.normalize();
gripper.position.copy(tip);
gripper.quaternion.setFromUnitVectors(upAxis, lastDirection);
if (state.carried) {
sourceMesh.position.copy(tip);
sourceMesh.position.y += 0.27;
sourceMesh.rotation.y = time * 1.3;
sourceMesh.rotation.z = Math.sin(time * 1.7) * 0.12;
}
return tip;
}
function updateTransferState(tip) {
const sourceDistance = Math.hypot(
tip.x - SOURCE.x,
tip.z - SOURCE.z
);
if (!state.carried && !state.complete && sourceDistance < 0.64) {
state.carried = true;
state.selected = "target";
targetMaterial.color.setHex(0x5fc3ad);
targetMaterial.emissive.setHex(0x155a4f);
targetMaterial.emissiveIntensity = 0.38;
showToast(
"Amber seed attached. Add a clear route around the reef ridge.",
"success"
);
updateInterface();
}
const targetDistance = Math.hypot(
tip.x - TARGET.x,
tip.z - TARGET.z
);
if (state.carried && !state.complete && targetDistance < 0.72) {
state.complete = true;
state.carried = false;
state.selected = "complete";
sourceMesh.position.set(TARGET.x, 0.68, TARGET.z);
sourceMesh.rotation.set(0, timeNow * 0.8, 0);
successCard.classList.add("visible");
showToast("Transfer complete: the scripted route succeeded.", "success");
updateInterface();
}
}
// ---------------------------------------------------------------------
// Custom camera controls implemented without Three.js addons
// ---------------------------------------------------------------------
const cameraState = {
yaw: 0.63,
pitch: 0.72,
distance: 16.2,
target: new THREE.Vector3(0, 0.55, 0)
};
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
const horizontal = Math.cos(pitch) * distance;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
updateCamera();
const pointer = {
down: false,
moved: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
const floorPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const floorHit = new THREE.Vector3();
const interactiveObjects = [sourceMesh, targetMesh];
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
}
function findInteractiveHit(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(interactiveObjects, true);
if (!hits.length) {
return null;
}
let object = hits[0].object;
while (object && !object.userData.action) {
object = object.parent;
}
return object ? object.userData.action : null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
pointer.down = true;
pointer.moved = false;
pointer.startX = pointer.lastX = event.clientX;
pointer.startY = pointer.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointer.down) {
const totalDistance = Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
);
if (totalDistance > 4) {
pointer.moved = true;
}
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.32,
1.25
);
updateCamera();
} else {
const action = findInteractiveHit(event);
renderer.domElement.style.cursor = action ? "pointer" : "default";
if (action) {
const rect = viewport.getBoundingClientRect();
hoverLabel.textContent =
action === "source"
? "Select amber seed"
: "Select reef socket";
hoverLabel.style.left = `${event.clientX - rect.left}px`;
hoverLabel.style.top = `${event.clientY - rect.top}px`;
hoverLabel.style.opacity = "1";
} else {
hoverLabel.style.opacity = "0";
}
}
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", (event) => {
renderer.domElement.releasePointerCapture(event.pointerId);
renderer.domElement.style.cursor = "default";
if (!pointer.moved) {
const action = findInteractiveHit(event);
if (action === "source") {
if (!state.carried && !state.complete) {
addWaypoint(SOURCE.x, SOURCE.z, "source");
} else {
showToast("The amber seed is already on the arm.");
}
} else if (action === "target") {
if (state.carried) {
addWaypoint(TARGET.x, TARGET.z, "target");
} else {
showToast("Collect the amber seed before selecting the socket.", "warning");
}
} else {
setPointerFromEvent(event);
if (raycaster.ray.intersectPlane(floorPlane, floorHit)) {
addWaypoint(floorHit.x, floorHit.z, "manual");
}
}
}
pointer.down = false;
pointer.moved = false;
});
renderer.domElement.addEventListener("pointercancel", () => {
pointer.down = false;
pointer.moved = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
10.5,
23
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// ---------------------------------------------------------------------
// Interactive top-down planner
// ---------------------------------------------------------------------
minimap.addEventListener("pointerdown", (event) => {
const rect = minimap.getBoundingClientRect();
const x = (event.clientX - rect.left) / rect.width;
const y = (event.clientY - rect.top) / rect.height;
const worldX = THREE.MathUtils.lerp(WORLD.minX, WORLD.maxX, x);
const worldZ = THREE.MathUtils.lerp(WORLD.minZ, WORLD.maxZ, y);
addWaypoint(worldX, worldZ, "manual");
});
function mapX(x) {
return ((x - WORLD.minX) / (WORLD.maxX - WORLD.minX)) * minimap.width;
}
function mapY(z) {
return ((z - WORLD.minZ) / (WORLD.maxZ - WORLD.minZ)) * minimap.height;
}
function drawMinimap(tip) {
const context = mapContext;
const width = minimap.width;
const height = minimap.height;
context.clearRect(0, 0, width, height);
context.fillStyle = "#e8f4f1";
context.fillRect(0, 0, width, height);
context.strokeStyle = "rgba(75, 143, 137, 0.12)";
context.lineWidth = 1;
for (let x = -6; x <= 6; x++) {
context.beginPath();
context.moveTo(mapX(x), 0);
context.lineTo(mapX(x), height);
context.stroke();
}
for (let z = -4; z <= 4; z++) {
context.beginPath();
context.moveTo(0, mapY(z));
context.lineTo(width, mapY(z));
context.stroke();
}
// Reach envelope.
context.save();
context.beginPath();
context.ellipse(
mapX(BASE.x),
mapY(BASE.z),
(MAX_REACH / (WORLD.maxX - WORLD.minX)) * width,
(MAX_REACH / (WORLD.maxZ - WORLD.minZ)) * height,
0,
0,
Math.PI * 2
);
context.fillStyle = "rgba(53, 172, 155, 0.09)";
context.fill();
context.setLineDash([8, 8]);
context.strokeStyle = "rgba(31, 132, 122, 0.36)";
context.lineWidth = 2;
context.stroke();
context.restore();
// Obstacles.
for (const obstacle of obstacles) {
context.fillStyle = "#d96f64";
context.strokeStyle = "#ad4c4e";
context.lineWidth = 2;
const x = mapX(obstacle.x - obstacle.width / 2);
const y = mapY(obstacle.z - obstacle.depth / 2);
const w =
(obstacle.width / (WORLD.maxX - WORLD.minX)) * width;
const h =
(obstacle.depth / (WORLD.maxZ - WORLD.minZ)) * height;
context.fillRect(x, y, w, h);
context.strokeRect(x, y, w, h);
}
// Planned route.
if (state.routePlan.length > 1) {
context.beginPath();
context.moveTo(mapX(state.routePlan[0].x), mapY(state.routePlan[0].z));
for (let i = 1; i < state.routePlan.length; i++) {
context.lineTo(
mapX(state.routePlan[i].x),
mapY(state.routePlan[i].z)
);
}
context.strokeStyle = "#7057a8";
context.lineWidth = 6;
context.lineCap = "round";
context.lineJoin = "round";
context.stroke();
for (let i = 1; i < state.routePlan.length; i++) {
context.beginPath();
context.arc(
mapX(state.routePlan[i].x),
mapY(state.routePlan[i].z),
6,
0,
Math.PI * 2
);
context.fillStyle = "#f2c75f";
context.fill();
context.strokeStyle = "#805d22";
context.lineWidth = 2;
context.stroke();
}
}
// Base.
context.beginPath();
context.arc(mapX(BASE.x), mapY(BASE.z), 11, 0, Math.PI * 2);
context.fillStyle = "#7057a8";
context.fill();
// Source.
context.beginPath();
context.arc(mapX(SOURCE.x), mapY(SOURCE.z), 10, 0, Math.PI * 2);
context.fillStyle = state.carried ? "#d6942d" : "#f2b84b";
context.fill();
context.strokeStyle = "#8e5f1b";
context.lineWidth = 2;
context.stroke();
// Target.
context.beginPath();
context.arc(mapX(TARGET.x), mapY(TARGET.z), 12, 0, Math.PI * 2);
context.strokeStyle = state.complete ? "#188f77" : "#278e87";
context.lineWidth = 4;
context.stroke();
context.fillStyle = "rgba(55, 160, 145, 0.2)";
context.fill();
// Current arm tip.
context.beginPath();
context.arc(mapX(tip.x), mapY(tip.z), 8, 0, Math.PI * 2);
context.fillStyle = "#ffffff";
context.fill();
context.strokeStyle = "#207f78";
context.lineWidth = 3;
context.stroke();
}
// ---------------------------------------------------------------------
// Interface updates
// ---------------------------------------------------------------------
function updateInterface(tip = currentTip()) {
const reach = Math.hypot(tip.x - BASE.x, tip.z - BASE.z);
const waypointCount = state.routePlan.length - 1;
reachStat.textContent = `${reach.toFixed(1)} m`;
waypointStat.textContent = `${waypointCount}`;
transferStat.textContent = state.complete ? "1 / 1" : "0 / 1";
undoButton.disabled = waypointCount === 0;
sourceButton.disabled = state.carried || state.complete;
targetButton.disabled = !state.carried || state.complete;
if (state.complete) {
objectiveTitle.textContent = "Transfer verified";
objectiveStatus.textContent =
"The amber seed reached the reef socket through the scripted route.";
} else if (state.carried) {
objectiveTitle.textContent = "Deliver the amber seed";
objectiveStatus.textContent =
"Plot a clear centerline around the reef ridge, then select the socket.";
} else if (waypointCount > 0) {
objectiveTitle.textContent = "Approach the amber seed";
objectiveStatus.textContent =
"The arm is following your waypoints. Pickup occurs at the source.";
} else {
objectiveTitle.textContent = "Collect the amber seed";
objectiveStatus.textContent =
"Select the source or click “Plan to source.”";
}
}
sourceButton.addEventListener("click", () => {
addWaypoint(SOURCE.x, SOURCE.z, "source");
});
targetButton.addEventListener("click", () => {
if (!state.carried) {
showToast("Collect the amber seed first.", "warning");
return;
}
addWaypoint(TARGET.x, TARGET.z, "target");
});
undoButton.addEventListener("click", undoWaypoint);
resetButton.addEventListener("click", resetTask);
playAgainButton.addEventListener("click", resetTask);
pauseButton.addEventListener("click", () => {
state.paused = !state.paused;
pauseButton.textContent = state.paused ? "Resume motion" : "Pause motion";
showToast(state.paused ? "Scripted motion paused." : "Scripted motion resumed.");
});
hintButton.addEventListener("click", () => {
hintText.classList.toggle("visible");
hintButton.textContent = hintText.classList.contains("visible")
? "Hide route hint"
: "Show a route hint";
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLButtonElement) {
return;
}
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
} else if (event.key.toLowerCase() === "u") {
undoWaypoint();
} else if (event.key.toLowerCase() === "r") {
resetTask();
}
});
// ---------------------------------------------------------------------
// Resize and animation loop
// ---------------------------------------------------------------------
const resizeObserver = new ResizeObserver(() => {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
resizeObserver.observe(viewport);
const clock = new THREE.Clock();
let timeNow = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
timeNow += dt;
updateMotion(dt);
const tip = updateArm(timeNow);
updateTransferState(tip);
if (!state.carried && !state.complete) {
sourceMesh.position.copy(SOURCE);
sourceMesh.position.y += Math.sin(timeNow * 2.1) * 0.055;
sourceMesh.rotation.y = timeNow * 0.42;
}
sourceRing.rotation.z = timeNow * 0.25;
const targetPulse = 1 + Math.sin(timeNow * 2.4) * 0.035;
targetRing.scale.setScalar(targetPulse);
if (state.complete) {
sourceMesh.rotation.y += dt * 0.8;
sourceRing.material.opacity = 0.22;
} else {
sourceRing.material.opacity = 0.58;
}
updateInterface(tip);
drawMinimap(tip);
renderer.render(scene, camera);
}
updateRouteVisuals();
updateInterface();
animate();
</script>
</body>
</html>
```