Three.js From Zero · Article s16-05
Boids — A Murmuration Nobody Programmed
Three steering rules, 1,200 instanced birds, and a spatial hash grid: emergence at 60fps, with turn-waves made visible by heading-mapped color. Part of the MasterAllArts Creative 3D Roadmap.
Part of the MasterAllArts Creative 3D Roadmap .
Season 16 · Article 05 · Beautiful Math
In 1987, Craig Reynolds put three rules into a computer — stay apart, align, stay together — and flocks came out. No leader, no choreography, no flock variable anywhere in the code. Twelve hundred birds, each seeing only its neighbors, and the shape they make sees itself. This is emergence, the headline act of mathematical beauty, and it runs at 60fps in your browser tab.
Drag to orbit. Watch for the turn waves — when one edge of the flock turns, the decision ripples through the body as a wave of shifting color (color tracks heading, so turns become visible). Then run the three classic experiments: alignment to 0 — the flock dissolves into a gnat cloud. Cohesion to 3 — it collapses into a writhing ball. Separation to 0 — the ball tightens into a black-hole knot. And hawk! hits every bird with a panic impulse so you can watch the flock re-assemble itself from chaos — the rules don't know what "re-assemble" means, and they do it anyway.
Three rules, no conductor
Every frame, each boid looks at neighbors within a perception radius and computes three steering nudges:
- Separation — push away from neighbors that are too close, weighted by 1/distance² so personal space is non-negotiable up close and irrelevant far away.
- Alignment — steer toward the average heading of the neighborhood.
- Cohesion — steer toward the neighborhood's center of mass.
velocity += separation · w₁ + alignment · w₂ + cohesion · w₃
velocity = clampSpeed(velocity, MIN, MAX)
position += velocity · dt
My old atlas sketch runs this for 42 boids in 2D, brute force. Going to 1,200+ birds in 3D forces the two upgrades this article is actually about: drawing that many oriented bodies cheaply, and finding neighbors without comparing everyone to everyone.
Step 1 — Birds that face where they fly
The bodies are an InstancedMesh of stretched cones — straight from
the phyllotaxis article, plus
one new ingredient: rotation. The trick is to align the geometry's axes with the
math once, at creation, then let lookAt do all quaternion work per frame:
const body = new THREE.ConeGeometry(0.35, 1.4, 5);
body.rotateX(Math.PI / 2); // cone points +Y by default → re-aim it down +Z
// per bird, per frame:
dummy.position.set(px, py, pz);
dummy.lookAt(px + vx, py + vy, pz + vz); // +Z now means "forward"
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
Object3D.lookAt points the local +Z axis at a target — which is why we rotated
the cone to point down +Z first. Bake the convention into the geometry once; never fight it
in the loop.
Step 2 — The spatial hash: the real lesson
Naive neighbor search compares every bird to every other: at 1,200 birds that's 1.44 million distance checks per frame; at 2,500 it's 6.25 million, and your simulation drowns. The fix is the workhorse of every particle system, physics engine, and crowd sim ever shipped — the uniform spatial hash:
const CELL = 6; // = perception radius, not a coincidence
const grid = new Map();
function key(x, y, z) { // integer cell coords → one number
return ((x + 64) << 14) | ((y + 64) << 7) | (z + 64);
}
// rebuild each frame: O(N)
grid.clear();
for (let i = 0; i < N; i++) {
const k = key(Math.floor(px / CELL), Math.floor(py / CELL), Math.floor(pz / CELL));
if (!grid.has(k)) grid.set(k, []);
grid.get(k).push(i);
}
Setting the cell size equal to the perception radius is the whole design: any neighbor a bird can perceive must be in its own cell or one of the 26 touching it. So the search loop visits at most 27 small buckets instead of the entire population. The stats bar shows the live number of distance checks per bird — drag the count to 2,500 and watch checks/bird stay flat while the naive version would have quintupled.
Step 3 — Keeping the show on stage
Two pieces of stagecraft that every flocking demo needs and most tutorials forget:
// soft spherical boundary: a pull, not a wall
const d = Math.sqrt(px*px + py*py + pz*pz);
if (d > R_SOFT) {
const pull = (d - R_SOFT) * 0.025;
vx -= (px / d) * pull; vy -= (py / d) * pull; vz -= (pz / d) * pull;
}
// clamp speed BOTH ways
const sp = Math.sqrt(vx*vx + vy*vy + vz*vz);
const cl = Math.max(MIN_SPEED, Math.min(MAX_SPEED, sp));
vx = (vx / sp) * cl; vy = (vy / sp) * cl; vz = (vz / sp) * cl;
A hard wall (bounce or wrap) makes the flock look caged; a soft radial pull makes the boundary invisible — the flock just always happens to turn back, like it meant to. And the minimum speed matters more than the maximum: real birds can't hover, and the moment a boid is allowed to stop, cohesion glues it into a dead clump. Minimum speed is what keeps a murmuration looking liquid.
Step 4 — Color is data, fourth verse
Season pattern: Lorenz colored by speed, phyllotaxis by age, the harmonograph by time. Boids get colored by heading — the vertical component of velocity, normalized:
c.copy(diveColor).lerp(climbColor, vy / sp * 0.5 + 0.5);
mesh.setColorAt(i, c);
Alone, one bird's color is noise. But neighbors align — that's rule two — so color is spatially correlated, and when a turn propagates through the flock it travels as a visible wave of orange or violet. The render isn't decorating the simulation; it's instrumenting it.
What the sliders teach
- separation / alignment / cohesion — the three-body personality space. Almost every animal-group behavior you've seen footage of lives somewhere in this cube: gnat swarm (low align), fish bait-ball (high coh, high sep), starling sheet (high align, moderate everything else).
- birds — the spatial hash earning its keep, live, in the stats bar.
- hawk! — emergence's party trick: recovery was never programmed, only the conditions for it.
The skeleton
<script type="importmap">
{ "imports": {
"three": "https://unpkg.com/three@0.170.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/" } }
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// InstancedMesh of +Z-aligned cones (Step 1)
// per frame: rebuild spatial hash, O(N) (Step 2)
// steer (3 rules + boundary + clamp) (Step 3)
// dummy.lookAt → setMatrixAt, setColorAt (Steps 1, 4)
</script>
Next: S16-06 — Reaction–Diffusion. Two chemicals, one blur, and leopard spots grow on your GPU: the season's first step from geometry into shaders.