WebGPU From Zero · Episode 06
Hello, Compute
Hello, Compute is Episode 06 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
For five episodes the GPU has been a very fast painter: the CPU decides
where every particle goes, hands over a fresh buffer, and the GPU dutifully draws it.
The GPU never thinks. That asymmetry is the wall WebGL spent fifteen years
stuck behind — there was no first-class way to run general math on the GPU, only clever
abuse of pixel shaders. WebGPU tears that wall down with one new word:
@compute. Today the GPU stops waiting for instructions and starts updating
the simulation itself.
Here's the promise, and it's the whole episode in one sentence: you will flip
a single toggle — CPU ⇄ GPU — and watch the particle ceiling jump fifty to a hundred
times. Same physics, same integrator, written twice: once as a plain JavaScript
loop over a Float32Array, once as a WGSL compute shader. On the CPU, crank
the count and watch 60fps crumble around ten or twenty thousand particles. Flip to GPU
and drag the slider to two hundred thousand without the frame timer blinking. By the end
you'll know exactly why — and you'll have written every line that makes it true.
What you're looking at
The canvas holds a swarm of particles, each with a 2-D position, orbiting the center in a rotation field. Every frame each particle is advanced one small step — rotated a fraction of a degree around the origin. Advancing state by one time-step like this is integration — the beating heart of every physics simulation, from smoke to cloth to galaxies. The only question this episode asks is who does the nudging: one CPU core marching through an array, or thousands of GPU lanes moving in lockstep.
The HUD tells the whole story. Top-left is the live fps. Bottom-left
is the badge: the backend (WebGPU or
fallback (CPU)), the active path (CPU/GPU), and the
particle count. The segmented CPU/GPU control in the corner is the one
you came for. Pick a stage to walk the build; flip the backend at any time to feel the
difference in your gut.
Stage 1 — CPU particles
We start where WebGL left us. The particle state lives in a plain
Float32Array — four floats per particle, [x, y, vx, vy] — and a
JavaScript for loop walks the whole thing once per frame, doing the
integration by hand. The positions are then copied into a GPU vertex buffer just so we
can see them. This is the honest baseline, and it is the same code shape every
particle tutorial you've ever read uses:
// CPU integrator — one core, one element at a time.
// state layout: [x, y, vx, vy] repeated, N times.
function stepCPU(state, count, dt, force) {
for (let i = 0; i < count; i++) {
const o = i * 4;
const px = state[o], py = state[o + 1];
let vx = state[o + 2], vy = state[o + 3];
// rigid rotation about the origin: radius is preserved exactly,
// so the cloud orbits forever and can never drift off-screen.
const a = (0.01 + force * 0.05) * dt; // angular step from the slider
const c = Math.cos(a), s = Math.sin(a);
const nx = px * c - py * s;
const ny = px * s + py * c;
state[o] = nx;
state[o + 1] = ny;
state[o + 2] = nx - px; // store the step as a pseudo-velocity
state[o + 3] = ny - py;
}
}
It works, and at a few thousand particles it's smooth. Now grab the count slider and pull. Somewhere around 15–25k (depending on your machine) the fps number starts sliding off 60, then 50, then into the 30s. You can watch a single core run out of road. That ceiling isn't a bug — it's the fundamental limit of doing N independent jobs one after another. The fix isn't a faster loop. It's no loop at all.
Stage 2 — First compute pass
Here's the conceptual leap. Those N iterations of the loop don't depend on each other
— particle 7 doesn't care what happened to particle 6. They're embarrassingly
parallel. A compute shader takes that loop body, deletes the for,
and tells the GPU: "run this once per particle, all at once, across thousands of lanes."
The loop counter i becomes a built-in the GPU hands you:
global_invocation_id.
Flip the backend to GPU on this stage. The motion is identical — the same
rotation step — but now the integration happens in a @compute shader,
and the particle data never leaves the GPU. Watch the fps: it doesn't move. The CPU's job
shrank from "integrate N particles" to "tell the GPU to go." Here is that shader, and it's
worth reading line by line because it is the CPU loop body, transposed:
// WGSL compute shader — the loop body, run N times in parallel.
struct Particle { pos: vec2<f32>, vel: vec2<f32> };
struct Params { dt: f32, force: f32, count: u32, _pad: u32 };
// read_write storage: every lane reads its own slot and writes it back.
@group(0) @binding(0) var<storage, read_write> particles: array<Particle>;
@group(0) @binding(1) 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; } // the tail guard — see below
var p = particles[i];
// rigid rotation about the origin: radius preserved → orbits, never escapes.
let a = (0.01 + u.force * 0.05) * u.dt;
let c = cos(a); let s = sin(a);
let nx = p.pos.x * c - p.pos.y * s;
let ny = p.pos.x * s + p.pos.y * c;
p.pos = vec2<f32>(nx, ny);
particles[i] = p; // in-place: lane i owns slot i
}
Three things to notice. The state buffer is declared var<storage,
read_write> — a storage buffer, the compute-era replacement for
the read-only uniforms you've used so far; it can be both read and written by the shader.
Each invocation touches only its own index, so there are no data races: lane
i owns slot i, full stop. And the layout — vec2f
pos + vec2f vel = 16 bytes — is a clean, aligned 16-byte stride, which keeps
WGSL's alignment rules happy without padding gymnastics.
Stage 3 — Storage buffer read_write + dispatch
A shader is inert until you run it. Drawing uses a render pass and
draw(); computing uses a compute pass and
dispatchWorkgroups(). The setup mirrors a render pipeline you already know,
with createComputePipeline in place of createRenderPipeline:
// One storage buffer holds all particle state on the GPU.
// usage must list EVERY way we touch it: compute writes it (STORAGE),
// the render pass reads it as geometry (VERTEX), we seed it (COPY_DST).
const stride = 4; // floats per particle: x,y,vx,vy
const particleBuf = device.createBuffer({
size: MAX_COUNT * stride * 4,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
const paramBuf = device.createBuffer({
size: 16, // dt, force, count, pad — 16B
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const computePipe = device.createComputePipeline({
layout: 'auto',
compute: { module: device.createShaderModule({ code: COMPUTE_WGSL }), entryPoint: 'main' },
});
const computeBind = device.createBindGroup({
layout: computePipe.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuf } },
{ binding: 1, resource: { buffer: paramBuf } },
],
});
Now the per-frame dance. We write the latest dt/force/count into the
uniform, open a compute pass, and dispatch. The crucial number is the
workgroup count: the GPU runs threads in fixed blocks of
@workgroup_size(64), so to cover N particles we ask for
ceil(N / 64) groups:
device.queue.writeBuffer(paramBuf, 0,
new Float32Array([dt, force, 0, 0])); // count written as u32 below
device.queue.writeBuffer(paramBuf, 8, new Uint32Array([count]));
const enc = device.createCommandEncoder();
// ── compute pass: move the particles ──
const cpass = enc.beginComputePass();
cpass.setPipeline(computePipe);
cpass.setBindGroup(0, computeBind);
cpass.dispatchWorkgroups(Math.ceil(count / 64)); // rounds UP → tail guard matters
cpass.end();
// ── render pass: draw the very same buffer (next stage) ──
const rpass = enc.beginRenderPass({ /* … */ });
// … draw …
rpass.end();
device.queue.submit([enc.finish()]); // both passes, one submit
Look closely at Math.ceil(count / 64). If count is 40,000,
that's 625 workgroups × 64 lanes = 40,000 exactly — lucky. But ask for
40,050 particles and you get 626 groups × 64 = 40,064 lanes: 14 extra invocations
with no particle to update. Those phantom lanes have i values past
the end of the array. Without protection they'd write past the buffer — corruption, or a
validation error, or worse, silently wrong physics. That's why every compute shader in
this series opens with if (i >= u.count) { return; }. It is the single
most-forgotten line in all of compute. Burn it in.
Stage 4 — The CPU ⇄ GPU toggle
This is the episode. Both integrators are wired up and the toggle swaps between them live, with the same particle count, the same forces, the same drawing code — only the who changes. The experiment is simple and you should actually do it: set the count to something the CPU can almost handle, then flip back and forth.
- Flip to CPU. Drag the count up until fps just dips below 60 — note the number. On a typical laptop that's roughly 15–25k.
- Flip to GPU at that same count. fps snaps back to a locked 60 and doesn't flinch.
- Now keep dragging on GPU. 50k, 100k, 200k — still 60. The GPU ceiling for this sim is roughly 50–100× higher than the CPU's.
Why such a gulf for identical arithmetic? Because the CPU does the work sequentially — one core, one particle, then the next — while the GPU does it in parallel across thousands of lanes at once. Forty thousand particles is forty thousand loop iterations on the CPU; on the GPU it's a few hundred workgroups that all run together. Same math, radically different schedule. That schedule is the entire reason compute exists.
One discipline makes this honest, and it's the easiest win to throw away: do not
read the particles back to the CPU. It is tempting to mapAsync the
storage buffer each frame "to check the values" — but a GPU→CPU readback is a synchronizing
round-trip that stalls the pipeline and erases the entire speedup. The particles are
computed on the GPU and drawn on the GPU; the CPU never sees a single coordinate. Keeping
data resident is half of why compute is fast.
Stage 5 — A force field
Parallel arithmetic is cheap, so let's spend some on beauty. This stage makes the
rotation speed vary with radius — differential rotation — so the disc shears into
drifting spiral arms instead of turning like a rigid plate. Crucially, none of this
costs the CPU anything — it's all in the shader, evaluated per particle, in
parallel. Drag the force slider and the whole field breathes. Here's the upgraded
step, dropped straight into the compute shader's main:
// Differential rotation: angular speed varies with radius → spiral shear.
let local = 1.0 + 0.8 * sin(length(p.pos) * 4.0);
let a = (0.01 + u.force * 0.05) * local * u.dt;
let c = cos(a); let s = sin(a);
let nx = p.pos.x * c - p.pos.y * s;
let ny = p.pos.x * s + p.pos.y * c;
p.pos = vec2<f32>(nx, ny);
This is the moment the value of compute clicks: a fancier force field is just more lines
in main, paid for once across all lanes. On the CPU, every extra term in that
expression is multiplied by N and runs serially — it makes the ceiling lower. On
the GPU it's nearly free. Compute doesn't just move existing work faster; it changes what
you can afford to compute at all.
Stage 6 — Scale up
Now the payoff lap. Push the count to its max — 200k — on GPU. The swarm becomes a luminous, structured cloud and the fps stays pinned at 60. Then, with the count still maxed, flip to CPU and watch the frame timer fall off a cliff: the single core simply cannot integrate two hundred thousand particles sixty times a second. The two backends are now visibly in different leagues — and you wrote both. To draw all those particles with zero CPU involvement, the render pass reads the same storage buffer directly as a vertex buffer:
// The storage buffer IS the vertex buffer — no copy, no readback.
// Each vertex pulls [x, y] (vel is just stride padding for drawing).
const renderPipe = device.createRenderPipeline({
layout: 'auto',
vertex: {
module, entryPoint: 'vs',
buffers: [{
arrayStride: 16, // 4 floats: x,y,vx,vy
stepMode: 'vertex',
attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }],
}],
},
fragment: { module, entryPoint: 'fs', targets: [{ format,
blend: { color: { srcFactor: 'one', dstFactor: 'one' }, // additive glow
alpha: { srcFactor: 'one', dstFactor: 'one' } } }] },
primitive: { topology: 'point-list' },
});
// in the render pass: bind the storage buffer as a vertex source and draw points.
rpass.setPipeline(renderPipe);
rpass.setVertexBuffer(0, particleBuf); // the SAME buffer compute just wrote
rpass.draw(count); // one point per particle
That setVertexBuffer(0, particleBuf) is the quiet payoff of the whole
episode: the buffer the compute pass just finished writing is handed straight to the
rasterizer in the same command encoder. The data is born, lives, and dies on the GPU. This
is the architecture every "a million particles" demo runs on, and it's exactly where
Episode 07 picks up.
The shape of a compute frame
Step back and the whole machine fits in a diagram. One command encoder carries a compute pass and a render pass back-to-back; one buffer flows between them; the CPU only writes a handful of uniform bytes:
That's the canonical compute-then-draw loop. Master it and you have the skeleton for fluids, boids, cloth, particle systems, image filters — anything where the same operation repeats across a big array.
Common pitfalls
- Forgetting the tail guard.
dispatchWorkgroupsrounds up to whole workgroups, so the last group almost always launches lanes past your array's end. Withoutif (i >= u.count) { return; }those lanes write out-of-range — corruption or a validation crash. This is the classic compute bug; write the guard before you write anything else. - A bad workgroup size. GPUs schedule threads in hardware bundles of
32 or 64. Pick
@workgroup_size(64)(or 32, 128, 256) — a multiple of 32. An odd size like 50 leaves lanes idle inside every bundle and quietly wastes throughput. - Incomplete buffer usage flags. The particle buffer is written by
compute (
STORAGE), read by the rasterizer (VERTEX), and seeded from the CPU (COPY_DST) — so itsusagemust OR all three. Forget one and you get a validation error at bind-group or draw time, not where you'd expect. - Reading back to the CPU per frame.
mapAsyncis a synchronizing round-trip. Doing it in the hot loop stalls the GPU and erases the entire win. Compute, then draw the result — don't ferry it back to JavaScript. - Bind-group layout doesn't match the shader. Every
@group(g) @binding(b)in the WGSL must have a matching entry, with a compatible buffer type (storage vs uniform). A mismatch throws at pipeline or bind-group creation — read the validation message; it names the offending binding. - Mixing the two passes up. A compute pass and a render pass are
separate objects, even inside the same encoder. You
beginComputePass…end()for the integration, thenbeginRenderPass…end()for the draw. You can't dispatch inside a render pass or draw inside a compute pass.
Exercises
- Tune the workgroup size and measure. Change
@workgroup_size(64)to 32, then 128, then 256 (and divide by the same number indispatchWorkgroups). At 200k particles, does the fps or frame time budge? You'll learn that 64 is a fine default and that the choice matters far less than beginners fear — as long as it's a multiple of 32. - Add a second force. Introduce a constant downward "gravity" term
(
p.vel.y -= 0.5 * u.dt;) on top of the attractor. Watch the swarm sag and pool. Notice this costs the GPU essentially nothing — but if you add the same term to the CPU path, the ceiling drops. Feel the asymmetry. - Let the user place gravity wells. Add two more floats to
Paramsfor a mouse position, feed the canvas pointer coordinates in viawriteBuffer, and add an attractor toward that point in the shader. Now the swarm chases your cursor — 200k particles steered live, all on the GPU, with the CPU only shipping two numbers a frame.
What's next
Episode 07 — A Million Particles. We take this exact compute-then-draw skeleton and push it to its conclusion: a million particles, positions evolved on the GPU by a curl-noise flow field instead of a single attractor, so the swarm flows like smoke. Same storage buffer, same dispatch, same no-readback discipline — just a richer force and a lot more lanes. The toggle you built today is the proof you'll need that none of it could ever have run on a CPU.