Prompt specification
Build or customize the Three.js 3D scene "Ant-route obstruction experiment" 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: Ant-route obstruction experiment
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/ant-route-obstruction-experiment-x0644
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts ant foraging trails. Create a bounded foraging network where users add an obstacle; local-rule agents gradually establish an alternate route, with labels clarifying that behavior is a simplified collective model. Low-poly.
Working Three.js Starter (ant-route-obstruction-experiment-x0644):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Collective Foraging — Ant Trail Laboratory</title>
<style>
:root {
--bg: #101817;
--panel: rgba(18, 29, 27, 0.88);
--panel-border: rgba(232, 240, 223, 0.13);
--text: #eef1df;
--muted: #a7b1a2;
--accent: #e9b85f;
--accent-bright: #ffd783;
--mint: #8fd6ae;
--danger: #f18b72;
}
* {
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;
}
button,
input {
font: inherit;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--accent-bright);
outline-offset: 3px;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#scene.placing {
cursor: crosshair;
}
#topbar {
position: fixed;
z-index: 10;
top: 20px;
left: 22px;
right: 22px;
display: flex;
align-items: flex-start;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.45);
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border: 1px solid rgba(255, 215, 131, 0.36);
border-radius: 13px;
background: rgba(19, 30, 28, 0.78);
color: var(--accent-bright);
box-shadow: inset 0 0 24px rgba(233, 184, 95, 0.07);
}
.brand-mark svg {
width: 25px;
height: 25px;
}
.eyebrow {
margin: 0 0 3px;
color: var(--accent);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(18px, 2.1vw, 27px);
font-weight: 720;
letter-spacing: -0.035em;
}
.live-pill {
display: flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
border: 1px solid rgba(143, 214, 174, 0.22);
border-radius: 999px;
background: rgba(15, 25, 23, 0.72);
color: #c6d8c8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
backdrop-filter: blur(12px);
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 12px rgba(143, 214, 174, 0.85);
}
#model-card {
position: fixed;
z-index: 10;
top: 92px;
left: 22px;
width: min(310px, calc(100vw - 44px));
padding: 17px 18px 15px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(18px) saturate(1.15);
}
.model-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.model-title strong {
font-size: 11px;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.tag {
padding: 4px 7px;
border-radius: 6px;
background: rgba(233, 184, 95, 0.12);
color: var(--accent-bright);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#model-card p {
margin: 0;
color: #bdc6b8;
font-size: 12px;
line-height: 1.58;
}
#model-card p strong {
color: #edf0dd;
font-weight: 650;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 15px;
padding-top: 13px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.metric {
min-width: 0;
}
.metric span {
display: block;
color: #829084;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
color: #f0f1df;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.signal-track {
height: 3px;
margin-top: 12px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.07);
}
#signal-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #b67832, #ffd783);
transition: width 0.25s ease;
}
#legend {
position: fixed;
z-index: 9;
top: 92px;
right: 22px;
width: 170px;
padding: 13px 14px;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: rgba(18, 29, 27, 0.72);
color: var(--muted);
font-size: 10px;
line-height: 1.8;
backdrop-filter: blur(14px);
pointer-events: none;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.legend-dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 9px rgba(233, 184, 95, 0.55);
}
.legend-dot.ant {
width: 7px;
height: 7px;
background: #1d1511;
box-shadow: none;
}
.legend-dot.rock {
width: 10px;
height: 10px;
border-radius: 2px;
background: #84908b;
box-shadow: none;
transform: rotate(15deg);
}
.legend-note {
margin-top: 7px;
padding-top: 7px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: #7f8c81;
}
#controls {
position: fixed;
z-index: 12;
left: 50%;
bottom: 20px;
display: flex;
align-items: center;
gap: 8px;
width: max-content;
max-width: calc(100vw - 30px);
padding: 9px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: rgba(16, 26, 24, 0.9);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.34);
transform: translateX(-50%);
backdrop-filter: blur(18px) saturate(1.15);
}
.control-button {
min-height: 38px;
padding: 0 13px;
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 10px;
background: rgba(255, 255, 255, 0.045);
color: #d9dfd0;
font-size: 11px;
font-weight: 650;
cursor: pointer;
transition:
background 0.16s ease,
border-color 0.16s ease,
transform 0.16s ease;
}
.control-button:hover {
background: rgba(255, 255, 255, 0.09);
border-color: rgba(255, 255, 255, 0.19);
}
.control-button:active {
transform: translateY(1px);
}
.control-button.primary {
border-color: rgba(233, 184, 95, 0.42);
background: rgba(233, 184, 95, 0.15);
color: #ffdc91;
}
.control-button.primary:hover,
.control-button.primary.active {
border-color: rgba(255, 215, 131, 0.7);
background: rgba(233, 184, 95, 0.27);
}
.divider {
width: 1px;
height: 27px;
margin: 0 3px;
background: rgba(255, 255, 255, 0.1);
}
.toggle {
display: flex;
align-items: center;
gap: 8px;
padding: 0 5px;
color: #b6c1b2;
font-size: 10px;
font-weight: 700;
white-space: nowrap;
cursor: pointer;
}
.toggle input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.toggle-ui {
position: relative;
width: 30px;
height: 17px;
border-radius: 999px;
background: #35423b;
transition: background 0.2s ease;
}
.toggle-ui::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 11px;
height: 11px;
border-radius: 50%;
background: #acb6a9;
transition:
left 0.2s ease,
background 0.2s ease;
}
.toggle input:checked + .toggle-ui {
background: #9a6c31;
}
.toggle input:checked + .toggle-ui::after {
left: 16px;
background: #ffd783;
}
.speed-control {
display: flex;
align-items: center;
gap: 9px;
padding-right: 5px;
color: #9da99d;
font-size: 10px;
font-weight: 700;
white-space: nowrap;
}
#speed {
width: 84px;
accent-color: var(--accent);
cursor: pointer;
}
#speed-value {
width: 27px;
color: var(--accent-bright);
font-variant-numeric: tabular-nums;
}
#placement-hint {
position: fixed;
z-index: 15;
top: 24px;
left: 50%;
padding: 10px 15px;
border: 1px solid rgba(255, 215, 131, 0.32);
border-radius: 999px;
background: rgba(34, 37, 27, 0.9);
color: #ffe0a0;
font-size: 11px;
font-weight: 700;
opacity: 0;
transform: translate(-50%, -8px);
transition:
opacity 0.2s ease,
transform 0.2s ease;
pointer-events: none;
}
#placement-hint.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#toast {
position: fixed;
z-index: 20;
left: 50%;
bottom: 92px;
max-width: min(440px, calc(100vw - 30px));
padding: 11px 15px;
border: 1px solid rgba(143, 214, 174, 0.25);
border-radius: 11px;
background: rgba(17, 29, 26, 0.94);
color: #d8e5d5;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.25);
font-size: 11px;
line-height: 1.45;
text-align: center;
opacity: 0;
transform: translate(-50%, 8px);
transition:
opacity 0.2s ease,
transform 0.2s ease;
pointer-events: none;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#world-labels {
position: fixed;
z-index: 7;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
top: 0;
left: 0;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 7px;
background: rgba(13, 21, 19, 0.72);
color: #dbe2d4;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
white-space: nowrap;
transform: translate(-50%, -50%);
backdrop-filter: blur(7px);
}
.world-label.food {
border-color: rgba(233, 184, 95, 0.24);
color: #f0c879;
}
.world-label.nest {
border-color: rgba(143, 214, 174, 0.24);
color: #9fd9b7;
}
#camera-help {
position: fixed;
z-index: 8;
right: 22px;
bottom: 20px;
color: rgba(211, 220, 204, 0.54);
font-size: 9px;
letter-spacing: 0.04em;
pointer-events: none;
}
@media (max-width: 850px) {
#legend {
display: none;
}
#model-card {
top: 80px;
width: 280px;
}
#model-card p {
font-size: 11px;
}
#camera-help {
display: none;
}
#controls {
flex-wrap: wrap;
justify-content: center;
width: min(610px, calc(100vw - 24px));
}
}
@media (max-width: 560px) {
#topbar {
top: 14px;
left: 14px;
right: 14px;
}
.brand-mark {
width: 36px;
height: 36px;
}
h1 {
font-size: 17px;
}
.brand .eyebrow {
font-size: 8px;
}
.live-pill {
padding: 7px 9px;
font-size: 8px;
}
#model-card {
top: 67px;
left: 12px;
width: 255px;
padding: 13px 14px;
}
#model-card p {
font-size: 10px;
line-height: 1.45;
}
.metrics {
margin-top: 10px;
padding-top: 9px;
}
.metric strong {
font-size: 13px;
}
#controls {
bottom: 10px;
gap: 5px;
padding: 7px;
}
.control-button {
min-height: 34px;
padding: 0 9px;
font-size: 9px;
}
.speed-control {
font-size: 9px;
}
#speed {
width: 62px;
}
.divider {
display: none;
}
#placement-hint {
top: 63px;
width: max-content;
max-width: calc(100vw - 24px);
font-size: 9px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly ant foraging simulation"></canvas>
<header id="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 32 32" fill="none">
<path
d="M8 23c0-6 3-10 8-10s8 4 8 10M16 13V7M12 9l4 4 4-4M10 16l-4-3M22 16l4-3M10 20l-4 2M22 20l4 2"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
<circle cx="16" cy="6" r="2.5" fill="currentColor" />
</svg>
</div>
<div>
<p class="eyebrow">Collective behavior laboratory</p>
<h1>Foraging Networks</h1>
</div>
</div>
<div class="live-pill">
<span class="live-dot"></span>
Simulation live
</div>
</header>
<aside id="model-card">
<div class="model-title">
<strong>Simplified collective model</strong>
<span class="tag">24 × 18 arena</span>
</div>
<p>
Each ant samples only <strong>nearby pheromone</strong>,
<strong>nearby obstacles</strong>, and a goal bearing. Returning ants
reinforce odor; outbound ants can follow that odor in reverse.
<strong>No map, planner, or central controller is used.</strong>
</p>
<div class="metrics">
<div class="metric">
<span>Agents</span>
<strong id="metric-agents">110</strong>
</div>
<div class="metric">
<span>Barriers</span>
<strong id="metric-obstacles">0</strong>
</div>
<div class="metric">
<span>Trail signal</span>
<strong id="metric-signal">0%</strong>
</div>
</div>
<div class="signal-track" aria-hidden="true">
<div id="signal-fill"></div>
</div>
</aside>
<aside id="legend" aria-label="Scene legend">
<div class="legend-row">
<span class="legend-dot"></span>
<span>Pheromone concentration</span>
</div>
<div class="legend-row">
<span class="legend-dot ant"></span>
<span>Foraging ant</span>
</div>
<div class="legend-row">
<span class="legend-dot rock"></span>
<span>User obstacle</span>
</div>
<div class="legend-note">
Amber paths are a visual abstraction of chemical trail strength.
</div>
</aside>
<div id="world-labels" aria-hidden="true">
<div class="world-label nest" id="label-nest">NEST</div>
<div class="world-label food" id="label-food-a">FOOD A</div>
<div class="world-label food" id="label-food-b">FOOD B</div>
</div>
<div id="placement-hint">
Click the soil to place an obstacle · Esc to cancel
</div>
<div id="toast" role="status" aria-live="polite"></div>
<nav id="controls" aria-label="Simulation controls">
<button
class="control-button primary"
id="place-obstacle"
type="button"
aria-pressed="false"
>
+ Place obstacle
</button>
<button class="control-button" id="clear-obstacles" type="button">
Clear rocks
</button>
<button class="control-button" id="restart" type="button">
Restart colony
</button>
<div class="divider"></div>
<label class="toggle">
<input id="show-pheromone" type="checkbox" checked />
<span class="toggle-ui"></span>
Pheromone
</label>
<label class="speed-control" for="speed">
Speed
<input
id="speed"
type="range"
min="0.5"
max="2.5"
step="0.1"
value="1.4"
/>
<output id="speed-value" for="speed">1.4×</output>
</label>
</nav>
<div id="camera-help">
Drag to orbit · right-drag to pan · scroll to zoom
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
// ------------------------------------------------------------
// Configuration
// ------------------------------------------------------------
const ARENA_W = 24;
const ARENA_D = 18;
const ANT_COUNT = 110;
const FOOD_POSITIONS = [
new THREE.Vector2(-7.5, -5.7),
new THREE.Vector2(7.5, -5.7)
];
const NEST_POSITION = new THREE.Vector2(0, 6.5);
const PH_NX = 80;
const PH_NZ = 60;
let pheromoneField = new Float32Array(PH_NX * PH_NZ);
let pheromoneTemp = new Float32Array(PH_NX * PH_NZ);
const agents = [];
const obstacles = [];
let simulationSpeed = 1.4;
let placementMode = false;
let pheromoneTimer = 0;
let metricsTimer = 0;
let maximumTrailSignal = 0;
// ------------------------------------------------------------
// Renderer, scene, camera
// ------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
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;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101817);
scene.fog = new THREE.Fog(0x101817, 38, 70);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
140
);
const cameraState = {
yaw: 0.48,
pitch: 0.72,
radius: 31,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
const horizontal = Math.sin(pitch) * radius;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.cos(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
updateCamera();
// ------------------------------------------------------------
// Lighting
// ------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(
0xb9d7c5,
0x34251d,
2.05
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedc6, 3.0);
sun.position.set(-11, 21, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8fb6d6, 0.65);
fill.position.set(12, 8, -12);
scene.add(fill);
// ------------------------------------------------------------
// Materials and helpers
// ------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
flatShading: true,
...options
});
}
const dirtMaterial = standardMaterial(0x4a392d);
const borderMaterial = standardMaterial(0x5a4935);
const darkWoodMaterial = standardMaterial(0x342a21);
const leafMaterial = standardMaterial(0x668347);
const leafLightMaterial = standardMaterial(0x8a9a4e);
const fruitMaterial = standardMaterial(0xe5a13a);
const fruitLightMaterial = standardMaterial(0xf1c44f);
function addMesh(geometry, material, parent = scene) {
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Backdrop under the raised habitat.
const backdrop = addMesh(
new THREE.PlaneGeometry(180, 180),
standardMaterial(0x15231f)
);
backdrop.rotation.x = -Math.PI / 2;
backdrop.position.y = -1.03;
backdrop.castShadow = false;
// Raised arena platform.
const platform = addMesh(
new THREE.BoxGeometry(ARENA_W + 0.8, 1, ARENA_D + 0.8),
dirtMaterial
);
platform.position.y = -0.5;
// A field of subtly varied, low-poly soil tiles.
const columns = 20;
const rows = 15;
const tileGeometry = new THREE.BoxGeometry(0.94, 0.035, 0.94);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
flatShading: true
});
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
columns * rows
);
tiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let z = 0; z < rows; z++) {
for (let x = 0; x < columns; x++) {
dummy.position.set(
-11.4 + x * 1.2,
0.019,
-8.4 + z * 1.2
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const variation = Math.random() * 0.055;
tileColor.setHSL(
0.095 + Math.random() * 0.018,
0.27 + Math.random() * 0.08,
0.245 + variation
);
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
// Visible arena boundary.
const longBorderGeometry = new THREE.BoxGeometry(
ARENA_W + 1.25,
0.32,
0.26
);
const shortBorderGeometry = new THREE.BoxGeometry(
0.26,
0.32,
ARENA_D + 1.25
);
const northBorder = addMesh(longBorderGeometry, borderMaterial);
northBorder.position.set(0, 0.13, -ARENA_D / 2 - 0.35);
const southBorder = addMesh(longBorderGeometry, borderMaterial);
southBorder.position.set(0, 0.13, ARENA_D / 2 + 0.35);
const westBorder = addMesh(shortBorderGeometry, borderMaterial);
westBorder.position.set(-ARENA_W / 2 - 0.35, 0.13, 0);
const eastBorder = addMesh(shortBorderGeometry, borderMaterial);
eastBorder.position.set(ARENA_W / 2 + 0.35, 0.13, 0);
// Sparse grass along the perimeter.
const grassGeometry = new THREE.ConeGeometry(0.09, 0.38, 4);
const grassMaterial = standardMaterial(0x526c3c);
const grass = new THREE.InstancedMesh(grassGeometry, grassMaterial, 72);
for (let i = 0; i < 72; i++) {
const side = Math.floor(Math.random() * 4);
let x;
let z;
if (side < 2) {
x = -11 + Math.random() * 22;
z = side === 0 ? -8.4 : 8.4;
} else {
x = side === 2 ? -11.4 : 11.4;
z = -7.8 + Math.random() * 15.6;
}
dummy.position.set(x, 0.2, z);
dummy.rotation.set(
(Math.random() - 0.5) * 0.2,
Math.random() * Math.PI,
(Math.random() - 0.5) * 0.25
);
const scale = 0.65 + Math.random() * 0.8;
dummy.scale.set(scale, scale, scale);
dummy.updateMatrix();
grass.setMatrixAt(i, dummy.matrix);
}
grass.instanceMatrix.needsUpdate = true;
grass.castShadow = true;
scene.add(grass);
// ------------------------------------------------------------
// Nest and food patches
// ------------------------------------------------------------
const nestGroup = new THREE.Group();
nestGroup.position.set(NEST_POSITION.x, 0, NEST_POSITION.y);
scene.add(nestGroup);
const mound = addMesh(
new THREE.ConeGeometry(1.18, 0.55, 9, 1),
standardMaterial(0x6b5134),
nestGroup
);
mound.position.y = 0.27;
const nestOpening = addMesh(
new THREE.CircleGeometry(0.36, 10),
standardMaterial(0x17120f),
nestGroup
);
nestOpening.rotation.x = -Math.PI / 2;
nestOpening.position.y = 0.555;
const nestStoneGeometry = new THREE.DodecahedronGeometry(0.22, 0);
for (let i = 0; i < 10; i++) {
const angle = (i / 10) * Math.PI * 2;
const stone = addMesh(
nestStoneGeometry,
standardMaterial(i % 2 ? 0x7c765f : 0x666552),
nestGroup
);
stone.position.set(
Math.cos(angle) * 0.86,
0.16,
Math.sin(angle) * 0.86
);
stone.scale.set(
0.8 + Math.random() * 0.5,
0.65 + Math.random() * 0.35,
0.8 + Math.random() * 0.5
);
stone.rotation.set(
Math.random(),
Math.random() * Math.PI,
Math.random()
);
}
function createFoodPatch(position, variation) {
const group = new THREE.Group();
group.position.set(position.x, 0, position.y);
scene.add(group);
for (let i = 0; i < 13; i++) {
const angle = Math.random() * Math.PI * 2;
const radius = Math.sqrt(Math.random()) * 0.88;
const fruit = addMesh(
new THREE.IcosahedronGeometry(0.16 + Math.random() * 0.07, 0),
i % 3 === 0 ? fruitLightMaterial : fruitMaterial,
group
);
fruit.position.set(
Math.cos(angle) * radius,
0.17 + Math.random() * 0.08,
Math.sin(angle) * radius
);
fruit.scale.y = 0.82;
fruit.rotation.set(Math.random(), Math.random(), Math.random());
}
for (let i = 0; i < 9; i++) {
const angle = Math.random() * Math.PI * 2;
const leaf = addMesh(
new THREE.SphereGeometry(1, 5, 3),
i % 2 ? leafMaterial : leafLightMaterial,
group
);
leaf.position.set(
Math.cos(angle) * (0.55 + Math.random() * 0.6),
0.08,
Math.sin(angle) * (0.55 + Math.random() * 0.6)
);
leaf.scale.set(
0.34 + Math.random() * 0.18,
0.055,
0.13 + Math.random() * 0.07
);
leaf.rotation.set(
(Math.random() - 0.5) * 0.25,
angle + variation,
(Math.random() - 0.5) * 0.3
);
}
}
createFoodPatch(FOOD_POSITIONS[0], 0.2);
createFoodPatch(FOOD_POSITIONS[1], 1.4);
// ------------------------------------------------------------
// Pheromone texture
// ------------------------------------------------------------
const pheromonePixels = new Uint8Array(PH_NX * PH_NZ * 4);
const pheromoneTexture = new THREE.DataTexture(
pheromonePixels,
PH_NX,
PH_NZ,
THREE.RGBAFormat
);
pheromoneTexture.colorSpace = THREE.SRGBColorSpace;
pheromoneTexture.minFilter = THREE.LinearFilter;
pheromoneTexture.magFilter = THREE.LinearFilter;
pheromoneTexture.generateMipmaps = false;
const pheromoneMesh = new THREE.Mesh(
new THREE.PlaneGeometry(ARENA_W, ARENA_D),
new THREE.MeshBasicMaterial({
map: pheromoneTexture,
transparent: true,
opacity: 0.86,
depthWrite: false,
side: THREE.DoubleSide
})
);
pheromoneMesh.rotation.x = -Math.PI / 2;
pheromoneMesh.position.y = 0.067;
pheromoneMesh.renderOrder = 2;
scene.add(pheromoneMesh);
function samplePheromone(x, z) {
const u = THREE.MathUtils.clamp(
(x / ARENA_W + 0.5) * (PH_NX - 1),
0,
PH_NX - 1
);
const v = THREE.MathUtils.clamp(
(z / ARENA_D + 0.5) * (PH_NZ - 1),
0,
PH_NZ - 1
);
const x0 = Math.floor(u);
const z0 = Math.floor(v);
const x1 = Math.min(x0 + 1, PH_NX - 1);
const z1 = Math.min(z0 + 1, PH_NZ - 1);
const tx = u - x0;
const tz = v - z0;
const a = pheromoneField[z0 * PH_NX + x0];
const b = pheromoneField[z0 * PH_NX + x1];
const c = pheromoneField[z1 * PH_NX + x0];
const d = pheromoneField[z1 * PH_NX + x1];
const ab = THREE.MathUtils.lerp(a, b, tx);
const cd = THREE.MathUtils.lerp(c, d, tx);
return THREE.MathUtils.lerp(ab, cd, tz);
}
function depositPheromone(x, z, amount) {
const ix = Math.floor(
THREE.MathUtils.clamp((x / ARENA_W + 0.5) * PH_NX, 0, PH_NX - 1)
);
const iz = Math.floor(
THREE.MathUtils.clamp((z / ARENA_D + 0.5) * PH_NZ, 0, PH_NZ - 1)
);
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const nx = ix + dx;
const nz = iz + dz;
if (nx < 0 || nx >= PH_NX || nz < 0 || nz >= PH_NZ) continue;
const distanceSquared = dx * dx + dz * dz;
const weight = 1 / (1 + distanceSquared * 0.85);
const index = nz * PH_NX + nx;
pheromoneField[index] = Math.min(
5,
pheromoneField[index] + amount * weight
);
}
}
}
function erasePheromoneAround(x, z, radius) {
for (let iz = 0; iz < PH_NZ; iz++) {
const wz = ((iz + 0.5) / PH_NZ - 0.5) * ARENA_D;
for (let ix = 0; ix < PH_NX; ix++) {
const wx = ((ix + 0.5) / PH_NX - 0.5) * ARENA_W;
const distance = Math.hypot(wx - x, wz - z);
if (distance < radius) {
pheromoneField[iz * PH_NX + ix] = 0;
}
}
}
}
function diffusePheromone() {
for (let z = 1; z < PH_NZ - 1; z++) {
for (let x = 1; x < PH_NX - 1; x++) {
const i = z * PH_NX + x;
const neighbors =
pheromoneField[i - 1] +
pheromoneField[i + 1] +
pheromoneField[i - PH_NX] +
pheromoneField[i + PH_NX];
pheromoneTemp[i] =
pheromoneField[i] * 0.94 + neighbors * 0.015;
}
}
for (let x = 0; x < PH_NX; x++) {
pheromoneTemp[x] = pheromoneField[x] * 0.96;
const last = (PH_NZ - 1) * PH_NX + x;
pheromoneTemp[last] = pheromoneField[last] * 0.96;
}
for (let z = 0; z < PH_NZ; z++) {
const left = z * PH_NX;
const right = z * PH_NX + PH_NX - 1;
pheromoneTemp[left] = pheromoneField[left] * 0.96;
pheromoneTemp[right] = pheromoneField[right] * 0.96;
}
pheromoneField.set(pheromoneTemp);
for (let i = 0; i < pheromoneField.length; i++) {
pheromoneField[i] *= 0.997;
}
}
function updatePheromoneTexture() {
let maximum = 0;
for (let i = 0; i < pheromoneField.length; i++) {
const value = pheromoneField[i];
maximum = Math.max(maximum, value);
const normalized = THREE.MathUtils.clamp(value / 2.1, 0, 1);
const pixel = i * 4;
pheromonePixels[pixel] = Math.round(178 + normalized * 77);
pheromonePixels[pixel + 1] = Math.round(91 + normalized * 117);
pheromonePixels[pixel + 2] = Math.round(24 + normalized * 52);
pheromonePixels[pixel + 3] = Math.round(normalized * 190);
}
maximumTrailSignal = maximum;
pheromoneTexture.needsUpdate = true;
}
function clearPheromone() {
pheromoneField.fill(0);
pheromoneTemp.fill(0);
updatePheromoneTexture();
}
// ------------------------------------------------------------
// Instanced low-poly ants
// ------------------------------------------------------------
const antBodyGeometry = new THREE.SphereGeometry(1, 7, 5);
const antLegGeometry = new THREE.BoxGeometry(1, 1, 1);
const antFruitGeometry = new THREE.IcosahedronGeometry(0.075, 0);
const abdomen = new THREE.InstancedMesh(
antBodyGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.82,
flatShading: true
}),
ANT_COUNT
);
const thorax = new THREE.InstancedMesh(
antBodyGeometry,
standardMaterial(0x251711),
ANT_COUNT
);
const head = new THREE.InstancedMesh(
antBodyGeometry,
standardMaterial(0x1b120e),
ANT_COUNT
);
const legs = new THREE.InstancedMesh(
antLegGeometry,
standardMaterial(0x15100d),
ANT_COUNT * 6
);
const carriedFood = new THREE.InstancedMesh(
antFruitGeometry,
fruitLightMaterial,
ANT_COUNT
);
for (const mesh of [abdomen, thorax, head, legs, carriedFood]) {
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
scene.add(mesh);
}
const antDark = new THREE.Color(0x2c1b13);
const antCarried = new THREE.Color(0xb97c2b);
const yAxis = new THREE.Vector3(0, 1, 0);
const antQuaternion = new THREE.Quaternion();
const bodyDummy = new THREE.Object3D();
const legDummy = new THREE.Object3D();
const fruitDummy = new THREE.Object3D();
// ------------------------------------------------------------
// Agent model
// ------------------------------------------------------------
function randomFoodIndex() {
return Math.random() < 0.5 ? 0 : 1;
}
function pointInsideObstacle(x, z, padding = 0) {
return obstacles.some(
(obstacle) =>
Math.hypot(x - obstacle.x, z - obstacle.z) <
obstacle.radius + padding
);
}
function resetAgents() {
agents.length = 0;
for (let i = 0; i < ANT_COUNT; i++) {
const outbound = i < ANT_COUNT * 0.55;
const agent = {
id: i,
x: 0,
z: 0,
heading: 0,
state: outbound ? 0 : 1,
carrying: !outbound,
foodIndex: randomFoodIndex(),
phase: Math.random() * Math.PI * 2
};
if (outbound) {
const angle = Math.random() * Math.PI * 2;
const radius = Math.random() * 0.75;
agent.x = NEST_POSITION.x + Math.cos(angle) * radius;
agent.z = NEST_POSITION.y + Math.sin(angle) * radius;
agent.heading = Math.atan2(
FOOD_POSITIONS[agent.foodIndex].x - agent.x,
FOOD_POSITIONS[agent.foodIndex].y - agent.z
);
} else {
const source = FOOD_POSITIONS[agent.foodIndex];
const t = 0.12 + Math.random() * 0.58;
agent.x = THREE.MathUtils.lerp(source.x, NEST_POSITION.x, t);
agent.z = THREE.MathUtils.lerp(source.y, NEST_POSITION.y, t);
agent.x += (Math.random() - 0.5) * 1.0;
agent.z += (Math.random() - 0.5) * 1.0;
if (pointInsideObstacle(agent.x, agent.z, 0.25)) {
agent.state = 0;
agent.carrying = false;
agent.x = NEST_POSITION.x + (Math.random() - 0.5);
agent.z = NEST_POSITION.y + (Math.random() - 0.5);
}
agent.heading = Math.atan2(
NEST_POSITION.x - agent.x,
NEST_POSITION.y - agent.z
);
}
agents.push(agent);
}
}
function wrapAngle(angle) {
return Math.atan2(Math.sin(angle), Math.cos(angle));
}
function updateAgents(dt) {
for (const agent of agents) {
agent.phase += dt * (agent.carrying ? 15 : 18);
let targetX;
let targetZ;
if (agent.state === 0) {
const food = FOOD_POSITIONS[agent.foodIndex];
targetX = food.x;
targetZ = food.y;
if (Math.hypot(agent.x - food.x, agent.z - food.y) < 0.72) {
agent.state = 1;
agent.carrying = true;
depositPheromone(agent.x, agent.z, 1.15);
targetX = NEST_POSITION.x;
targetZ = NEST_POSITION.y;
}
} else {
targetX = NEST_POSITION.x;
targetZ = NEST_POSITION.y;
if (
Math.hypot(
agent.x - NEST_POSITION.x,
agent.z - NEST_POSITION.y
) < 0.58
) {
agent.state = 0;
agent.carrying = false;
agent.foodIndex = randomFoodIndex();
const food = FOOD_POSITIONS[agent.foodIndex];
targetX = food.x;
targetZ = food.y;
}
}
let goalX = targetX - agent.x;
let goalZ = targetZ - agent.z;
const goalLength = Math.hypot(goalX, goalZ) || 1;
goalX /= goalLength;
goalZ /= goalLength;
let steerX = goalX;
let steerZ = goalZ;
// Local gradient sensing. Returning ants follow increasing odor;
// outbound ants can follow it in reverse toward the food.
const gradientX =
samplePheromone(agent.x + 0.45, agent.z) -
samplePheromone(agent.x - 0.45, agent.z);
const gradientZ =
samplePheromone(agent.x, agent.z + 0.45) -
samplePheromone(agent.x, agent.z - 0.45);
const direction = agent.state === 0 ? -1 : 1;
steerX += gradientX * 5.4 * direction;
steerZ += gradientZ * 5.4 * direction;
// Local obstacle avoidance with a tangent slide around surfaces.
for (const obstacle of obstacles) {
const dx = obstacle.x - agent.x;
const dz = obstacle.z - agent.z;
const distance = Math.hypot(dx, dz);
const influence = obstacle.radius + 1.65;
if (distance > 0.0001 && distance < influence) {
const amount = (influence - distance) / influence;
const nx = dx / distance;
const nz = dz / distance;
steerX -= nx * amount * 3.2;
steerZ -= nz * amount * 3.2;
const tangentX = -nz;
const tangentZ = nx;
const currentDirectionX = Math.sin(agent.heading);
const currentDirectionZ = Math.cos(agent.heading);
const currentTangentDot =
tangentX * currentDirectionX + tangentZ * currentDirectionZ;
let sign =
Math.abs(currentTangentDot) > 0.22
? Math.sign(currentTangentDot)
: agent.id % 2 === 0
? 1
: -1;
steerX += tangentX * sign * amount * 2.15;
steerZ += tangentZ * sign * amount * 2.15;
}
}
// Soft boundary steering keeps the colony inside the arena.
const marginX = ARENA_W / 2 - 1.0;
const marginZ = ARENA_D / 2 - 1.0;
if (agent.x > marginX) steerX -= (agent.x - marginX) * 4;
if (agent.x < -marginX) steerX += (-marginX - agent.x) * 4;
if (agent.z > marginZ) steerZ -= (agent.z - marginZ) * 4;
if (agent.z < -marginZ) steerZ += (-marginZ - agent.z) * 4;
// Small stochastic component prevents perfectly synchronized paths.
steerX += (Math.random() - 0.5) * 0.18;
steerZ += (Math.random() - 0.5) * 0.18;
const desiredHeading = Math.atan2(steerX, steerZ);
const headingDifference = wrapAngle(
desiredHeading - agent.heading
);
const turnLimit = (agent.carrying ? 2.55 : 3.15) * dt;
agent.heading += THREE.MathUtils.clamp(
headingDifference,
-turnLimit,
turnLimit
);
const movementSpeed = 1.48;
agent.x += Math.sin(agent.heading) * movementSpeed * dt;
agent.z += Math.cos(agent.heading) * movementSpeed * dt;
// Hard collision correction after integration.
for (const obstacle of obstacles) {
const dx = agent.x - obstacle.x;
const dz = agent.z - obstacle.z;
const distance = Math.hypot(dx, dz);
const minimumDistance = obstacle.radius + 0.08;
if (distance < minimumDistance && distance > 0.0001) {
agent.x = obstacle.x + (dx / distance) * minimumDistance;
agent.z = obstacle.z + (dz / distance) * minimumDistance;
}
}
agent.x = THREE.MathUtils.clamp(
agent.x,
-ARENA_W / 2 + 0.35,
ARENA_W / 2 - 0.35
);
agent.z = THREE.MathUtils.clamp(
agent.z,
-ARENA_D / 2 + 0.35,
ARENA_D / 2 - 0.35
);
if (agent.carrying) {
depositPheromone(agent.x, agent.z, 0.2 * dt);
} else {
depositPheromone(agent.x, agent.z, 0.025 * dt);
}
}
pheromoneTimer += dt;
if (pheromoneTimer >= 0.085) {
diffusePheromone();
updatePheromoneTexture();
pheromoneTimer = 0;
}
}
function updateAgentInstances() {
const legOffsets = [-0.15, 0.035, 0.19];
for (let i = 0; i < agents.length; i++) {
const agent = agents[i];
const forwardX = Math.sin(agent.heading);
const forwardZ = Math.cos(agent.heading);
const rightX = Math.cos(agent.heading);
const rightZ = -Math.sin(agent.heading);
antQuaternion.setFromAxisAngle(yAxis, agent.heading);
function setBodyPart(mesh, index, forwardOffset, scale) {
bodyDummy.position.set(
agent.x + forwardX * forwardOffset,
0.205,
agent.z + forwardZ * forwardOffset
);
bodyDummy.quaternion.copy(antQuaternion);
bodyDummy.scale.set(scale[0], scale[1], scale[2]);
bodyDummy.updateMatrix();
mesh.setMatrixAt(index, bodyDummy.matrix);
}
setBodyPart(abdomen, i, -0.18, [0.15, 0.12, 0.24]);
setBodyPart(thorax, i, 0.0, [0.105, 0.1, 0.135]);
setBodyPart(head, i, 0.18, [0.13, 0.115, 0.14]);
abdomen.setColorAt(
i,
agent.carrying ? antCarried : antDark
);
for (let leg = 0; leg < 6; leg++) {
const pair = Math.floor(leg / 2);
const side = leg % 2 === 0 ? -1 : 1;
const forwardOffset = legOffsets[pair];
const swing =
Math.sin(
agent.phase +
pair * 2.15 +
(side > 0 ? Math.PI : 0)
) * 0.055;
legDummy.position.set(
agent.x +
forwardX * (forwardOffset + swing) +
rightX * side * 0.16,
0.135,
agent.z +
forwardZ * (forwardOffset + swing) +
rightZ * side * 0.16
);
legDummy.quaternion.copy(antQuaternion);
legDummy.scale.set(0.34, 0.035, 0.035);
legDummy.updateMatrix();
legs.setMatrixAt(i * 6 + leg, legDummy.matrix);
}
if (agent.carrying) {
fruitDummy.position.set(
agent.x - forwardX * 0.13,
0.39,
agent.z - forwardZ * 0.13
);
fruitDummy.quaternion.copy(antQuaternion);
fruitDummy.scale.set(1, 0.85, 1);
} else {
fruitDummy.position.set(agent.x, -2, agent.z);
fruitDummy.scale.set(0.001, 0.001, 0.001);
}
fruitDummy.updateMatrix();
carriedFood.setMatrixAt(i, fruitDummy.matrix);
}
abdomen.instanceMatrix.needsUpdate = true;
thorax.instanceMatrix.needsUpdate = true;
head.instanceMatrix.needsUpdate = true;
legs.instanceMatrix.needsUpdate = true;
carriedFood.instanceMatrix.needsUpdate = true;
if (abdomen.instanceColor) {
abdomen.instanceColor.needsUpdate = true;
}
}
// ------------------------------------------------------------
// Obstacles
// ------------------------------------------------------------
function createObstacle(x, z) {
if (Math.hypot(x - NEST_POSITION.x, z - NEST_POSITION.y) < 2.5) {
showToast("Place the obstacle farther from the nest.");
return;
}
for (const food of FOOD_POSITIONS) {
if (Math.hypot(x - food.x, z - food.y) < 2.0) {
showToast("Keep the food patches clear so ants can reach them.");
return;
}
}
for (const obstacle of obstacles) {
if (Math.hypot(x - obstacle.x, z - obstacle.z) < 3.0) {
showToast("That obstacle overlaps another. Try a nearby empty patch.");
return;
}
}
const radius = 1.35 + Math.random() * 0.3;
const rock = addMesh(
new THREE.DodecahedronGeometry(radius, 0),
standardMaterial(Math.random() > 0.5 ? 0x747f78 : 0x66716d)
);
rock.position.set(x, radius * 0.69, z);
rock.rotation.set(
(Math.random() - 0.5) * 0.22,
Math.random() * Math.PI,
(Math.random() - 0.5) * 0.18
);
rock.scale.y = 0.78;
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius * 0.92, radius * 0.98, 40),
new THREE.MeshBasicMaterial({
color: 0xf0c979,
transparent: true,
opacity: 0.58,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(x, 0.078, z);
scene.add(ring);
obstacles.push({
x,
z,
radius: radius * 0.9,
rock,
ring
});
// A physical barrier removes stale chemical memory directly beneath it.
erasePheromoneAround(x, z, radius + 0.65);
updatePheromoneTexture();
updateMetrics();
showToast(
"Obstacle added. Watch nearby ants choose a side and reinforce a new route."
);
}
function clearObstacles() {
for (const obstacle of obstacles) {
scene.remove(obstacle.rock);
scene.remove(obstacle.ring);
obstacle.rock.geometry.dispose();
obstacle.rock.material.dispose();
obstacle.ring.geometry.dispose();
obstacle.ring.material.dispose();
}
obstacles.length = 0;
updateMetrics();
showToast("Obstacles cleared. Existing chemical trails remain as memory.");
}
// ------------------------------------------------------------
// UI and placement mode
// ------------------------------------------------------------
let toastTimeout;
function showToast(message) {
const toast = $("toast");
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => {
toast.classList.remove("visible");
}, 3400);
}
function setPlacementMode(enabled) {
placementMode = enabled;
const button = $("place-obstacle");
button.classList.toggle("active", enabled);
button.setAttribute("aria-pressed", String(enabled));
button.textContent = enabled ? "Click arena…" : "+ Place obstacle";
canvas.classList.toggle("placing", enabled);
$("placement-hint").classList.toggle("visible", enabled);
}
$("place-obstacle").addEventListener("click", () => {
setPlacementMode(!placementMode);
});
$("clear-obstacles").addEventListener("click", clearObstacles);
$("restart").addEventListener("click", () => {
clearPheromone();
resetAgents();
showToast("Colony restarted. Obstacles remain in place.");
});
$("show-pheromone").addEventListener("change", (event) => {
pheromoneMesh.visible = event.target.checked;
});
$("speed").addEventListener("input", (event) => {
simulationSpeed = Number(event.target.value);
$("speed-value").textContent = `${simulationSpeed.toFixed(1)}×`;
});
window.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
setPlacementMode(false);
}
});
function updateMetrics() {
$("metric-agents").textContent = ANT_COUNT;
$("metric-obstacles").textContent = obstacles.length;
const signal = Math.min(
100,
Math.round((maximumTrailSignal / 2.5) * 100)
);
$("metric-signal").textContent = `${signal}%`;
$("signal-fill").style.width = `${signal}%`;
}
// ------------------------------------------------------------
// Custom pointer camera controls and obstacle placement
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-0.07
);
const intersection = new THREE.Vector3();
let interaction = null;
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function placeObstacleFromPointer(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(groundPlane, intersection)) {
const x = THREE.MathUtils.clamp(
intersection.x,
-ARENA_W / 2 + 1.5,
ARENA_W / 2 - 1.5
);
const z = THREE.MathUtils.clamp(
intersection.z,
-ARENA_D / 2 + 1.5,
ARENA_D / 2 - 1.5
);
createObstacle(x, z);
}
}
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
event.preventDefault();
canvas.setPointerCapture(event.pointerId);
if (placementMode && event.button === 0) {
placeObstacleFromPointer(event);
return;
}
interaction = {
mode:
event.button === 2 || event.shiftKey ? "pan" : "orbit",
x: event.clientX,
y: event.clientY
};
});
canvas.addEventListener("pointermove", (event) => {
if (!interaction) return;
const dx = event.clientX - interaction.x;
const dy = event.clientY - interaction.y;
interaction.x = event.clientX;
interaction.y = event.clientY;
if (interaction.mode === "orbit") {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
0.38,
1.25
);
} else {
const scale = cameraState.radius * 0.0016;
const rightX = Math.cos(cameraState.yaw);
const rightZ = -Math.sin(cameraState.yaw);
const forwardX = -Math.sin(cameraState.yaw);
const forwardZ = -Math.cos(cameraState.yaw);
cameraState.target.x +=
rightX * -dx * scale + forwardX * dy * scale;
cameraState.target.z +=
rightZ * -dx * scale + forwardZ * dy * scale;
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-4,
4
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-4,
4
);
}
updateCamera();
});
function endPointerInteraction(event) {
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
interaction = null;
}
canvas.addEventListener("pointerup", endPointerInteraction);
canvas.addEventListener("pointercancel", endPointerInteraction);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.018,
18,
48
);
updateCamera();
},
{ passive: false }
);
// ------------------------------------------------------------
// World-space labels
// ------------------------------------------------------------
const labelDefinitions = [
{
element: $("label-nest"),
position: new THREE.Vector3(NEST_POSITION.x, 1.15, NEST_POSITION.y)
},
{
element: $("label-food-a"),
position: new THREE.Vector3(
FOOD_POSITIONS[0].x,
0.85,
FOOD_POSITIONS[0].y
)
},
{
element: $("label-food-b"),
position: new THREE.Vector3(
FOOD_POSITIONS[1].x,
0.85,
FOOD_POSITIONS[1].y
)
}
];
const projected = new THREE.Vector3();
function updateWorldLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const label of labelDefinitions) {
projected.copy(label.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.12 &&
projected.x < 1.12 &&
projected.y > -1.12 &&
projected.y < 1.12;
label.element.style.display = visible ? "block" : "none";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
}
// ------------------------------------------------------------
// Resize and animation loop
// ------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetAgents();
clearPheromone();
updateAgentInstances();
updateMetrics();
const clock = new THREE.Clock();
const FIXED_STEP = 1 / 60;
let accumulator = 0;
function animate() {
requestAnimationFrame(animate);
const frameDelta = Math.min(clock.getDelta(), 0.05);
accumulator += frameDelta * simulationSpeed;
let steps = 0;
while (accumulator >= FIXED_STEP && steps < 8) {
updateAgents(FIXED_STEP);
accumulator -= FIXED_STEP;
steps++;
}
if (steps === 8) accumulator = 0;
updateAgentInstances();
metricsTimer += frameDelta;
if (metricsTimer > 0.25) {
updateMetrics();
metricsTimer = 0;
}
renderer.render(scene, camera);
updateWorldLabels();
}
animate();
setTimeout(() => {
showToast(
"Place a rock between the nest and a food patch to test collective rerouting."
);
}, 900);
</script>
</body>
</html>
```