WebGPU From Zero · Episode 05

Instancing: 100k Quads

Instancing: 100k Quads is Episode 05 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 05 · WebGPU From Zero

One draw call. A hundred thousand things. That's not a typo and it's not a streaming trick — it's a single line, pass.draw(6, 100000), and the GPU rasterizes a hundred thousand little animated sprites in the same breath it would draw one. No loop on the CPU, no hundred thousand draw calls choking the driver. You describe one quad and say "now do that N times, and here's a buffer telling you how each copy differs." The GPU spreads the work across thousands of cores and paints the whole shimmering field in parallel.

This is the first real scale flex of the series, and it's also the on-ramp to the back half. By the end you'll have a field of 100k sprites breathing at 60fps — and you'll feel exactly where it stops being free. Crank the count and watch the frame time climb, not because the GPU is drawing more (it laughs at 100k quads) but because the CPU is rewriting that buffer every single frame. That wall is the whole point. Episode 06 tears it down by letting the GPU write the buffer itself.

0 fps
init…
A single quad built from six vertices — no buffer, no instances. The seed of everything.

What you're looking at

Six stages, one machine. The same vertex shader runs the whole demo; all that changes is how many copies we ask for and how much per-copy data we feed it. Stage 1 draws a lone quad. Stage 2 stamps a handful of copies using nothing but the instance number. Stage 3 starts reading a real storage buffer for each instance's position; Stage 4 adds color and size to that buffer. Stage 5 animates 10k of them by rewriting the buffer every frame, and Stage 6 pushes to 100k+ with the count slider so you can watch the CPU-update cost surface as a visible wall. The badge shows your backend (WebGPU or a Canvas2D fallback), the live instance count, and the per-frame CPU upload cost in milliseconds.

Stage 1 — One quad, no buffer

Before instancing, the foundation: how do you draw a quad with no vertex buffer at all? The same trick Episode 01 used for its fullscreen triangle — @builtin(vertex_index). The GPU calls your vertex shader once per vertex and hands it the index of which vertex this is (0…5 for a six-vertex quad). You look up the corner position from a small constant array baked into the shader. Two triangles, six verts, zero buffers:

// Six vertices = two triangles = one quad, in normalized [-1,1] corner space.
fn quadCorner(vi: u32) -> vec2f {
  var c = array<vec2f, 6>(
    vec2f(-1., -1.), vec2f( 1., -1.), vec2f(-1.,  1.),  // tri A
    vec2f(-1.,  1.), vec2f( 1., -1.), vec2f( 1.,  1.),  // tri B
  );
  return c[vi];
}

We draw it with pass.draw(6) — six vertices, one instance (the default). One quad sits in the middle of the screen. Boring, but it's the cell we're about to clone a hundred thousand times.

Stage 2 — A few instances from the instance index

Here's the leap. Call pass.draw(6, 12) and the GPU runs your vertex shader 72 times: six vertices × twelve instances. Each invocation gets two indices — @builtin(vertex_index) (which corner, 0…5) and @builtin(instance_index) (which copy, 0…11). The corner builds the quad shape; the instance index moves the whole copy somewhere new. With nothing but the instance number and some arithmetic, we can scatter twelve quads across the screen:

// Stage 2: offset each instance purely from its index — still no buffer.
let corner = quadCorner(vi) * 0.06;
let fi  = f32(ii);
let ang = fi * 2.39996;                 // golden angle → even spiral
let rad = sqrt(fi) * 0.12;
let center = vec2f(cos(ang), sin(ang)) * rad;
let pos = center + corner;

This is the core mental model: one quad, many positions, and the position is a pure function of the instance index. The CPU sent one draw command. The driver didn't break a sweat. But indices alone are a weak way to vary instances — you can't store a captured galaxy in cos(ii). For real per-instance data, we need a buffer.

Stage 3 — Per-instance position from a storage buffer

Now the centerpiece. We allocate a storage buffer — a big flat array the shader can index freely — and fill it on the CPU with one record per instance. The vertex shader reads its own record using instance_index as the subscript. The buffer is uploaded once; from then on the draw call is just pass.draw(6, N) and the GPU fans out across the array.

An Instance is a small struct. WGSL storage structs follow alignment rules (more on this below), so we lay it out to land cleanly on 16-byte boundaries. For Stage 3 we only read pos, but we define the full struct up front so the later stages just light up fields that were already there:

// WGSL — the per-instance record, read in the VERTEX shader.
struct Instance {
  pos:   vec2f,   // world-ish xy   (offset  0)
  size:  f32,    // half-extent    (offset  8)
  phase: f32,    // anim phase     (offset 12)
  color: vec4f,   // rgb + a        (offset 16)
};                // stride = 32 bytes — already 16-aligned

// One bound resource: a read-only array of those records.
@group(0) @binding(1) var<storage, read> insts: array<Instance>;

The matching CPU layout is a Float32Array with the same stride. Get this wrong by one float and every instance reads garbage shifted out of its neighbor. Eight floats × 4 bytes = the 32-byte stride the struct declares:

