WebGPU From Zero · Episode 08
Boids on the GPU
Boids on the GPU is Episode 08 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Tens of thousands of birds, no leader, no script — and yet they fold and twist through the sky as one body. That's a murmuration, and the astonishing fact is that the whole shape emerges from three dumb little rules each bird follows by looking only at its handful of nearest neighbors. In this finale we put one of those birds on every GPU invocation and let forty thousand of them flock in real time — every neighbor glance, every steering nudge, computed in parallel on the device.
Episode 07's particles were independent: each one read its own slot, integrated its own velocity, wrote its own slot back. Boids break that spell. Here every invocation has to read its neighbors — hundreds of other boids' positions — while everyone is updating at once. Read and write the same buffer in that situation and you get a data race: garbage in, garbage out. The fix is the single most important idea in GPU simulation, and the whole reason this is the season finale: ping-pong buffers. Read the frozen snapshot in buffer A, write the future into buffer B, swap, repeat. That's the foundation under every cloth solver, every fluid sim, every flocking crowd you've ever seen.
What you're looking at
Each little triangle is one boid, pointed in the direction it's heading. The
backend dropdown switches between the WebGPU compute path (the real
deal) and a plain JavaScript loop doing the identical math on the CPU — flip it and
watch the fps gap explode as you raise the count. The stage dropdown
walks the three flocking rules on one at a time so you can feel each one;
the weight sliders let you sculpt the flock from a tight nervous school to a loose
drifting cloud; vision sets how far each boid can see its neighbors; and
predator turns your mouse into a hawk the whole flock flees from. The
badge bottom-left always tells you the active backend and the live boid count.
Hold 60 fps on the GPU path well into the tens of thousands. The CPU path will buckle far sooner — that buckling is the entire point of the season, and here it buckles harder than in Episode 07, because flocking is O(N²): every boid looks at every other boid. More on that honestly, below.
One thing worth saying up front: there is no flock object anywhere in this program. Nothing tracks "the murmuration," computes its shape, or steers it. There are only N independent boids, each running the same tiny rulebook against whatever it can see, and the shape on screen is a side effect — pure emergence. That is exactly why it maps so cleanly onto a GPU: an emergent system made of identical local agents is a parallel program. Each boid is one thread. The murmuration is what 40,000 threads look like from a distance.
Stage 1 — No rules
Start with the skeleton. Each boid has a position and a velocity; every frame we just advance it along its heading and wrap it around the edges of the screen, like Asteroids. No boid is aware any other boid exists. It looks like television static that drifts — busy, but dead. This is the substrate. Everything interesting is about to come from boids reading each other.
Stage 2 — Separation
The first rule and the only one that's about personal space: steer away from neighbors that are too close. For each boid we scan the others; any that fall inside a small "too close" radius push back, harder the closer they are. Suddenly the static decongests — boids stop overlapping and spread into an even, breathing spacing. On its own, separation gives you a gas: particles that politely refuse to touch but have no reason to travel together.
Stage 3 — + Alignment
Add the second rule: match the average heading of the boids you can see. We sum up neighbors' velocities, average them, and steer toward that direction. Now boids that happen to be near each other start agreeing on a direction, and little currents form — ribbons of boids streaming the same way, then splitting, then re-forming. Alignment is what turns a gas into a flow. But the streams still wander apart; nothing pulls them back into a body.
Stage 4 — + Cohesion (full flocking)
The third and last rule closes the loop: steer toward the average position of your neighbors — the local center of mass. Now stragglers get reeled back in, the streams clump into a coherent mass, and the three rules start fighting each other in the productive way that makes flocking flocking: cohesion pulls the body together, separation keeps it from collapsing, alignment keeps it moving as one. This is Craig Reynolds' 1986 boids model in full, and three lines of arithmetic per neighbor is genuinely all it takes to get a murmuration. Tune the three weight sliders and watch the personality of the flock change in real time.
Stage 5 — Ping-pong, and why neighbor reads demand it
This is the lesson that earns the finale slot. In Episode 07 each particle only
ever touched its own slot, so updating the buffer in place was safe. Boids
are different: invocation i needs to read the positions of invocations
j, k, l… — and all of those are being
rewritten in the very same dispatch, in an order the GPU never promises you.
If boid i reads boid j's position, but j
already ran and overwrote itself with next frame's value, then i
is steering off a mix of present and future — a data race. Some
neighbors are "now," some are "next," and which is which changes every frame and
every GPU. The flock dissolves into seizing, flickering garbage. There's no error
message; it just looks broken.
The cure is to never read and write the same memory in one pass. Keep two copies of the flock. Each frame, treat one as a frozen, read-only snapshot of the present and compute every boid's future into the other:
Because A is never written during the pass that reads it, every boid sees the
exact same consistent snapshot of all its neighbors — no race, fully deterministic,
order-independent. Then you swap the two buffers and last frame's output becomes this
frame's input. This demo runs ping-pong in every stage (you can't see it,
which is the point); this stage just visualizes the A→B→A handoff so you know it's
there. Switch to the CPU backend and the same discipline applies: we read from one
Float32Array and write into a second, then swap the references.
Stage 6 — Scale, and your mouse becomes a predator
Now crank the boids slider toward 40,000 and keep the GPU backend
selected. Tens of thousands of triangles, every one of them consulting its neighbors
every frame, still holding frame rate — that's the payoff of putting the simulation
where the parallelism is. Toggle predator on and move your mouse through
the swarm: each boid that can see the cursor adds a strong flee force, and the flock
splits and re-knits around the threat exactly like real starlings dodging a hawk. The
weight sliders stay live the whole time — pull cohesion up and separation down for a
dense panicking ball; do the reverse for a thin, calm sheet.
The code — the flocking compute shader
Here is the heart of it: one invocation per boid, the honest O(N²) neighbor loop,
and the three steering forces accumulated with explicit f32 casts and a
guard against normalizing a zero vector. Note that it reads from boidsIn
and writes only to boidsOut — two different bindings. That separation is
the ping-pong:
struct Boid { pos: vec2<f32>, vel: vec2<f32> };
struct Params {
count: u32, dt: f32, sep: f32, ali: f32,
coh: f32, vision: f32, sepDist: f32, maxSpeed: f32,
mouse: vec2<f32>, predator: f32, rules: f32, // rules = how many rules are active (1..3)
bounds: vec2<f32>,
};
// PING-PONG: read one buffer, write the OTHER — never the same one.
@group(0) @binding(0) var<storage, read> boidsIn: array<Boid>;
@group(0) @binding(1) var<storage, read_write> boidsOut: array<Boid>;
@group(0) @binding(2) var<uniform> u: Params;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = gid.x;
if (i >= u.count) { return; } // guard the tail — dispatch rounds up
var me = boidsIn[i];
var sepForce = vec2<f32>(0.0, 0.0); // push away from the too-close
var aliSum = vec2<f32>(0.0, 0.0); // sum of neighbor velocities
var cohSum = vec2<f32>(0.0, 0.0); // sum of neighbor positions
var neighbors = 0.0;
let visSq = u.vision * u.vision;
let sepSq = u.sepDist * u.sepDist;
// O(N²): every boid looks at every other boid. Honest, and the cap on count.
for (var j = 0u; j < u.count; j = j + 1u) {
if (j == i) { continue; }
let other = boidsIn[j];
let off = me.pos - other.pos;
let d2 = dot(off, off);
if (d2 > visSq || d2 == 0.0) { continue; }
if (d2 < sepSq) {
sepForce = sepForce + off / d2; // closer ⇒ stronger push
}
aliSum = aliSum + other.vel;
cohSum = cohSum + other.pos;
neighbors = neighbors + 1.0;
}
var accel = vec2<f32>(0.0, 0.0);
if (neighbors > 0.0) {
let inv = 1.0 / neighbors; // explicit f32 math, no implicit casts
accel = accel + sepForce * u.sep;
if (u.rules >= 2.0) { // alignment: steer toward avg heading
accel = accel + (aliSum * inv - me.vel) * 0.06 * u.ali;
}
if (u.rules >= 3.0) { // cohesion: steer toward local center
accel = accel + (cohSum * inv - me.pos) * 0.0008 * u.coh;
}
}
// predator: flee the mouse if it's within vision
if (u.predator > 0.5) {
let toMe = me.pos - u.mouse;
let pd2 = dot(toMe, toMe);
if (pd2 < visSq * 4.0 && pd2 > 0.0) {
accel = accel + normalize(toMe) * 90.0 / max(sqrt(pd2), 8.0);
}
}
me.vel = me.vel + accel * u.dt;
// normalize(0) is NaN — guard the speed clamp with a length check.
let speed = length(me.vel);
if (speed > u.maxSpeed) { me.vel = me.vel / speed * u.maxSpeed; }
if (speed < 12.0 && speed > 0.0001) { me.vel = me.vel / speed * 12.0; }
me.pos = me.pos + me.vel * u.dt;
// wrap-around at the edges so nobody escapes the box
me.pos = (me.pos + u.bounds) % u.bounds;
boidsOut[i] = me; // write the OTHER buffer
}
The code — two buffers, two bind groups, one swap
Ping-pong is only three moving parts on the JS side: allocate two storage buffers, build two bind groups (one wired A→B, the other B→A), and flip an index each frame so the buffer you just wrote becomes next frame's input:
// 4 floats per boid (pos.xy + vel.xy) = 16 bytes — already 16B aligned.
const STRIDE = 4;
const byteSize = MAX_BOIDS * STRIDE * 4;
const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST;
// TWO buffers — the ping and the pong.
const buffers = [
device.createBuffer({ size: byteSize, usage }),
device.createBuffer({ size: byteSize, usage }),
];
device.queue.writeBuffer(buffers[0], 0, initialBoids);
// TWO bind groups. bindGroups[0]: read 0, write 1. bindGroups[1]: read 1, write 0.
const bindGroups = [0, 1].map((i) => device.createBindGroup({
layout: computePipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: buffers[i] } }, // read
{ binding: 1, resource: { buffer: buffers[i ^ 1] } }, // write the other
{ binding: 2, resource: { buffer: paramsBuffer } },
],
}));
let ping = 0; // which buffer is "now"
The code — dispatch, swap, then render the fresh buffer
Each frame: run the compute pass with the current bind group, advance the swap index, then draw from the buffer we just wrote — no CPU round-trip, the data never leaves the GPU:
function frame() {
device.queue.writeBuffer(paramsBuffer, 0, packParams()); // dt, weights, mouse…
const enc = device.createCommandEncoder();
// 1) COMPUTE: read buffers[ping], write buffers[ping^1]
const cpass = enc.beginComputePass();
cpass.setPipeline(computePipeline);
cpass.setBindGroup(0, bindGroups[ping]);
cpass.dispatchWorkgroups(Math.ceil(count / 64)); // workgroup_size(64)
cpass.end();
ping = ping ^ 1; // SWAP — what we just wrote is now "current"
// 2) RENDER from the freshly-written buffer (buffers[ping])
const rpass = enc.beginRenderPass({ colorAttachments: [{
view: context.getCurrentTexture().createView(),
clearValue: { r: 0.02, g: 0.03, b: 0.06, a: 1 },
loadOp: 'clear', storeOp: 'store' }] });
rpass.setPipeline(renderPipeline);
rpass.setVertexBuffer(0, buffers[ping]); // boids as instances
rpass.setBindGroup(0, renderBind);
rpass.draw(3, count); // one triangle per boid
rpass.end();
device.queue.submit([enc.finish()]);
requestAnimationFrame(frame);
}
The boid storage buffer doubles as the render path's vertex buffer (note
the VERTEX usage flag above), stepped per-instance, so the same 16 bytes
that the compute pass just wrote are read straight back by the vertex shader to place
and orient each triangle. The vertex shader rotates a unit triangle to face along the
boid's velocity:
struct VsOut { @builtin(position) clip: vec4<f32>, @location(0) shade: f32 };
@vertex
fn vs(@location(0) pos: vec2<f32>, @location(1) vel: vec2<f32>,
@builtin(vertex_index) vi: u32) -> VsOut {
// a little arrow pointing +x in local space
var tri = array<vec2<f32>, 3>(
vec2<f32>( 1.6, 0.0), vec2<f32>(-1.0, 0.9), vec2<f32>(-1.0, -0.9));
let p = tri[vi] * u.boidSize;
// heading from velocity; guard the zero-vector case (normalize(0)=NaN)
var dir = vec2<f32>(1.0, 0.0);
let sp = length(vel);
if (sp > 0.0001) { dir = vel / sp; }
let rot = mat2x2<f32>(dir.x, dir.y, -dir.y, dir.x); // face along velocity
let world = pos + rot * p;
let ndc = world / u.bounds * 2.0 - 1.0; // pixels → clip space
var out: VsOut;
out.clip = vec4<f32>(ndc.x, -ndc.y, 0.0, 1.0);
out.shade = clamp(sp / u.maxSpeed, 0.3, 1.0); // faster = brighter
return out;
}
Common pitfalls
- Reading and writing one buffer = a data race (the big one).
This is the whole episode. If your compute shader reads
boids[j]and writesboids[i]in the same pass, neighbors are a random mix of this frame and next frame, and the flock turns to flickering garbage with no error printed. Two buffers, swap each frame. Always, for any neighbor-reading sim. - O(N²) caps the count. Every boid scanning every other boid is N² distance checks — 40k boids is 1.6 billion per frame. The GPU eats it far longer than a CPU, but it's still the wall you hit. The real fix is a spatial grid: only test boids in nearby cells, which needs a GPU sort to bucket them — exactly the machinery the Gaussian Splatting series builds for depth sorting, and a Season 3 topic here.
normalize(0)is NaN. A boid with zero velocity, or one sitting exactly on a neighbor, makesnormalize()divide by zero and poison the whole buffer (NaN spreads). Guard every normalize with a length check, as in both shaders above.- Forgetting the tail guard. Dispatch rounds up to whole
workgroups, so with
workgroup_size(64)and 6000 boids you launch 6016 invocations. Withoutif (i >= count) { return; }the extra 16 read and write out of bounds. - Vision radius too large tanks fps. A bigger vision radius means
every boid counts more neighbors, more steering math, more bandwidth. It's the
cheapest way to drop below 60 — slide
visionup and watch. Keep it as small as still looks like flocking. - Boids escaping the box. Without wrap-around (or a soft
turn-back force) the flock drifts off-screen and never returns. We modulo positions
back into
boundsevery frame. Beware: a naïve%on a negative number can go wrong, so we addboundsbefore taking the remainder. - Two bind groups, not one. A classic ping-pong bug is building a single bind group and reusing it — then you only ever ping, never pong. You need both wirings (A→B and B→A) and you must select the right one for the current frame.
Exercises
- Add a food source they swarm. Put a second point in the params (like the predator, but attractive). Add an acceleration toward it scaled by distance, and watch the flock collapse into a feeding frenzy around it. Bonus: make the food move and they'll chase it like fish after bait.
- Add a second predator. Pass two mouse-like points (e.g. the cursor plus an auto-circling one). Now the flock has to thread between two threats — you'll see it tear into sub-flocks and re-merge, which single-predator flocking never does.
- Tune for a tight school vs a loose cloud. With the sliders: high cohesion + low separation + high max-speed gives a dense, darting bait-ball; low cohesion + high separation + small vision gives a thin, calm, drifting sheet. Find the knife-edge where the flock keeps splitting and re-forming — that's the sweet spot real murmurations live in.
If you want a harder challenge, the honest next step is the one the pitfalls keep pointing at: replace the brute-force neighbor loop with a spatial grid. Bin every boid into a cell by its position, sort the boids by cell id on the GPU, and then each boid only scans the handful of boids in its own cell and the eight around it. That turns O(N²) into roughly O(N) and is what lets production crowd sims push into the hundreds of thousands. It also forces you to learn a parallel sort — which is precisely the tool the splatting series builds for depth ordering.
What's next — Season 1 is complete
That's the season. Across eight episodes you went from a blank canvas to a living forty-thousand-body simulation, and you did it with zero dependencies — every pipeline, buffer, and line of WGSL written by hand. You learned the render pipeline (Eps 01–04), then crossed into compute: independent particles updating in place (Ep 07), and now interaction — boids reading their neighbors, the data race that lurks there, and ping-pong as the discipline that makes any GPU physics sim correct. That last idea is the load-bearing beam under cloth, fluids, soft bodies, and crowds. You have the foundation.
Season 2 — Rendering for Real turns from simulation back to making things look good: a real depth buffer and 3D geometry, physically-based shading (PBR) so surfaces respond to light like the real world, shadow maps so things cast shadows, and a post-processing chain (bloom, tone-mapping, anti-aliasing) to tie it together. Season 1 made the GPU compute; Season 2 makes it shade. Cross-pollinate while you wait: the Shaders From Zero series is the GLSL mirror of all this WGSL, and the Gaussian Splatting series is where the GPU sort that fixes our O(N²) neighbor loop actually gets built.