Prompt specification
Build or customize the Three.js 3D scene "Garden path ant colony" 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: Garden path ant colony
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/garden-path-ant-colony-x0643
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts a voxel ant colony beside a garden path. Place a small nest entrance under a stone, a fallen leaf arch, damp soil patches, and several discrete food crumbs. Individual ants travel along coherent outgoing and return paths, with carried crumbs visibly attached during transport and removed from the food pile only once. Show simple local trail markers influencing route choices around a newly placed pebble. Keep the behavior rule explicit and schematic instead of claiming a complete biological colony simulation. A close ground-level camera should reveal the route under the leaf and the repeated traffic at the nest opening.
Working Three.js Starter (garden-path-ant-colony-x0643):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Ant Colony Beside a Garden Path</title>
<style>
:root {
color-scheme: light;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9cdb5;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#panel {
position: fixed;
top: 16px;
left: 16px;
width: min(350px, calc(100vw - 32px));
padding: 16px 17px 14px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 14px;
color: #26352b;
background: rgba(248, 246, 232, 0.91);
box-shadow: 0 12px 36px rgba(40, 51, 36, 0.18);
backdrop-filter: blur(8px);
user-select: none;
}
.kicker {
margin-bottom: 4px;
color: #687661;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0 0 8px;
font-size: 24px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.intro {
margin: 0 0 11px;
color: #526052;
font-size: 12px;
line-height: 1.45;
}
.rule {
margin: 0 0 8px;
padding: 9px 10px;
border-left: 3px solid #df9e29;
border-radius: 3px 8px 8px 3px;
background: rgba(229, 181, 79, 0.15);
font-size: 11.5px;
line-height: 1.42;
}
.rule strong {
display: block;
margin-bottom: 3px;
color: #765214;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin: 10px 0 12px;
}
.stat {
min-width: 0;
padding: 7px 8px;
border: 1px solid rgba(65, 79, 59, 0.13);
border-radius: 8px;
background: rgba(255, 255, 255, 0.48);
}
.stat b {
display: block;
overflow: hidden;
color: #334431;
font-size: 15px;
text-overflow: ellipsis;
white-space: nowrap;
}
.stat span {
display: block;
margin-top: 2px;
color: #71806d;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.buttons {
display: flex;
gap: 7px;
}
button {
flex: 1;
padding: 8px 9px;
border: 1px solid #87967d;
border-radius: 7px;
color: #344432;
background: rgba(255, 255, 255, 0.66);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
}
button:hover {
background: #fffdf2;
}
button:active {
transform: translateY(1px);
}
#hint {
position: fixed;
right: 14px;
bottom: 13px;
padding: 7px 10px;
border-radius: 8px;
color: rgba(39, 53, 40, 0.82);
background: rgba(250, 248, 235, 0.78);
font-size: 10px;
font-weight: 650;
pointer-events: none;
}
@media (max-width: 650px) {
#panel {
top: 10px;
left: 10px;
width: min(330px, calc(100vw - 20px));
padding: 12px 13px;
}
h1 {
font-size: 20px;
}
.intro {
display: none;
}
.rule {
font-size: 10.5px;
}
#hint {
right: 8px;
bottom: 8px;
}
}
</style>
</head>
<body>
<section id="panel">
<div class="kicker">Garden path / ant study</div>
<h1>Voxel colony</h1>
<p class="intro">
Ants use a shared route beside the paving, split around a newly placed
pebble, and pass repeatedly through the stone-covered nest entrance.
</p>
<div class="rule">
<strong>Explicit schematic rule — not a complete biological simulation</strong>
At the pebble fork, an outbound ant chooses the detour with more amber
trail-marker chips; ties split randomly. A returning ant deposits one
chip on its chosen detour. Every food crumb has one state:
pile → visibly carried → delivered.
</div>
<div class="stats">
<div class="stat">
<b id="outboundStat">0</b>
<span>Outbound</span>
</div>
<div class="stat">
<b id="returningStat">0</b>
<span>Returning</span>
</div>
<div class="stat">
<b id="crumbStat">0</b>
<span>Crumbs left</span>
</div>
</div>
<div class="stats" style="grid-template-columns: 1fr 1fr; margin-top: -4px;">
<div class="stat">
<b id="markerStat">South 0 / North 0</b>
<span>Local marker chips</span>
</div>
<div class="stat">
<b id="deliveredStat">0</b>
<span>Delivered</span>
</div>
</div>
<div class="buttons">
<button id="pauseButton" type="button">Pause motion</button>
<button id="cameraButton" type="button">Reset camera</button>
</div>
</section>
<div id="hint">Drag to orbit · wheel/pinch to zoom · double-click to reset</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 simple controls implemented directly in this file.
// -------------------------------------------------------------------------
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;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9cdb5);
scene.fog = new THREE.Fog(0xb9cdb5, 13, 34);
const camera = new THREE.PerspectiveCamera(
49,
window.innerWidth / window.innerHeight,
0.08,
70
);
const cameraTarget = new THREE.Vector3(-0.35, 0.24, 0.02);
const orbit = {
radius: 7.0,
theta: 0.53,
phi: 1.39
};
function resetCamera() {
orbit.radius = window.innerWidth / window.innerHeight < 0.9 ? 8.8 : 7.0;
orbit.theta = 0.53;
orbit.phi = 1.39;
updateCamera();
}
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
cameraTarget.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
cameraTarget.y + orbit.radius * Math.cos(orbit.phi),
cameraTarget.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(cameraTarget);
}
resetCamera();
let dragging = false;
let dragX = 0;
let dragY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
orbit.theta -= dx * 0.005;
orbit.phi = THREE.MathUtils.clamp(orbit.phi + dy * 0.004, 0.57, 1.52);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
2.8,
13.5
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
document.getElementById("cameraButton").addEventListener("click", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Lighting and material palette.
// -------------------------------------------------------------------------
const hemi = new THREE.HemisphereLight(0xe7f2d8, 0x6f5942, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff0d1, 3.2);
sun.position.set(-3.5, 8.0, 5.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -9;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 26;
sun.shadow.bias = -0.0007;
scene.add(sun);
const leafFill = new THREE.PointLight(0xffd798, 2.1, 4.2, 2);
leafFill.position.set(-1.95, 0.58, 0.1);
scene.add(leafFill);
const material = (color, roughness = 0.86, extra = {}) =>
new THREE.MeshStandardMaterial({ color, roughness, ...extra });
const M = {
grass: material(0x829c6b),
grassDark: material(0x6f895c),
soil: material(0x604735),
soilEdge: material(0x71543d),
trail: material(0x856047),
trailLight: material(0x987052),
damp: material(0x423c32, 0.42),
puddle: material(0x4e625b, 0.18, { metalness: 0.08 }),
stone: material(0x858982),
stoneLight: material(0x9a9d92),
stoneDark: material(0x686d68),
cavity: material(0x171914),
leafA: material(0xb96b2f),
leafB: material(0xd18a37),
leafC: material(0x8f6530),
stem: material(0x68502d),
pebble: material(0x777d78),
pebbleLight: material(0x969b91),
pebbleDark: material(0x626863),
pavingA: material(0xb7ad93),
pavingB: material(0xc8bea4),
pavingC: material(0xa89f87),
wood: material(0x7b5a3d),
woodLight: material(0x98714b),
antBody: material(0x34231b),
antHead: material(0x241713),
antLeg: material(0x1e1713),
antEye: material(0x090807, 0.35),
marker: material(0xffbd35, 0.48, {
emissive: 0x6d3700,
emissiveIntensity: 0.62
})
};
// A deterministic random source keeps the landscape stable between reloads.
let seed = 142857;
function random() {
seed |= 0;
seed = (seed + 0x6D2B79F5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const rand = (min, max) => min + (max - min) * random();
function box(parent, size, position, mat, rotation = [0, 0, 0]) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
mat
);
mesh.position.set(position[0], position[1], position[2]);
mesh.rotation.set(rotation[0], rotation[1], rotation[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Garden path, soil bed, damp patches, fence, and plants.
// -------------------------------------------------------------------------
box(scene, [24, 0.44, 16], [0, -0.24, 0], M.grass);
box(scene, [15.5, 0.12, 6.4], [0, 0.005, 0.48], M.soil);
box(scene, [15.5, 0.08, 0.22], [0, 0.045, -2.72], M.soilEdge);
// Pale, voxel paving stones beside the ant route.
const pavingMaterials = [M.pavingA, M.pavingB, M.pavingC];
for (let i = 0; i < 13; i++) {
const x = -7.2 + i * 1.2;
const z = -3.48 + (i % 2 === 0 ? 0.035 : -0.035);
const h = rand(0.15, 0.20);
box(
scene,
[1.02, h, 1.34],
[x, h * 0.5 + 0.015, z],
pavingMaterials[i % pavingMaterials.length]
);
box(
scene,
[0.18, 0.09, 0.20],
[x - 0.54, 0.06, -2.69],
M.stone
);
}
// A low wooden garden fence in the distance.
for (let x = -8; x <= 8; x += 2) {
box(scene, [0.16, 1.05, 0.16], [x, 0.52, -6.2], M.wood);
box(scene, [0.22, 0.11, 0.22], [x, 1.05, -6.2], M.woodLight);
}
box(scene, [16.2, 0.13, 0.14], [0, 0.40, -6.2], M.wood);
box(scene, [16.2, 0.13, 0.14], [0, 0.79, -6.2], M.woodLight);
// Grass tufts around the paving.
const grassMaterials = [M.grass, M.grassDark];
for (let i = 0; i < 52; i++) {
const x = rand(-8.3, 8.3);
const z = rand(-4.75, -2.43);
const h = rand(0.12, 0.28);
box(
scene,
[0.035, h, 0.045],
[x, h * 0.5 + 0.015, z],
grassMaterials[i % 2],
[rand(-0.22, 0.22), 0, rand(-0.28, 0.28)]
);
}
// Irregular damp soil clusters and shallow blue-grey puddles.
function dampPatch(cx, cz, sx, sz) {
for (let i = 0; i < 8; i++) {
const w = rand(0.18, 0.52) * sx;
const d = rand(0.15, 0.40) * sz;
const x = cx + rand(-0.35, 0.35) * sx;
const z = cz + rand(-0.28, 0.28) * sz;
box(scene, [w, 0.018, d], [x, 0.074, z], M.damp);
}
box(
scene,
[0.62 * sx, 0.012, 0.40 * sz],
[cx, 0.087, cz],
M.puddle
);
}
dampPatch(-3.55, 0.90, 1.0, 0.8);
dampPatch(-1.40, 1.65, 0.8, 0.65);
dampPatch(2.60, -0.72, 0.9, 0.7);
dampPatch(4.18, 1.55, 0.75, 0.6);
// -------------------------------------------------------------------------
// The shared route graph. Coordinates are [x, z] on the ground.
// -------------------------------------------------------------------------
const N = {
nest: [-5.05, -0.20],
door: [-5.05, 0.62],
turn: [-4.38, 0.88],
west: [-3.25, 0.28],
leaf: [-1.95, 0.00],
forkA: [-0.70, 0.05],
s1: [-0.72, -1.20],
s2: [ 1.12, -1.18],
s3: [ 1.48, -0.12],
n1: [-0.72, 1.18],
n2: [ 1.12, 1.20],
n3: [ 1.48, 0.18],
merge: [2.25, 0.48],
mid: [3.55, 1.27],
food: [5.05, 2.12]
};
const BASE_ROUTE = [
N.nest, N.door, N.turn, N.west, N.leaf, N.forkA
];
const branches = {
south: {
nodes: ["forkA", "s1", "s2", "s3", "merge"],
edges: [
{ a: "forkA", b: "s1", count: 3 },
{ a: "s1", b: "s2", count: 3 },
{ a: "s2", b: "s3", count: 1 },
{ a: "s3", b: "merge", count: 0 }
]
},
north: {
nodes: ["forkA", "n1", "n2", "n3", "merge"],
edges: [
{ a: "forkA", b: "n1", count: 0 },
{ a: "n1", b: "n2", count: 1 },
{ a: "n2", b: "n3", count: 0 },
{ a: "n3", b: "merge", count: 0 }
]
}
};
const mainEdges = [
["nest", "door"],
["door", "turn"],
["turn", "west"],
["west", "leaf"],
["leaf", "forkA"],
["merge", "mid"],
["mid", "food"]
];
function addTrailStrip(aKey, bKey, width = 0.42, mat = M.trail) {
const a = N[aKey];
const b = N[bKey];
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz);
const angle = -Math.atan2(dz, dx);
box(
scene,
[length, 0.018, width],
[(a[0] + b[0]) * 0.5, 0.077, (a[1] + b[1]) * 0.5],
mat,
[0, angle, 0]
);
// Small packed-earth voxels make the route legible without hiding ants.
for (let i = 0; i < 3; i++) {
const t = (i + 1) / 4;
const x = a[0] + dx * t + rand(-0.12, 0.12);
const z = a[1] + dz * t + rand(-0.12, 0.12);
box(
scene,
[rand(0.06, 0.13), 0.022, rand(0.05, 0.11)],
[x, 0.096, z],
M.trailLight,
[0, rand(0, Math.PI), 0]
);
}
}
for (const [a, b] of mainEdges) addTrailStrip(a, b);
for (const branch of Object.values(branches)) {
for (const edge of branch.edges) {
addTrailStrip(edge.a, edge.b, 0.40, M.trailLight);
}
}
// -------------------------------------------------------------------------
// Stone-covered nest entrance, facing toward the camera.
// -------------------------------------------------------------------------
box(scene, [1.45, 0.055, 1.25], [-5.05, 0.073, 0.22], M.soilEdge);
box(scene, [0.72, 0.025, 0.80], [-5.05, 0.095, 0.20], M.cavity);
// The dark back wall makes the opening read as a cavity.
box(scene, [0.74, 0.26, 0.055], [-5.05, 0.20, -0.18], M.cavity);
box(scene, [0.31, 0.57, 0.60], [-5.48, 0.37, 0.37], M.stoneDark);
box(scene, [0.31, 0.57, 0.60], [-4.62, 0.37, 0.37], M.stone);
box(scene, [1.18, 0.27, 0.78], [-5.05, 0.76, 0.34], M.stoneLight);
box(scene, [0.82, 0.16, 0.59], [-5.08, 0.96, 0.31], M.stone, [0, 0.04, 0]);
box(scene, [0.28, 0.14, 0.32], [-5.50, 1.08, 0.25], M.stoneDark);
// -------------------------------------------------------------------------
// Fallen leaf arch over the route.
// -------------------------------------------------------------------------
const leafMaterials = [M.leafA, M.leafB, M.leafC];
for (let i = 0; i <= 14; i++) {
const t = -1 + (2 * i) / 14;
const z = t * 1.06;
const y = 0.22 + 0.68 * (1 - t * t);
const x = -1.95 + 0.07 * Math.cos(t * Math.PI);
const tilt = Math.atan(0.65 * t);
box(
scene,
[0.36, 0.13, 0.22],
[x, y, z],
leafMaterials[i % leafMaterials.length],
[tilt, 0.04 * Math.sin(i), 0]
);
// A narrow raised vein follows the top of the leaf.
box(
scene,
[0.39, 0.035, 0.045],
[x, y + 0.075, z],
M.stem,
[tilt, 0, 0]
);
}
box(scene, [0.10, 0.09, 0.36], [-1.95, 0.13, -1.10], M.stem, [0.18, 0, 0]);
box(scene, [0.10, 0.09, 0.36], [-1.95, 0.13, 1.10], M.stem, [-0.18, 0, 0]);
// -------------------------------------------------------------------------
// Newly placed pebble. It blocks the old straight line between the two
// branches, so ants visibly use the north or south detour.
// -------------------------------------------------------------------------
box(scene, [1.10, 0.025, 1.02], [-0.05, 0.088, 0.15], M.soilEdge);
box(scene, [0.52, 0.35, 0.48], [-0.05, 0.27, 0.15], M.pebble);
box(scene, [0.34, 0.18, 0.32], [-0.08, 0.52, 0.13], M.pebbleLight);
box(scene, [0.20, 0.20, 0.22], [ 0.25, 0.19, 0.20], M.pebbleDark);
// A few pale disturbed-soil voxels suggest that the pebble was just set down.
for (let i = 0; i < 8; i++) {
const a = (i / 8) * Math.PI * 2;
box(
scene,
[0.09, 0.025, 0.07],
[-0.05 + Math.cos(a) * 0.59, 0.106, 0.15 + Math.sin(a) * 0.53],
M.trailLight,
[0, a, 0]
);
}
// -------------------------------------------------------------------------
// Local trail markers: visible amber chips beside detour edges.
// -------------------------------------------------------------------------
const markerGeometry = new THREE.BoxGeometry(0.070, 0.070, 0.070);
for (const branch of Object.values(branches)) {
for (const edge of branch.edges) {
edge.group = new THREE.Group();
scene.add(edge.group);
rebuildMarkers(edge);
}
}
function rebuildMarkers(edge) {
edge.group.clear();
const a = N[edge.a];
const b = N[edge.b];
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz);
const px = -dz / length;
const pz = dx / length;
for (let i = 0; i < edge.count; i++) {
const t = (i + 1) / (edge.count + 1);
const side = i % 2 === 0 ? 1 : -1;
const marker = new THREE.Mesh(markerGeometry, M.marker);
marker.position.set(
a[0] + dx * t + px * 0.20 * side,
0.125,
a[1] + dz * t + pz * 0.20 * side
);
marker.rotation.y = i * 0.43;
marker.castShadow = true;
edge.group.add(marker);
}
}
function branchScore(branchName) {
return branches[branchName].edges.reduce(
(sum, edge) => sum + edge.count,
0
);
}
function chooseBranch() {
const south = branchScore("south");
const north = branchScore("north");
if (south > north) return "south";
if (north > south) return "north";
return random() < 0.5 ? "south" : "north";
}
function depositMarker(ant) {
const branch = branches[ant.branch];
const edge = branch.edges[random() < 0.65 ? 0 : 1];
if (edge.count < 10) {
edge.count++;
rebuildMarkers(edge);
}
}
// -------------------------------------------------------------------------
// Food pile. Each source crumb has exactly one mutable state.
// -------------------------------------------------------------------------
const crumbGeometry = new THREE.BoxGeometry(1, 1, 1);
const crumbMaterials = [
material(0xd59a50),
material(0xe0b66a),
material(0xb87836),
material(0xc99143)
];
const crumbs = [];
box(scene, [1.62, 0.026, 1.35], [5.08, 0.087, 2.12], M.soilEdge);
for (let i = 0; i < 24; i++) {
const angle = rand(0, Math.PI * 2);
const radius = Math.sqrt(random()) * 0.63;
const sx = rand(0.065, 0.12);
const sy = rand(0.045, 0.085);
const sz = rand(0.055, 0.11);
const mesh = new THREE.Mesh(
crumbGeometry,
crumbMaterials[i % crumbMaterials.length]
);
mesh.position.set(
5.08 + Math.cos(angle) * radius,
0.105 + sy * 0.5,
2.12 + Math.sin(angle) * radius * 0.76
);
mesh.scale.set(sx, sy, sz);
mesh.rotation.set(rand(-0.25, 0.25), rand(0, Math.PI), rand(-0.2, 0.2));
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
crumbs.push({
mesh,
state: "available"
});
}
// -------------------------------------------------------------------------
// Voxel ants.
// -------------------------------------------------------------------------
const antMaterials = {
abdomen: material(0x3a261c),
thorax: material(0x2d1d16),
head: material(0x241713),
leg: M.antLeg,
eye: M.antEye
};
function createAntModel() {
const group = new THREE.Group();
const legs = [];
const abdomen = box(group, [0.135, 0.105, 0.155], [0, 0.080, -0.16], antMaterials.abdomen);
abdomen.rotation.x = -0.10;
box(group, [0.105, 0.095, 0.105], [0, 0.076, 0], antMaterials.thorax);
box(group, [0.115, 0.105, 0.115], [0, 0.078, 0.145], antMaterials.head);
// Six blocky legs, alternating their animation phase.
for (const side of [-1, 1]) {
for (let i = 0; i < 3; i++) {
const leg = box(
group,
[0.018, 0.026, 0.155],
[side * 0.070, 0.026, -0.105 + i * 0.105],
antMaterials.leg,
[0, side * 0.58, 0]
);
leg.userData.phase = (i + (side > 0 ? 1 : 0)) * Math.PI;
legs.push(leg);
}
}
// Short antennae and tiny eyes.
for (const side of [-1, 1]) {
box(
group,
[0.014, 0.014, 0.115],
[side * 0.035, 0.140, 0.220],
antMaterials.leg,
[0.18, side * 0.32, 0]
);
box(
group,
[0.019, 0.025, 0.022],
[side * 0.059, 0.090, 0.176],
antMaterials.eye
);
}
scene.add(group);
return { group, legs };
}
const ants = [];
function outboundPath(branchName) {
return BASE_ROUTE.concat(
branches[branchName].nodes.slice(1).map((key) => N[key]),
[N.merge, N.mid, N.food]
);
}
function placeAntOnSegment(ant, segment, t) {
const a = ant.route[segment];
const b = ant.route[segment + 1];
ant.group.position.set(
a[0] + (b[0] - a[0]) * t,
0.086,
a[1] + (b[1] - a[1]) * t
);
ant.targetIndex = segment + 1;
}
function claimCrumb(antGroup) {
const crumb = crumbs.find((item) => item.state === "available");
if (!crumb) return null;
// Claim happens exactly once. The same mesh becomes the carried crumb.
crumb.state = "carried";
crumb.mesh.removeFromParent();
antGroup.add(crumb.mesh);
crumb.mesh.position.set(0, 0.103, 0.305);
crumb.mesh.rotation.set(0.12, random(-0.3, 0.3), 0.08);
return crumb;
}
function createAnt(options = {}) {
const model = createAntModel();
const ant = {
group: model.group,
legs: model.legs,
state: "outbound",
branch: null,
route: BASE_ROUTE.slice(),
outboundPath: null,
targetIndex: 1,
crumb: null,
speed: rand(0.54, 0.78),
phase: rand(0, Math.PI * 2),
deposited: false,
timer: 0
};
if (options.returner) {
ant.branch = options.branch || chooseBranch();
ant.outboundPath = outboundPath(ant.branch);
ant.route = ant.outboundPath.slice().reverse();
ant.state = "returning";
ant.crumb = claimCrumb(ant.group);
if (!ant.crumb) {
scene.remove(ant.group);
return null;
}
} else if (options.startSegment >= BASE_ROUTE.length - 1) {
// This initial ant has already passed the fork.
ant.branch = chooseBranch();
ant.outboundPath = outboundPath(ant.branch);
ant.route = ant.outboundPath.slice();
}
if (options.startSegment !== undefined) {
const maxSegment = ant.route.length - 2;
const segment = THREE.MathUtils.clamp(options.startSegment, 0, maxSegment);
placeAntOnSegment(ant, segment, options.startT ?? 0.25);
} else {
ant.group.position.set(ant.route[0][0], 0.086, ant.route[0][1]);
ant.targetIndex = 1;
}
ants.push(ant);
return ant;
}
// -------------------------------------------------------------------------
// Small delivery burst at the nest.
// -------------------------------------------------------------------------
const particles = [];
function deliveryBurst(x, y, z) {
for (let i = 0; i < 5; i++) {
const mesh = new THREE.Mesh(
crumbGeometry,
crumbMaterials[i % crumbMaterials.length]
);
mesh.scale.setScalar(rand(0.035, 0.06));
mesh.position.set(x, y, z);
mesh.castShadow = true;
scene.add(mesh);
particles.push({
mesh,
velocity: new THREE.Vector3(rand(-0.35, 0.35), rand(0.25, 0.65), rand(-0.25, 0.25)),
life: 0.5,
maxLife: 0.5
});
}
}
function updateParticles(dt) {
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= dt;
particle.velocity.y -= 1.6 * dt;
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.mesh.scale.multiplyScalar(Math.max(0.01, 1 - dt * 1.8));
if (particle.life <= 0) {
scene.remove(particle.mesh);
particles.splice(i, 1);
}
}
}
// -------------------------------------------------------------------------
// Initial population: outbound traffic plus a few already-loaded returners.
// -------------------------------------------------------------------------
createAnt({ startSegment: 0, startT: 0.1 });
createAnt({ startSegment: 1, startT: 0.35 });
createAnt({ startSegment: 2, startT: 0.55 });
createAnt({ startSegment: 3, startT: 0.30 });
createAnt({ startSegment: 4, startT: 0.65 });
createAnt({ startSegment: 6, startT: 0.30 });
createAnt({ startSegment: 8, startT: 0.45 });
createAnt({ returner: true, startSegment: 4, startT: 0.35 });
createAnt({ returner: true, startSegment: 5, startT: 0.55 });
createAnt({ returner: true, startSegment: 6, startT: 0.25 });
let spawnTimer = 0.65;
function updateAnt(ant, dt) {
if (ant.state === "leaving") {
ant.timer -= dt;
const scale = Math.max(0.001, ant.timer / 0.38);
ant.group.scale.setScalar(scale);
if (ant.timer <= 0) {
scene.remove(ant.group);
return false;
}
return true;
}
if (ant.state === "noFood") {
ant.timer -= dt;
if (ant.timer <= 0) {
scene.remove(ant.group);
return false;
}
return true;
}
const target = ant.route[ant.targetIndex];
if (!target) return true;
const dx = target[0] - ant.group.position.x;
const dz = target[1] - ant.group.position.z;
const distance = Math.hypot(dx, dz);
const step = ant.speed * dt;
if (distance <= step) {
ant.group.position.x = target[0];
ant.group.position.z = target[1];
ant.targetIndex++;
} else {
ant.group.position.x += dx / distance * step;
ant.group.position.z += dz / distance * step;
ant.group.rotation.y = Math.atan2(dx, dz);
}
ant.phase += dt * 13;
for (const leg of ant.legs) {
leg.rotation.x = Math.sin(ant.phase + leg.userData.phase) * 0.34;
}
// The outbound ant reaches the fork, observes the current local marker
// counts, and then commits to one of the two detour branches.
if (
ant.state === "outbound" &&
ant.branch === null &&
ant.targetIndex >= ant.route.length
) {
ant.branch = chooseBranch();
const fullRoute = outboundPath(ant.branch);
ant.route = fullRoute;
ant.outboundPath = fullRoute.slice();
ant.targetIndex = BASE_ROUTE.length;
return true;
}
if (ant.state === "returning" && !ant.deposited) {
// Deposit after the returning ant has passed the pebble and entered
// the detour portion of the route.
const depositIndex = ant.branch === "south" ? 5 : 5;
if (ant.targetIndex >= depositIndex) {
depositMarker(ant);
ant.deposited = true;
}
}
if (ant.state === "outbound" && ant.targetIndex >= ant.route.length) {
const crumb = claimCrumb(ant.group);
if (crumb) {
ant.crumb = crumb;
ant.state = "returning";
ant.route = ant.outboundPath.slice().reverse();
ant.targetIndex = 1;
ant.deposited = false;
} else {
ant.state = "noFood";
ant.timer = 1.8;
}
}
if (ant.state === "returning" && ant.targetIndex >= ant.route.length) {
if (ant.crumb) {
ant.crumb.mesh.removeFromParent();
ant.crumb.state = "delivered";
deliveryBurst(-5.05, 0.20, 0.10);
ant.crumb = null;
}
ant.state = "leaving";
ant.timer = 0.38;
}
return true;
}
// -------------------------------------------------------------------------
// UI state and animation loop.
// -------------------------------------------------------------------------
const outboundStat = document.getElementById("outboundStat");
const returningStat = document.getElementById("returningStat");
const crumbStat = document.getElementById("crumbStat");
const markerStat = document.getElementById("markerStat");
const deliveredStat = document.getElementById("deliveredStat");
const pauseButton = document.getElementById("pauseButton");
let paused = false;
let uiTimer = 0;
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume motion" : "Pause motion";
});
function updateUI() {
outboundStat.textContent = ants.filter((ant) => ant.state === "outbound").length;
returningStat.textContent = ants.filter((ant) => ant.state === "returning").length;
const available = crumbs.filter((crumb) => crumb.state === "available").length;
const delivered = crumbs.filter((crumb) => crumb.state === "delivered").length;
crumbStat.textContent = available;
deliveredStat.textContent = delivered;
markerStat.textContent =
`South ${branchScore("south")} / North ${branchScore("north")}`;
}
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.04);
if (!paused) {
spawnTimer -= dt;
if (spawnTimer <= 0) {
spawnTimer = 0.62;
if (ants.length < 13) createAnt();
}
for (let i = ants.length - 1; i >= 0; i--) {
if (!updateAnt(ants[i], dt)) {
ants.splice(i, 1);
}
}
updateParticles(dt);
}
uiTimer -= dt;
if (uiTimer <= 0) {
uiTimer = 0.15;
updateUI();
}
renderer.render(scene, camera);
});
updateUI();
</script>
</body>
</html>
```