// JS — must mirror the WGSL struct exactly. STRIDE in *floats*.
const STRIDE = 8;                       // pos.xy, size, phase, color.rgba
const data = new Float32Array(count * STRIDE);
for (let i = 0; i < count; i++) {
  const o = i * STRIDE;
  data[o+0] = x;  data[o+1] = y;     // pos.xy
  data[o+2] = halfSize;               // size  (float @ +8 bytes)
  data[o+3] = Math.random() * 6.283;     // phase (float @ +12 bytes)
  data[o+4] = r; data[o+5] = g;        // color.rg (vec4 starts @ +16)
  data[o+6] = b; data[o+7] = 1.;        // color.ba
}

The positions come from a tiny seeded RNG so the field is identical every load. Switch to Stage 3 and the spiral becomes a real, scattered cloud — read from memory, not computed from an index. This is how a captured scene, a particle system, or a point cloud actually gets to the GPU.

Stage 4 — Color and size from the same buffer

The fields were already in the struct, so Stage 4 costs nothing extra to upload — we just use them. The vertex shader scales the quad by the instance's size and passes its color through to the fragment shader. Here's the full vertex shader, the heart of the episode — note how it pulls one record by instance_index and builds the quad from vertex_index:

struct VSOut {
  @builtin(position) clip: vec4f,
  @location(0) uv:    vec2f,   // corner coord, for the round mask
  @location(1) color: vec4f,
};

@vertex
fn vs(@builtin(vertex_index) vi: u32,
       @builtin(instance_index) ii: u32) -> VSOut {
  let inst   = insts[ii];               // ← per-instance record
  let corner = quadCorner(vi);           // ← per-vertex shape  (-1..1)

  let world  = inst.pos + corner * inst.size;
  let p      = world * vec2f(u.aspect, 1.) * u.zoom;

  var out: VSOut;
  out.clip  = vec4f(p, 0., 1.);
  out.uv    = corner;
  out.color = inst.color;
  return out;
}

And the fragment shader carves each quad into a soft round sprite with a smooth falloff — the same circle-from-a-square idea as the splatting series, but in WGSL:

@fragment
fn fs(in: VSOut) -> @location(0) vec4f {
  let d = length(in.uv);                 // 0 at center, ~1.41 at corners
  let a = (1. - smoothstep(0.6, 1.0, d)) * in.color.a;
  if (a < 0.01) { discard; }
  return vec4f(in.color.rgb * a, a);    // premultiplied
}

Now the field has texture: warm motes near the core, cool ones at the rim, each a different size. Every pixel of variety came out of that one storage buffer, indexed by instance_index.

Stage 5 — 10k animated, the CPU rewriting the buffer

