Prompt specification
Build or customize the Three.js 3D scene "Dry-season watering-place approach" 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: Dry-season watering-place approach
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/dry-season-watering-place-approach-x0679
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring elephant herd movement. Compose a savanna waterhole with shade, paths, and several elephants; individuals drink, wait, and move away through coherent routes rather than overlapping at one point. Voxel style.
Working Three.js Starter (dry-season-watering-place-approach-x0679):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Waterhole — Elephant Herd</title>
<style>
:root {
--ink: #352f28;
--paper: rgba(255, 248, 222, 0.88);
--line: rgba(79, 65, 43, 0.18);
--gold: #d39a3b;
--blue: #4d91a6;
--brown: #9a6547;
--violet: #88759c;
--green: #6d8050;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #ddc18a;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app, canvas {
width: 100%;
height: 100%;
display: block;
}
canvas {
cursor: grab;
touch-action: none;
}
canvas.dragging { cursor: grabbing; }
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--line);
background: var(--paper);
box-shadow: 0 10px 35px rgba(66, 48, 28, 0.13);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
#title {
top: 18px;
left: 18px;
width: 286px;
padding: 17px 18px 15px;
border-radius: 4px 18px 18px 18px;
pointer-events: none;
}
.eyebrow {
margin: 0 0 5px;
color: #9b6d37;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 27px;
font-weight: 600;
line-height: 1.04;
letter-spacing: -0.025em;
}
.subtitle {
margin: 8px 0 0;
color: #746753;
font-size: 12px;
line-height: 1.45;
}
#herd {
top: 18px;
right: 18px;
width: 244px;
padding: 13px 14px 12px;
border-radius: 16px 4px 16px 16px;
pointer-events: none;
}
#herd h2 {
margin: 0 0 9px;
font-size: 10px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.status-row {
display: grid;
grid-template-columns: 8px 1fr auto;
gap: 8px;
align-items: center;
min-height: 27px;
border-top: 1px solid rgba(79, 65, 43, 0.08);
font-size: 12px;
}
.status-row:first-of-type { border-top: 0; }
.status-dot {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--gold);
box-shadow: 0 0 0 2px rgba(255,255,255,0.45);
}
.status-name { font-weight: 750; }
.status-action {
color: #766b57;
font-size: 10px;
white-space: nowrap;
}
#controls {
left: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 7px;
padding: 8px;
border-radius: 14px;
}
button {
appearance: none;
border: 1px solid rgba(79, 65, 43, 0.14);
border-radius: 9px;
padding: 9px 12px;
background: rgba(255,255,255,0.62);
color: var(--ink);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: transform 0.15s, background 0.15s;
}
button:hover {
transform: translateY(-1px);
background: rgba(255,255,255,0.94);
}
button:active { transform: translateY(0); }
#hint {
position: fixed;
z-index: 8;
right: 18px;
bottom: 20px;
padding: 9px 12px;
border-radius: 12px;
background: rgba(69, 55, 37, 0.62);
color: rgba(255, 249, 229, 0.9);
font-size: 10px;
letter-spacing: 0.04em;
pointer-events: none;
}
#labels {
position: fixed;
inset: 0;
z-index: 5;
overflow: hidden;
pointer-events: none;
}
.animal-label {
position: absolute;
left: 0;
top: 0;
padding: 4px 7px;
border: 1px solid rgba(255,255,255,0.5);
border-radius: 7px;
background: rgba(51, 43, 32, 0.72);
color: #fff7dc;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.02em;
white-space: nowrap;
transform: translate(-50%, -100%);
box-shadow: 0 4px 12px rgba(43,34,24,0.15);
}
#loading {
position: fixed;
inset: 0;
z-index: 30;
display: grid;
place-items: center;
background: #ddc18a;
color: #69553d;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
transition: opacity 0.4s;
}
#loading.hidden { opacity: 0; pointer-events: none; }
@media (max-width: 720px) {
#title {
top: 10px;
left: 10px;
width: 220px;
padding: 13px 14px;
}
h1 { font-size: 22px; }
.subtitle { display: none; }
#herd {
top: 10px;
right: 10px;
width: 178px;
padding: 10px;
}
.status-row {
grid-template-columns: 7px 1fr;
min-height: 24px;
}
.status-action { display: none; }
#controls { left: 10px; bottom: 10px; }
#hint { display: none; }
}
</style>
</head>
<body>
<div id="app"></div>
<div id="labels"></div>
<section id="title" class="panel">
<p class="eyebrow">Savanna observation · 07</p>
<h1>Waterhole Watch</h1>
<p class="subtitle">
Six elephants follow separate paths to individual drinking places,
pause, and return to the herd without crowding the shoreline.
</p>
</section>
<section id="herd" class="panel">
<h2>Herd activity</h2>
<div id="status-list"></div>
</section>
<div id="controls" class="panel">
<button id="pause" type="button">Pause herd</button>
<button id="restart" type="button">Restart</button>
<button id="camera-reset" type="button">Reset view</button>
</div>
<div id="hint">Drag to orbit · Scroll to zoom · Space to pause</div>
<div id="loading">Preparing the waterhole…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, lighting
// -------------------------------------------------------------------------
const app = document.querySelector("#app");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe4c58d);
scene.fog = new THREE.Fog(0xe4c58d, 43, 88);
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;
renderer.domElement.setAttribute(
"aria-label",
"Voxel savanna scene with an elephant herd around a waterhole"
);
app.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
39,
window.innerWidth / window.innerHeight,
0.1,
150
);
const hemisphere = new THREE.HemisphereLight(0xffefc5, 0x78613e, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffdf9d, 3.25);
sun.position.set(-18, 30, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -31;
sun.shadow.camera.right = 31;
sun.shadow.camera.top = 27;
sun.shadow.camera.bottom = -27;
sun.shadow.camera.near = 2;
sun.shadow.camera.far = 75;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const coolFill = new THREE.DirectionalLight(0xb9d3db, 0.65);
coolFill.position.set(18, 10, -20);
scene.add(coolFill);
// -------------------------------------------------------------------------
// Deterministic randomness and shared voxel geometry
// -------------------------------------------------------------------------
let seed = 14731;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
const range = (a, b) => a + random() * (b - a);
const clamp = THREE.MathUtils.clamp;
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function standard(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.92,
...extra
});
}
function addBox(
parent, sx, sy, sz, x, y, z, material,
castShadow = true, receiveShadow = false
) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(sx, sy, sz);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Six non-intersecting approach corridors, each ending at its own slot
// -------------------------------------------------------------------------
const routeDefinitions = [
{
name: "Amani",
points: [
[-12, -13.5], [-8, -11], [-5, -8.2], [-1.3, -5.5]
]
},
{
name: "Juma",
points: [
[13, -12], [10, -9], [7.4, -6.3], [4.8, -4]
]
},
{
name: "Kito",
points: [
[16.5, -0.8], [12, -0.5], [9.2, -0.2], [7.1, -0.3]
]
},
{
name: "Nala",
points: [
[14, 12], [11, 9.5], [8, 6.5], [5.2, 4.1]
]
},
{
name: "Zuri",
points: [
[-14, 12], [-10, 9.5], [-7, 7], [-4.7, 4.4]
]
},
{
name: "Tamu",
points: [
[-16.5, 2], [-12, 1.8], [-9, 1.4], [-7, 1.2]
]
}
];
function prepareRoute(points) {
const segments = [];
let total = 0;
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz);
segments.push({
a, b, dx, dz, length,
start: total,
tx: dx / length,
tz: dz / length
});
total += length;
}
return { points, segments, total };
}
const routes = routeDefinitions.map(r => prepareRoute(r.points));
function sampleRoute(route, progress) {
const distance = clamp(progress, 0, 1) * route.total;
for (let i = 0; i < route.segments.length; i++) {
const segment = route.segments[i];
if (
distance <= segment.start + segment.length ||
i === route.segments.length - 1
) {
const local = clamp(
(distance - segment.start) / segment.length,
0,
1
);
return {
x: segment.a[0] + segment.dx * local,
z: segment.a[1] + segment.dz * local,
tx: segment.tx,
tz: segment.tz
};
}
}
}
function distanceToSegment(px, pz, a, b) {
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const lengthSq = dx * dx + dz * dz;
const t = lengthSq === 0
? 0
: clamp(((px - a[0]) * dx + (pz - a[1]) * dz) / lengthSq, 0, 1);
const x = a[0] + dx * t;
const z = a[1] + dz * t;
return Math.hypot(px - x, pz - z);
}
function nearAnyPath(x, z, margin = 0.8) {
return routes.some(route =>
route.segments.some(segment =>
distanceToSegment(x, z, segment.a, segment.b) < margin
)
);
}
// -------------------------------------------------------------------------
// Blocky terrain and water
// -------------------------------------------------------------------------
const soilMaterial = standard(0x8a633e);
const outsideMaterial = standard(0xb4945d);
addBox(
scene, 180, 0.5, 180, 0, -0.68, 0,
outsideMaterial, false, true
);
addBox(
scene, 44, 0.45, 34, 0, -0.55, 0,
soilMaterial, false, true
);
const landCells = [];
const waterCells = [];
for (let ix = 0; ix < 44; ix++) {
for (let iz = 0; iz < 34; iz++) {
const x = ix - 21.5;
const z = iz - 16.5;
const radius = Math.hypot(x / 7.4, z / 5.3);
if (radius < 0.82) {
waterCells.push({ x, z, radius });
} else {
landCells.push({ x, z, radius });
}
}
}
const landMaterial = standard(0xffffff);
const landMesh = new THREE.InstancedMesh(
unitBox, landMaterial, landCells.length
);
landMesh.receiveShadow = true;
landMesh.castShadow = false;
scene.add(landMesh);
const matrix = new THREE.Matrix4();
const quaternion = new THREE.Quaternion();
const scaleVector = new THREE.Vector3();
const positionVector = new THREE.Vector3();
const color = new THREE.Color();
const grassPalette = [0x99964f, 0xa5a058, 0x909149, 0xaea65c, 0x969a51];
const shorePalette = [0xc7a76a, 0xd0b174, 0xba985d, 0xc9aa70];
landCells.forEach((cell, index) => {
const shore = cell.radius < 1.08;
const top = shore ? 0.15 : range(0.025, 0.095);
const height = 0.52;
positionVector.set(cell.x, top - height / 2, cell.z);
scaleVector.set(0.985, height, 0.985);
matrix.compose(positionVector, quaternion, scaleVector);
landMesh.setMatrixAt(index, matrix);
const palette = shore ? shorePalette : grassPalette;
color.setHex(palette[Math.floor(random() * palette.length)]);
color.offsetHSL(range(-0.015, 0.015), range(-0.03, 0.03), range(-0.035, 0.035));
landMesh.setColorAt(index, color);
});
landMesh.instanceMatrix.needsUpdate = true;
landMesh.instanceColor.needsUpdate = true;
const waterMaterial = standard(0xffffff, {
roughness: 0.26,
metalness: 0.08,
emissive: 0x10313b,
emissiveIntensity: 0.15
});
const waterMesh = new THREE.InstancedMesh(
unitBox, waterMaterial, waterCells.length
);
waterMesh.receiveShadow = true;
scene.add(waterMesh);
const waterPalette = [0x4f96a7, 0x5b9eac, 0x478a9d, 0x629eaa];
waterCells.forEach((cell, index) => {
positionVector.set(cell.x, -0.08, cell.z);
scaleVector.set(0.985, 0.1, 0.985);
matrix.compose(positionVector, quaternion, scaleVector);
waterMesh.setMatrixAt(index, matrix);
color.setHex(waterPalette[Math.floor(random() * waterPalette.length)]);
color.offsetHSL(0, range(-0.03, 0.03), range(-0.025, 0.025));
waterMesh.setColorAt(index, color);
});
waterMesh.instanceMatrix.needsUpdate = true;
waterMesh.instanceColor.needsUpdate = true;
// Dust paths follow the same lanes as the elephants.
const pathTransforms = [];
for (const route of routes) {
for (const segment of route.segments) {
const count = Math.max(1, Math.ceil(segment.length / 0.58));
for (let i = 0; i < count; i++) {
const t = (i + 0.5) / count;
pathTransforms.push({
x: segment.a[0] + segment.dx * t,
z: segment.a[1] + segment.dz * t,
length: segment.length / count + 0.1,
yaw: Math.atan2(segment.dx, segment.dz)
});
}
}
}
const pathMaterial = standard(0xffffff);
const pathMesh = new THREE.InstancedMesh(
unitBox, pathMaterial, pathTransforms.length
);
pathMesh.receiveShadow = true;
scene.add(pathMesh);
pathTransforms.forEach((path, index) => {
positionVector.set(path.x, 0.185, path.z);
scaleVector.set(0.57, 0.055, path.length);
quaternion.setFromEuler(new THREE.Euler(0, path.yaw, 0));
matrix.compose(positionVector, quaternion, scaleVector);
pathMesh.setMatrixAt(index, matrix);
color.setHex(0xc4a16a);
color.offsetHSL(0, range(-0.04, 0.03), range(-0.05, 0.045));
pathMesh.setColorAt(index, color);
});
pathMesh.instanceMatrix.needsUpdate = true;
pathMesh.instanceColor.needsUpdate = true;
// -------------------------------------------------------------------------
// Acacia shade trees, shrubs, grass, reeds, rocks, and termite mounds
// -------------------------------------------------------------------------
const trunkMaterial = standard(0x705034);
const branchMaterial = standard(0x65472e);
const canopyMaterials = [
standard(0x64713c),
standard(0x738044),
standard(0x596735)
];
const shadeMaterial = new THREE.MeshBasicMaterial({
color: 0x4d5934,
transparent: true,
opacity: 0.22,
depthWrite: false
});
function createTree(x, z, size = 1, makeShade = true) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(size);
scene.add(tree);
if (makeShade) {
addBox(
tree, 5.4, 0.025, 4.2, 0, 0.145, 0,
shadeMaterial, false, false
);
}
addBox(tree, 0.52, 3.4, 0.52, 0, 1.7, 0, trunkMaterial);
addBox(tree, 0.42, 2.3, 0.42, 0, 3.35, 0, trunkMaterial);
const leftBranch = addBox(
tree, 2.2, 0.32, 0.34, -0.9, 3.65, 0,
branchMaterial
);
leftBranch.rotation.z = -0.28;
const rightBranch = addBox(
tree, 2.1, 0.32, 0.34, 0.9, 3.9, 0.1,
branchMaterial
);
rightBranch.rotation.z = 0.25;
addBox(tree, 4.7, 0.62, 3.1, 0, 4.35, 0, canopyMaterials[0]);
addBox(tree, 3.5, 0.72, 2.45, -0.15, 4.92, 0.05, canopyMaterials[1]);
addBox(tree, 3.8, 0.58, 2.35, 0.4, 4.72, -0.25, canopyMaterials[2]);
addBox(tree, 2.15, 0.56, 2.25, -1.7, 4.35, 0.1, canopyMaterials[2]);
addBox(tree, 2.0, 0.5, 2.0, 1.75, 4.5, -0.1, canopyMaterials[1]);
addBox(tree, 1.4, 0.46, 1.45, -0.6, 5.4, 0.1, canopyMaterials[2]);
addBox(tree, 1.15, 0.4, 1.2, 0.8, 5.3, -0.15, canopyMaterials[1]);
return tree;
}
createTree(-15, -6.2, 1.05);
createTree(-13.5, 9, 0.9);
createTree(11.5, -13.4, 0.78);
createTree(-3.5, 14, 0.84);
// Distant edge trees give the tile field a broader savanna silhouette.
createTree(-20, -13, 0.62, false);
createTree(19, 12.5, 0.68, false);
createTree(-19, 13.5, 0.55, false);
createTree(20, -9, 0.55, false);
const grassMaterial = standard(0xffffff);
const grassCount = 680;
const grassMesh = new THREE.InstancedMesh(
unitBox, grassMaterial, grassCount
);
grassMesh.receiveShadow = true;
scene.add(grassMesh);
let grassIndex = 0;
let attempts = 0;
while (grassIndex < grassCount && attempts < 12000) {
attempts++;
const x = range(-21.5, 21.5);
const z = range(-16.5, 16.5);
const radius = Math.hypot(x / 7.4, z / 5.3);
if (radius < 1.13 || nearAnyPath(x, z, 0.5)) continue;
const h = range(0.25, 0.65);
positionVector.set(x, 0.04 + h / 2, z);
scaleVector.set(range(0.055, 0.1), h, range(0.055, 0.1));
quaternion.setFromEuler(new THREE.Euler(0, random() * Math.PI, 0));
matrix.compose(positionVector, quaternion, scaleVector);
grassMesh.setMatrixAt(grassIndex, matrix);
color.setHex([0x788044, 0x899149, 0x69743d][Math.floor(random() * 3)]);
grassMesh.setColorAt(grassIndex, color);
grassIndex++;
}
grassMesh.count = grassIndex;
grassMesh.instanceMatrix.needsUpdate = true;
grassMesh.instanceColor.needsUpdate = true;
// Reeds form a broken green fringe around the water.
const reedMaterial = standard(0x6e8148);
const reedCount = 58;
const reedMesh = new THREE.InstancedMesh(
unitBox, reedMaterial, reedCount
);
scene.add(reedMesh);
for (let i = 0; i < reedCount; i++) {
const angle = random() * Math.PI * 2;
const x = Math.cos(angle) * range(6.9, 7.9);
const z = Math.sin(angle) * range(4.8, 5.8);
const h = range(0.45, 0.95);
positionVector.set(x, 0.12 + h / 2, z);
scaleVector.set(0.07, h, 0.07);
quaternion.setFromEuler(new THREE.Euler(0, 0, range(-0.12, 0.12)));
matrix.compose(positionVector, quaternion, scaleVector);
reedMesh.setMatrixAt(i, matrix);
}
reedMesh.instanceMatrix.needsUpdate = true;
const rockMaterials = [
standard(0x8c806a),
standard(0x9d8d73),
standard(0x756b5d)
];
function createRock(x, z, size) {
const rock = new THREE.Group();
rock.position.set(x, 0, z);
scene.add(rock);
const material = rockMaterials[Math.floor(random() * rockMaterials.length)];
const base = addBox(
rock, size, size * 0.6, size * 0.85,
0, size * 0.25, 0, material
);
base.rotation.y = range(-0.3, 0.3);
const top = addBox(
rock, size * 0.62, size * 0.45, size * 0.55,
size * 0.16, size * 0.62, -size * 0.08, material
);
top.rotation.y = range(-0.4, 0.4);
}
for (let i = 0; i < 25; i++) {
const x = range(-20, 20);
const z = range(-15.5, 15.5);
const radius = Math.hypot(x / 7.4, z / 5.3);
if (radius < 1.25 || nearAnyPath(x, z, 0.8)) continue;
createRock(x, z, range(0.35, 0.95));
}
const bushMaterials = [
standard(0x65713b),
standard(0x788044),
standard(0x596633)
];
for (let i = 0; i < 22; i++) {
const x = range(-20, 20);
const z = range(-15.5, 15.5);
const radius = Math.hypot(x / 7.4, z / 5.3);
if (radius < 1.18 || nearAnyPath(x, z, 0.7)) continue;
const bush = new THREE.Group();
bush.position.set(x, 0, z);
scene.add(bush);
const material = bushMaterials[Math.floor(random() * bushMaterials.length)];
const width = range(0.55, 1.05);
addBox(bush, width, 0.52, width * 0.75, 0, 0.27, 0, material);
addBox(
bush, width * 0.7, 0.42, width * 0.65,
width * 0.24, 0.58, 0.05, material
);
addBox(
bush, width * 0.55, 0.38, width * 0.55,
-width * 0.28, 0.51, -0.08, material
);
}
const moundMaterial = standard(0xa8663f);
[
[-10, -2.2, 1],
[9.6, 8.8, 0.85],
[-6.8, 12.7, 0.72]
].forEach(([x, z, size]) => {
const mound = new THREE.Group();
mound.position.set(x, 0, z);
mound.scale.setScalar(size);
scene.add(mound);
addBox(mound, 1.25, 0.55, 1.05, 0, 0.28, 0, moundMaterial);
addBox(mound, 0.9, 0.55, 0.75, 0.08, 0.72, 0, moundMaterial);
addBox(mound, 0.52, 0.55, 0.46, 0.12, 1.17, 0, moundMaterial);
addBox(mound, 0.23, 0.35, 0.22, 0.15, 1.58, 0, moundMaterial);
});
// -------------------------------------------------------------------------
// Water glints and drinking ripples
// -------------------------------------------------------------------------
const glintMaterial = new THREE.MeshBasicMaterial({
color: 0xc5eef0,
transparent: true,
opacity: 0.48,
depthWrite: false
});
const glints = [];
for (let i = 0; i < 24; i++) {
const x = range(-5.5, 5.5);
const z = range(-3.8, 3.8);
if (Math.hypot(x / 6.1, z / 4.35) > 0.82) continue;
const mesh = addBox(
scene, range(0.18, 0.48), 0.025, range(0.06, 0.12),
x, -0.008, z, glintMaterial, false, false
);
glints.push({
mesh,
phase: random() * Math.PI * 2,
baseX: x,
baseZ: z
});
}
function createRipple(x, z) {
const group = new THREE.Group();
group.position.set(x, -0.005, z);
scene.add(group);
const material = new THREE.MeshBasicMaterial({
color: 0xc3e9e8,
transparent: true,
opacity: 0,
depthWrite: false
});
addBox(group, 1, 0.022, 0.04, 0, 0, 0.5, material, false, false);
addBox(group, 1, 0.022, 0.04, 0, 0, -0.5, material, false, false);
addBox(group, 0.04, 0.022, 1, 0.5, 0, 0, material, false, false);
addBox(group, 0.04, 0.022, 1, -0.5, 0, 0, material, false, false);
return { group, material };
}
const drinkingRipples = routes.map(route => {
const slot = route.points[route.points.length - 1];
const length = Math.hypot(slot[0], slot[1]);
const x = slot[0] / length * 3.9;
const z = slot[1] / length * 3.9;
return createRipple(x, z);
});
// -------------------------------------------------------------------------
// Voxel elephants
// -------------------------------------------------------------------------
function createElephant(bodyColor) {
const root = new THREE.Group();
const visual = new THREE.Group();
root.add(visual);
const bodyMaterial = standard(bodyColor);
const darkMaterial = standard(0x454741);
const footMaterial = standard(0x64645c);
const ivoryMaterial = standard(0xe9dfbc);
const eyeMaterial = standard(0x171916);
const innerEarMaterial = standard(0x8d7764);
addBox(visual, 1.58, 1.25, 2.35, 0, 1.72, 0, bodyMaterial);
addBox(visual, 1.35, 0.38, 1.38, 0, 2.39, -0.08, bodyMaterial);
addBox(visual, 1.18, 0.82, 0.65, 0, 1.73, -1.32, bodyMaterial);
const headGroup = new THREE.Group();
headGroup.position.set(0, 2.03, 1.28);
visual.add(headGroup);
addBox(headGroup, 0.94, 1.03, 0.86, 0, 0, 0, bodyMaterial);
addBox(headGroup, 0.88, 0.4, 0.72, 0, 0.46, -0.02, bodyMaterial);
const ears = [];
for (const side of [-1, 1]) {
const ear = addBox(
headGroup, 0.2, 0.86, 0.78,
side * 0.53, 0.12, -0.13, bodyMaterial
);
ear.rotation.z = side * -0.1;
ear.rotation.y = side * 0.12;
ears.push(ear);
addBox(
headGroup, 0.035, 0.62, 0.53,
side * 0.64, 0.1, -0.13, innerEarMaterial
);
addBox(
headGroup, 0.085, 0.085, 0.065,
side * 0.475, 0.2, 0.445, eyeMaterial, false
);
const tusk = addBox(
headGroup, 0.13, 0.14, 0.66,
side * 0.29, -0.28, 0.46, ivoryMaterial
);
tusk.rotation.x = 0.12;
}
// A segmented, voxel trunk. The joints can curl toward the water.
const trunkRoot = new THREE.Group();
trunkRoot.position.set(0, -0.08, 0.38);
headGroup.add(trunkRoot);
const trunkJoints = [];
let trunkParent = trunkRoot;
const trunkWidths = [0.34, 0.29, 0.24, 0.2];
for (let i = 0; i < 4; i++) {
const joint = new THREE.Group();
if (i > 0) joint.position.y = -0.47;
trunkParent.add(joint);
addBox(
joint,
trunkWidths[i], 0.48, trunkWidths[i],
0, -0.24, 0.015, bodyMaterial
);
trunkJoints.push(joint);
trunkParent = joint;
}
addBox(
trunkParent, 0.19, 0.08, 0.18,
0, -0.47, 0.02, darkMaterial, false
);
const legs = [];
for (const [x, z, phase] of [
[-0.52, 0.68, 0],
[0.52, 0.68, Math.PI],
[-0.52, -0.69, Math.PI],
[0.52, -0.69, 0]
]) {
const pivot = new THREE.Group();
pivot.position.set(x, 1.35, z);
visual.add(pivot);
addBox(pivot, 0.38, 1.2, 0.4, 0, -0.6, 0, bodyMaterial);
addBox(pivot, 0.43, 0.18, 0.53, 0, -1.14, 0.07, footMaterial);
legs.push({ pivot, phase });
}
const tail = new THREE.Group();
tail.position.set(0, 2.02, -1.23);
visual.add(tail);
addBox(tail, 0.1, 0.76, 0.1, 0, -0.34, 0, bodyMaterial);
addBox(tail, 0.2, 0.22, 0.19, 0, -0.78, 0, darkMaterial);
return {
root,
visual,
headGroup,
ears,
trunkJoints,
legs,
tail
};
}
// -------------------------------------------------------------------------
// Herd state machine
//
// waiting -> approaching -> drinking -> leaving -> resting -> approaching
//
// Each elephant owns one route and one drinking slot. A final collision
// solver provides an additional hard spacing guarantee.
// -------------------------------------------------------------------------
const elephantColors = [
0x77766d, 0x817b6e, 0x6f726c, 0x858074, 0x7c786c, 0x74756e
];
const initialHerd = [
{ route: 0, state: "waiting", progress: 0.28, timer: 5.2, speed: 1.05, scale: 1.00 },
{ route: 1, state: "drinking", progress: 1.00, timer: 4.8, speed: 1.08, scale: 1.00 },
{ route: 2, state: "approaching", progress: 0.52, timer: 0, speed: 0.92, scale: 0.68 },
{ route: 3, state: "waiting", progress: 0.73, timer: 4.3, speed: 1.02, scale: 1.00 },
{ route: 4, state: "drinking", progress: 1.00, timer: 7.2, speed: 1.04, scale: 1.00 },
{ route: 5, state: "leaving", progress: 0.16, timer: 0, speed: 1.10, scale: 1.00 }
];
const agents = [];
const stateColors = {
approaching: "#d39a3b",
waiting: "#88759c",
drinking: "#4d91a6",
leaving: "#9a6547",
resting: "#6d8050"
};
const stateLabels = {
approaching: "approaching",
waiting: "waiting",
drinking: "drinking",
leaving: "moving away",
resting: "resting"
};
function damp(current, target, lambda, dt) {
return THREE.MathUtils.lerp(current, target, 1 - Math.exp(-lambda * dt));
}
function dampAngle(current, target, lambda, dt) {
let delta = (target - current + Math.PI) % (Math.PI * 2);
if (delta < 0) delta += Math.PI * 2;
delta -= Math.PI;
return current + delta * (1 - Math.exp(-lambda * dt));
}
function agentRoutePosition(agent) {
if (agent.state === "leaving") {
return sampleRoute(agent.route, 1 - agent.progress);
}
if (agent.state === "resting") {
return sampleRoute(agent.route, 0);
}
return sampleRoute(agent.route, agent.progress);
}
function createAgents() {
initialHerd.forEach((config, index) => {
const model = createElephant(elephantColors[index]);
model.root.scale.setScalar(config.scale);
scene.add(model.root);
const agent = {
...config,
name: routeDefinitions[index].name,
route: routes[index],
model,
position: new THREE.Vector3(),
heading: 0,
gait: index * 0.9,
radius: config.scale < 0.8 ? 0.72 : 1.02
};
const sample = agentRoutePosition(agent);
agent.position.set(sample.x, 0, sample.z);
agent.heading = Math.atan2(sample.tx, sample.tz);
model.root.position.copy(agent.position);
model.root.rotation.y = agent.heading;
agents.push(agent);
});
}
createAgents();
function setState(agent, state) {
agent.state = state;
if (state === "drinking") {
agent.progress = 1;
agent.timer = range(5.2, 8.8);
} else if (state === "leaving") {
agent.progress = 0;
} else if (state === "resting") {
agent.progress = 1;
agent.timer = range(3.8, 6.4);
}
}
function resetHerd() {
agents.forEach((agent, index) => {
const config = initialHerd[index];
agent.state = config.state;
agent.progress = config.progress;
agent.timer = config.timer;
agent.gait = index * 0.9;
const sample = agentRoutePosition(agent);
agent.position.set(sample.x, 0, sample.z);
agent.heading = Math.atan2(sample.tx, sample.tz);
agent.model.root.position.copy(agent.position);
agent.model.root.rotation.y = agent.heading;
});
}
// -------------------------------------------------------------------------
// Status UI and world labels
// -------------------------------------------------------------------------
const statusList = document.querySelector("#status-list");
const labelsRoot = document.querySelector("#labels");
agents.forEach(agent => {
const row = document.createElement("div");
row.className = "status-row";
row.innerHTML = `
<span class="status-dot"></span>
<span class="status-name">${agent.name}</span>
<span class="status-action"></span>
`;
statusList.appendChild(row);
agent.statusRow = row;
const label = document.createElement("div");
label.className = "animal-label";
labelsRoot.appendChild(label);
agent.label = label;
});
let statusTimer = 0;
function updateStatus() {
agents.forEach(agent => {
agent.statusRow.querySelector(".status-dot").style.background =
stateColors[agent.state];
agent.statusRow.querySelector(".status-action").textContent =
stateLabels[agent.state];
agent.label.textContent =
`${agent.name} · ${stateLabels[agent.state]}`;
});
}
updateStatus();
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
function updateAgents(dt) {
// Update each route and state first.
agents.forEach(agent => {
if (agent.state === "waiting") {
agent.timer -= dt;
if (agent.timer <= 0) setState(agent, "approaching");
} else if (agent.state === "approaching") {
agent.progress += agent.speed * dt / agent.route.total;
if (agent.progress >= 1) {
agent.progress = 1;
setState(agent, "drinking");
}
} else if (agent.state === "drinking") {
agent.timer -= dt;
if (agent.timer <= 0) setState(agent, "leaving");
} else if (agent.state === "leaving") {
agent.progress += agent.speed * dt / agent.route.total;
if (agent.progress >= 1) {
agent.progress = 1;
setState(agent, "resting");
}
} else if (agent.state === "resting") {
agent.timer -= dt;
if (agent.timer <= 0) {
agent.progress = 0;
setState(agent, "approaching");
}
}
const sample = agentRoutePosition(agent);
const oldX = agent.position.x;
const oldZ = agent.position.z;
agent.position.x = sample.x;
agent.position.z = sample.z;
let targetHeading = agent.heading;
if (agent.state === "approaching" || agent.state === "waiting") {
targetHeading = Math.atan2(sample.tx, sample.tz);
} else if (agent.state === "leaving") {
targetHeading = Math.atan2(-sample.tx, -sample.tz);
} else if (agent.state === "resting") {
targetHeading = Math.atan2(-sample.tx, -sample.tz);
} else if (agent.state === "drinking") {
targetHeading = Math.atan2(-agent.position.x, -agent.position.z);
}
agent.heading = dampAngle(agent.heading, targetHeading, 7, dt);
const moved = Math.hypot(
agent.position.x - oldX,
agent.position.z - oldZ
);
agent.gait += moved * 3.1;
agent.movedThisFrame = moved;
});
// Hard safety net: no two elephants may occupy the same small area.
// The route geometry already keeps their lanes separate.
for (let i = 0; i < agents.length; i++) {
for (let j = i + 1; j < agents.length; j++) {
const a = agents[i];
const b = agents[j];
let dx = a.position.x - b.position.x;
let dz = a.position.z - b.position.z;
let distance = Math.hypot(dx, dz);
const minimum = a.radius + b.radius + 0.22;
if (distance >= minimum) continue;
if (distance < 0.0001) {
dx = 0.01;
dz = 0.01;
distance = Math.hypot(dx, dz);
}
const nx = dx / distance;
const nz = dz / distance;
const correction = minimum - distance;
const aMoving = a.state === "approaching" || a.state === "leaving";
const bMoving = b.state === "approaching" || b.state === "leaving";
if (aMoving && bMoving) {
a.position.x += nx * correction * 0.5;
a.position.z += nz * correction * 0.5;
b.position.x -= nx * correction * 0.5;
b.position.z -= nz * correction * 0.5;
} else if (aMoving) {
a.position.x += nx * correction;
a.position.z += nz * correction;
} else if (bMoving) {
b.position.x -= nx * correction;
b.position.z -= nz * correction;
}
}
}
// Pose each elephant.
agents.forEach(agent => {
const model = agent.model;
const moving =
agent.state === "approaching" || agent.state === "leaving";
const bob = moving
? Math.abs(Math.sin(agent.gait)) * 0.045
: 0;
model.root.position.set(
agent.position.x,
bob,
agent.position.z
);
model.root.rotation.y = agent.heading;
model.legs.forEach(leg => {
const swing = moving
? Math.sin(agent.gait + leg.phase) * 0.43
: 0;
leg.pivot.rotation.x = damp(
leg.pivot.rotation.x,
swing,
14,
dt
);
});
const drinking = agent.state === "drinking";
const headY = drinking ? 1.82 : 2.03;
model.headGroup.position.y = damp(
model.headGroup.position.y,
headY,
5,
dt
);
const idleCurl = [
-0.02,
-0.045 - Math.sin(agent.gait * 0.6) * 0.015,
-0.075,
-0.05
];
const drinkCurl = [-0.15, -0.3, -0.3, -0.2];
model.trunkJoints.forEach((joint, index) => {
const target = drinking
? drinkCurl[index]
: idleCurl[index];
joint.rotation.x = damp(
joint.rotation.x,
target,
drinking ? 4.5 : 2.5,
dt
);
});
model.ears.forEach((ear, index) => {
const side = index === 0 ? -1 : 1;
ear.rotation.z = damp(
ear.rotation.z,
side * (-0.1 + Math.sin(agent.gait * 0.75 + index) * 0.035),
5,
dt
);
});
model.tail.rotation.z = Math.sin(agent.gait * 0.8) * 0.12;
model.tail.rotation.x = Math.cos(agent.gait * 0.55) * 0.08;
});
}
function updateEnvironment(time) {
glints.forEach((glint, index) => {
const phase = time * 0.55 + glint.phase;
glint.mesh.position.x = glint.baseX + Math.sin(phase) * 0.08;
glint.mesh.position.z = glint.baseZ + Math.cos(phase * 0.8) * 0.05;
glint.mesh.scale.x =
0.7 + Math.sin(phase * 1.3 + index) * 0.2;
});
drinkingRipples.forEach((ripple, index) => {
const agent = agents[index];
const active = agent.state === "drinking";
if (active) {
const phase = (time * 0.52 + index * 0.16) % 1;
ripple.group.scale.setScalar(0.72 + phase * 0.95);
ripple.material.opacity = (1 - phase) * 0.52;
} else {
ripple.material.opacity = damp(
ripple.material.opacity,
0,
5,
0.016
);
ripple.group.scale.setScalar(
damp(ripple.group.scale.x, 0.8, 5, 0.016)
);
}
});
}
// -------------------------------------------------------------------------
// Custom orbit camera: pointer drag + wheel, no add-ons
// -------------------------------------------------------------------------
const orbit = {
theta: 0.72,
phi: 0.86,
radius: 42,
target: new THREE.Vector3(0, 0.75, 0)
};
const initialOrbit = { ...orbit };
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.theta -= dx * 0.0055;
orbit.phi = clamp(orbit.phi - dy * 0.0045, 0.38, 1.35);
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
orbit.radius = clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
23,
66
);
},
{ passive: false }
);
updateCamera();
// -------------------------------------------------------------------------
// Buttons, pause behavior, labels, and render loop
// -------------------------------------------------------------------------
let paused = false;
const pauseButton = document.querySelector("#pause");
function togglePause() {
paused = !paused;
pauseButton.textContent = paused ? "Resume herd" : "Pause herd";
}
pauseButton.addEventListener("click", togglePause);
document.querySelector("#restart").addEventListener("click", () => {
resetHerd();
updateStatus();
});
document.querySelector("#camera-reset").addEventListener("click", () => {
orbit.theta = initialOrbit.theta;
orbit.phi = initialOrbit.phi;
orbit.radius = initialOrbit.radius;
});
window.addEventListener("keydown", event => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
togglePause();
}
});
const projected = new THREE.Vector3();
function updateLabels() {
agents.forEach(agent => {
projected.set(
agent.position.x,
3.45 * agent.scale,
agent.position.z
);
projected.project(camera);
const visible = projected.z > -1 && projected.z < 1;
agent.label.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
agent.label.style.left = `${x}px`;
agent.label.style.top = `${y}px`;
});
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const clock = new THREE.Clock();
let simulationTime = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (!paused) {
simulationTime += dt;
updateAgents(dt);
updateEnvironment(simulationTime);
statusTimer += dt;
if (statusTimer > 0.2) {
updateStatus();
statusTimer = 0;
}
}
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(() => {
document.querySelector("#loading").classList.add("hidden");
});
</script>
</body>
</html>
```