Static data uploads once and lives on the GPU forever — practically free. The moment things move, something has to recompute positions and get them back to the GPU. The simplest way (and the wrong way, as we'll see) is to do it on the CPU: loop over all N records every frame, update them, and re-upload the whole array with writeBuffer:

// Per-frame CPU update — runs on the main thread, every frame.
function updateOnCPU(t) {
  for (let i = 0; i < count; i++) {
    const o = i * STRIDE;
    const ph = data[o+3];                  // each instance's phase
    data[o+0] = baseX[i] + Math.cos(t + ph) * 0.04;  // jitter x
    data[o+1] = baseY[i] + Math.sin(t + ph) * 0.04;  // jitter y
  }
  device.queue.writeBuffer(instBuf, 0, data);  // ← upload the WHOLE array
}

At 10k instances this is fine — the field breathes, the sprites swim, fps stays pinned at 60. But watch the badge: it now reports a non-zero CPU upload cost in milliseconds. That number is the seed of the wall. The GPU is barely working; the time is going into that JS loop and the megabyte-scale copy across the CPU→GPU boundary, every frame.

Stage 6 — 100k, and the wall appears

Drag the count slider up. Drawing is still cheap — 100k soft quads is nothing for a modern GPU. But the per-frame CPU work scales linearly with the count: at 100k that JS loop runs a hundred thousand times and re-uploads ~3 MB per frame. The badge's CPU-upload number climbs, and eventually the frame budget (16.6 ms for 60fps) is eaten alive — not by the GPU, but by the CPU preparing work for it. Push it until fps drops and read the wall in the HUD.

The GPU draws 100k quads in well under a millisecond. The CPU rewriting their positions every frame is what falls over. That asymmetry — cheap to draw, expensive to feed from the CPU — is the entire reason compute shaders exist.

The buffer, the bind group, and the one draw call

Four pieces wire it together. First, the storage buffer — note the usage flags: STORAGE because the shader reads it as a storage array, and COPY_DST because writeBuffer copies into it:

// Allocate big enough for the max count we allow.
const instBuf = device.createBuffer({
  size:  MAX_COUNT * STRIDE * 4,            // floats → bytes
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(instBuf, 0, data);    // initial upload (once)

Second, the pipeline. It compiles the WGSL once and pins the two entry points. layout: 'auto' is the easy button: WebGPU reads the shader and derives the bind-group layout — including the fact that binding 1 is a vertex-stage storage buffer — so you never spell out visibility by hand. The fragment target carries premultiplied-alpha blending so overlapping soft sprites add up into a glow instead of clobbering each other:

const module = device.createShaderModule({ code: WGSL });
const pipeline = device.createRenderPipeline({
  layout: 'auto',                                // infer layout from the shader
  vertex:   { module, entryPoint: 'vs' },
  fragment: { module, entryPoint: 'fs', targets: [{
    format,
    blend: {
      color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
      alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
    },
  }] },
  primitive: { topology: 'triangle-list' },
});

Third, the bind group. The uniform (aspect, zoom, time) sits at binding 0; the storage array at binding 1. Crucially, the layout must make the storage buffer visible to the vertex stage — we read it in vs, not fs. With layout: 'auto' WebGPU infers this from the shader, but if you write an explicit layout you must say GPUShaderStage.VERTEX:

const bind = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [
    { binding: 0, resource: { buffer: ubo     } },   // uniform
    { binding: 1, resource: { buffer: instBuf } },   // storage array
  ],
});

Finally — the punchline of the whole episode — the draw. Six vertices, count instances. One call. That single line is what replaces a hundred thousand draws:

const pass = enc.beginRenderPass({ /* … */ });
pass.setPipeline(pipeline);
pass.setBindGroup(0, bind);
pass.draw(6, count);                 // ← 6 verts × N instances, ONE call
pass.end();

Why the CPU update is the bottleneck

Stage 5's updateOnCPU looks innocent, but it does two expensive things per frame, both scaling with N. The JS loop touches every record on a single thread. Then writeBuffer hands the entire Float32Array to the driver, which copies it across the PCIe bus into GPU memory. At 100k × 32 bytes that's ~3 MB of traffic per frame, 60 times a second — ~190 MB/s of pure overhead, all to move data the GPU could have computed itself, in place, in parallel, without ever leaving its own memory.

That's the cliff, and it's deliberate. We built the slow path so you can feel it. Episode 06 keeps the exact same instance buffer and the exact same one-line draw — but deletes updateOnCPU entirely and replaces it with a compute shader that updates all N records on the GPU in one dispatch. Same field, same 100k, but the frame time flattens out because nothing crosses the bus anymore.

Common pitfalls

  • Storage buffer not visible to the vertex stage. We read insts[ii] in vs. If you hand-write a bind-group layout and forget visibility: GPUShaderStage.VERTEX on that entry, pipeline or bind-group creation throws. layout: 'auto' avoids this by reading the shader — prefer it until you need explicit layouts.
  • Instance vs. vertex index confusion. @builtin(vertex_index) is which corner (0…5); instance_index is which copy (0…N-1). Swap them and you'll index the instance array with 0…5 and draw six overlapping quads at the first six records. If everything piles up in one spot, check this first.
  • Struct alignment / stride mismatch. A WGSL vec4f aligns to 16 bytes; a vec2f to 8. Our struct (vec2f, f32, f32, vec4f) happens to pack tightly into 32 bytes with the vec4 landing at offset 16 — but if you add a stray f32 or reorder fields, the GPU's stride won't match your JS layout and every instance reads its neighbor's bytes. When in doubt, pad to a multiple of 16 and lay vec4s on 16-byte boundaries. Verify by checking that your JS STRIDE × 4 equals the WGSL struct's reported size.
  • Updating a 100k buffer on the CPU every frame. This is the headline pitfall — and we did it on purpose. It's fine for a few thousand static-ish instances; it's a wall at 100k animated. The fix isn't a faster loop, it's not looping on the CPU at all. That's compute (Ep06).
  • maxStorageBufferBindingSize ceiling. Adapters cap how large a single bound storage buffer can be — commonly 128 MB, sometimes less. At 32 bytes/instance that's ~4M instances, but don't assume; read adapter.limits.maxStorageBufferBindingSize and clamp your max count to it. Allocating past the limit fails buffer creation.

Exercises

  1. Per-instance rotation. Add a rot: f32 to the struct (mind the stride — you'll want to pad back to a 16-byte multiple), seed a random angle per instance, and rotate corner by it in the vertex shader with a 2×2 rotation before scaling. Spin them slowly by adding u.time to the angle.
  2. Color by position. Instead of reading inst.color, compute color in the vertex shader from inst.pos — e.g. hue from atan2(pos.y, pos.x) and brightness from length(pos). Now the field's palette is a map of where things are, and you can drop the color fields from the buffer entirely (smaller stride, less upload).
  3. Find the wall. On Stage 6, turn off animate and push the count to max — fps holds, because the buffer never re-uploads. Turn animate back on and raise the count until fps drops below 60. Read the CPU-upload number in the badge at the breaking point. That millisecond figure is your CPU's per-frame budget for this work — and the number Episode 06 sends to near-zero.

What's next

Episode 06 — Hello, Compute. We keep this exact scene — same instance buffer, same one-line draw(6, N) — but hand the per-frame update to the GPU. A compute shader walks all N records in parallel and writes them in place, so the data never crosses back to the CPU. You'll watch the wall you just found in Stage 6 simply… not be there anymore. That CPU↔GPU difference, felt directly, is the moment WebGPU stops being "WebGL with new syntax" and becomes a parallel computer you happen to draw with.