WebGPU From Zero · Episode 02
The Render Pipeline
The Render Pipeline is Episode 02 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Every single frame WebGPU ever draws flows through one object: the
render pipeline. It's the part most tutorials wave their hands at — a
big createRenderPipeline({...}) blob you copy and never look at again. We're
going to look at it. By the end of this page you'll know what every field is for, because
you'll have built one up field by field, from a bare triangle to a spinning, color-bleeding
polygon — all from vertex data you upload.
The pipeline is where it all gets tied together: your shaders (the two
programs that run on the GPU), the layout of the vertex bytes you hand it,
the primitive state (triangles? lines? which way is "front"?), and the
targets it writes pixels into. Once that object exists, drawing is almost
anticlimactic: open a render pass, point it at the pipeline, bind your buffers, and say
draw. Step through the six stages below and watch a triangle become a machine.
drag the sliders · switch stages · toggle wireframe
What you're looking at
One canvas, one pipeline family, six visibly different states of the same machine. In
Stage 1 there is a single flat triangle — three positions, no color logic at all, the
minimum thing a GPU can rasterize. By Stage 6 the same code path is drawing an N-sided
polygon you build in JavaScript, spinning, scaling, every vertex carrying its own color
that the hardware smears smoothly across each face. Nothing here is a library. The 2D
rotation is a mat2 we type out by hand; the polygon is a for loop;
the colors are bytes we pack into a buffer.
The whole thing hangs off a mental model worth burning in now — the path from your data to a pixel:
The pipeline sits dead center. It is the contract: "vertices arrive in this byte layout, run through these shaders, get assembled as triangles, and land in a target of this format." Get the contract right once and every frame is cheap. Get one field wrong and you get a validation error or a black screen — which is exactly the stuff we'll teach you to read.
Stage 1 — One triangle from a vertex buffer
Episode 01 cheated: it drew a fullscreen triangle whose three corners were hard-coded inside the vertex shader, so there was no vertex buffer at all. That's a great trick for fullscreen effects, but it's not how you draw geometry. Real meshes live in a vertex buffer: a flat array of bytes on the GPU that the pipeline reads one vertex at a time.
So our first real step is to put three 2D positions into a Float32Array,
copy them to a GPUBuffer, and — crucially — describe their layout to
the pipeline so it knows how to slice the bytes back into vertices:
// Three corners of a triangle, as (x, y) pairs in clip space (-1..1)
const verts = new Float32Array([
0.0, 0.6, // top
-0.6, -0.5, // bottom-left
0.6, -0.5, // bottom-right
]);
const vbuf = device.createBuffer({
size: verts.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, // used as a vertex source AND written to
});
device.queue.writeBuffer(vbuf, 0, verts);
// Tell the pipeline how to read those bytes back into a vertex:
const vbLayout = {
arrayStride: 2 * 4, // 2 floats × 4 bytes = 8 bytes per vertex
attributes: [{
shaderLocation: 0, // matches @location(0) in the WGSL
offset: 0, // position starts at byte 0 of each vertex
format: 'float32x2', // it's a vec2<f32>
}],
};
Three numbers do all the work here. arrayStride is how many bytes one whole
vertex occupies — the GPU adds this to its read cursor after each vertex. offset
is where, inside that stride, this particular attribute begins. format
says how to interpret the bytes (float32x2 = two 32-bit floats = a
vec2f). If any of these disagrees with reality, you read garbage — the first
of our pitfalls below.
The shaders for this stage are the smallest pair that can exist. The vertex shader takes
the position at @location(0) and passes it straight through to clip space; the
fragment shader paints every pixel one flat color:
// WGSL — Stage 1: positions in, one flat color out
@vertex
fn vs(@location(0) pos: vec2f) -> @builtin(position) vec4f {
return vec4f(pos, 0.0, 1.0); // (x, y, z=0, w=1)
}
@fragment
fn fs() -> @location(0) vec4f {
return vec4f(0.22, 0.74, 0.97, 1.0); // flat sky-blue
}
Notice @location(0) in the shader and shaderLocation: 0 in the
layout are the same wire. That correspondence is the heart of how vertex data gets
into a shader — and the most common thing people mismatch.
Stage 2 — Vertex colors, and free hardware interpolation
A flat triangle is boring because every vertex says the same thing. Let's give each corner a color and let the GPU do the most satisfying thing it does for free: interpolate. We add a second attribute. Now each vertex is position and color packed together, so the stride grows and the color attribute gets an offset past the position:
// Interleaved: x, y, r, g, b per vertex (5 floats = 20 bytes)
const verts = new Float32Array([
0.0, 0.6, 1, 0.2, 0.3, // top → red
-0.6, -0.5, 0.2, 1, 0.4, // left → green
0.6, -0.5, 0.3, 0.4, 1, // right → blue
]);
const vbLayout = {
arrayStride: 5 * 4, // 5 floats now → 20 bytes
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x2' }, // position
{ shaderLocation: 1, offset: 2 * 4, format: 'float32x3' }, // color, after the 2 floats
],
};
Both attributes live in one buffer, one after another — this is
interleaved layout, the common case. The color's offset is
8 because position eats the first 8 bytes of every 20-byte vertex. Now the
WGSL carries color from vertex to fragment using a small struct — the
canonical WebGPU pattern, a VSOut that bundles the required clip-space position
with anything else you want interpolated:
// WGSL — Stage 2: a VSOut struct carries color across the triangle's face
struct VSOut {
@builtin(position) clip: vec4f, // required: where the vertex lands
@location(0) color: vec3f, // anything extra → interpolated for free
};
@vertex
fn vs(@location(0) pos: vec2f, @location(1) col: vec3f) -> VSOut {
var out: VSOut;
out.clip = vec4f(pos, 0.0, 1.0);
out.color = col;
return out;
}
@fragment
fn fs(in: VSOut) -> @location(0) vec4f {
return vec4f(in.color, 1.0); // in.color is the BLEND of the 3 corners
}
You only set color at three vertices, but the fragment shader runs for every
pixel inside the triangle — and each one receives a smooth, perspective-correct blend of the
three corner colors. That's the rasterizer's interpolator, free silicon between the vertex
and fragment stages. The red-green-blue gradient triangle you see is the "hello world" of
this fact.
Stage 3 — A quad from two triangles, via an index buffer
GPUs only draw triangles. A square is two triangles sharing an edge — which means two of
the four corners get used twice. Instead of duplicating those vertices in the buffer, we
keep four unique vertices and add an index buffer: a list
of u16 integers that says "draw the triangle made of vertices 0, 1, 2, then the
one made of 2, 1, 3."
// 4 unique corners (pos + color), reused via indices
const verts = new Float32Array([
-0.6, -0.6, 1, 0.3, 0.3, // 0 BL
0.6, -0.6, 0.3, 1, 0.4, // 1 BR
-0.6, 0.6, 0.3, 0.5, 1, // 2 TL
0.6, 0.6, 1, 0.9, 0.3, // 3 TR
]);
// Two triangles. Winding is counter-clockwise (matches the default front face).
const idx = new Uint16Array([ 0, 1, 2, 2, 1, 3 ]);
const ibuf = device.createBuffer({
size: idx.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(ibuf, 0, idx);
Four vertices instead of six is a tiny saving here, but on a real mesh — where most
vertices are shared by many triangles — indexing roughly halves your vertex memory and lets
the GPU's post-transform cache skip re-running the vertex shader for vertices it just saw.
The buffer is marked INDEX in its usage, and when we draw we'll
call setIndexBuffer(ibuf, 'uint16') then drawIndexed(6). The
string 'uint16' must match the Uint16Array — mixing it up with
'uint32' is a classic, silent-ish bug (see pitfalls).
Stage 4 — Spin, with a hand-written rotation matrix in a uniform
Time to move. We want to rotate the shape every frame. The data per vertex never
changes, so the rotation belongs in a uniform buffer — one small blob the
shader reads once per vertex, the same for all of them. A 2D rotation is a 2×2
matrix, and we'll write the trig by hand because it's four lines and you should see it:
// Inline 2D rotation matrix — no math library, just sin/cos.
// A mat2 rotates a vector by angle a: [ c -s ]
// [ s c ]
function rot2(a) {
const c = Math.cos(a), s = Math.sin(a);
// WGSL/WebGPU store mat2x2 column-major: column0 = (c, s), column1 = (-s, c)
return [ c, s, -s, c ];
}
// A uniform buffer big enough for a mat2x2<f32>. NOTE the alignment trap:
// a mat2x2<f32> needs 8-byte column alignment, but uniform buffers round up
// to 16, so we pad the struct out to 16 bytes (4 floats) to be safe.
const ubo = device.createBuffer({
size: 16, // 4 floats, padded
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
// per frame:
const m = rot2(angle);
device.queue.writeBuffer(ubo, 0, new Float32Array([ m[0], m[1], 0, m[2], m[3], 0 ]));
That padding pattern (two floats of matrix column, then a float of pad, so each column
sits on a 16-byte-friendly slot) is the single most common source of "my uniform is full of
garbage" bugs in WebGPU — we'll restate it in pitfalls because it bites everyone once. The
shader binds the matrix at @group(0) @binding(0) and multiplies each position
by it:
// WGSL — Stage 4: rotate every vertex by a shared uniform matrix
struct Uniforms { rot: mat2x2f }; // matches the bind group below
@group(0) @binding(0) var<uniform> U: Uniforms;
@vertex
fn vs(@location(0) pos: vec2f, @location(1) col: vec3f) -> VSOut {
var out: VSOut;
out.clip = vec4f(U.rot * pos, 0.0, 1.0); // mat2 × vec2 = rotated vec2
out.color = col;
return out;
}
We also need a bind group to connect the JS buffer to that
@binding(0) slot — the same dance Episode 01 used for its time uniform:
const bind = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0), // group 0's auto layout
entries: [{ binding: 0, resource: { buffer: ubo } }],
});
Crank the spin speed slider. The shape pivots around the origin because rotation
is about (0,0) in clip space, and the center of our shapes is the origin. (Want
it to orbit instead? Rotate, then add an offset — try it in the exercises.)
Stage 5 — Morph and scale: sliders push uniforms
Uniforms aren't just for matrices. Anything the whole draw shares can live there. We
extend the struct with a scale and a tiny per-vertex wobble amount
driven by sliders, proving the loop: move a slider → write a uniform → the GPU redraws
differently next frame, with the vertex buffer never touched. The aspect ratio also
rides in here so the shape stays round on a 16:10 canvas instead of stretching:
// Pack everything the draw shares into one std140-friendly block.
// Layout (floats): rot.col0(2) pad(1) | rot.col1(2) pad(1) | scale aspect time wobble
const data = new Float32Array(12); // 12 floats = 48 bytes, 16-aligned
data.set([ m[0], m[1], 0 ], 0);
data.set([ m[2], m[3], 0 ], 3);
data[6] = scale;
data[7] = canvas.height / canvas.width; // squash x to keep it round
data[8] = time;
data[9] = wobble;
device.queue.writeBuffer(ubo, 0, data);
And the WGSL grows to match. A z-wobble on a 2D shape doesn't change depth
(we're flat), so we spend it as a gentle per-vertex radial pulse — enough to see a
uniform-driven deformation breathe:
struct Uniforms {
rot: mat2x2f, // 0..32 bytes (two 16-byte-aligned columns)
scale: f32, // 32
aspect: f32, // 36
time: f32, // 40
wobble: f32, // 44
};
@group(0) @binding(0) var<uniform> U: Uniforms;
@vertex
fn vs(@location(0) pos: vec2f, @location(1) col: vec3f) -> VSOut {
var p = pos * U.scale;
// per-vertex pulse: push each vertex along its own direction over time
let pulse = 1.0 + U.wobble * 0.25 * sin(U.time * 3.0 + pos.x * 6.0 + pos.y * 6.0);
p = U.rot * (p * pulse);
p.x = p.x * U.aspect; // aspect correction in clip space
var out: VSOut;
out.clip = vec4f(p, 0.0, 1.0);
out.color = col;
return out;
}
Stage 6 — An N-gon generated in JavaScript
The payoff: nothing about the pipeline cares how many vertices you feed it. So we generate a polygon in a loop — a center vertex plus N rim vertices — and stitch it into a triangle fan with an index buffer. Drag the sides slider from 3 to 24 and watch a triangle smoothly become a near-circle, all through the exact same pipeline:
// Build an N-gon as a triangle fan: 1 center + N rim vertices.
function makePolygon(n) {
const v = [ 0, 0, 1, 1, 1 ]; // center: white
for (let i = 0; i <= n; i++) { // <= n: repeat the first rim vert to close the fan
const a = (i / n) * Math.PI * 2;
const x = Math.cos(a) * 0.7, y = Math.sin(a) * 0.7;
// rainbow around the rim via a tiny HSV-ish wheel
const r = 0.5 + 0.5 * Math.cos(a);
const g = 0.5 + 0.5 * Math.cos(a - 2.094);
const b = 0.5 + 0.5 * Math.cos(a + 2.094);
v.push(x, y, r, g, b);
}
const idx = [];
for (let i = 1; i <= n; i++) idx.push(0, i, i + 1); // fan: center, rim[i], rim[i+1]
return { verts: new Float32Array(v), idx: new Uint16Array(idx) };
}
That's it. The shaders, the pipeline, the render pass — untouched. Only the contents of two buffers and the index count change. This is the lesson of the whole episode in one function: the pipeline is a fixed machine; geometry is just data you pour through it.
createRenderPipeline, every field annotated
Here's the object that ties all of the above together, with a comment on every line that mattered today. This is the version used from Stage 2 onward (position + color, indexed, one uniform):
const module = device.createShaderModule({ code: WGSL });
const pipeline = device.createRenderPipeline({
// layout 'auto' derives bind-group layouts from the WGSL. Fine until you
// share layouts across pipelines — then build a real GPUPipelineLayout.
layout: 'auto',
vertex: {
module,
entryPoint: 'vs', // the @vertex fn to run
buffers: [ vbLayout ], // ← the GPUVertexBufferLayout from above
},
fragment: {
module,
entryPoint: 'fs', // the @fragment fn
targets: [{ format }], // must match the canvas's preferred format
},
primitive: {
topology: 'triangle-list', // 3 indices = 1 triangle (vs strip / line / point)
cullMode: 'none', // 'back' to drop back-facing tris; 'none' = draw both
frontFace: 'ccw', // counter-clockwise = front (the default)
},
// no depthStencil here — we're 2D and never test depth. Add it for 3D (Ep 04).
});
Four blocks, and you now know all four. vertex names the vertex program
and the byte layout it expects. fragment names the pixel program and the
target format it writes. primitive decides how vertices clump into shapes
and which faces survive. layout wires up uniforms. For the wireframe toggle
in the demo we simply build a second pipeline with
topology: 'line-list' (and a matching line-list index buffer) — same shaders,
different primitive. That's how cheap it is to change the machine's behavior once you see it
as a set of fields.
The render pass that drives it
With the pipeline built and buffers filled, a frame is short. Open an encoder, begin a render pass that clears to a background color, set the pipeline, set the vertex and index buffers, bind the uniform, and draw:
function frame() {
// update the uniform for this frame (rotation, scale, time…)
device.queue.writeBuffer(ubo, 0, uniformData);
const enc = device.createCommandEncoder();
const pass = enc.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
clearValue: { r: 0.03, g: 0.04, b: 0.07, a: 1 },
loadOp: 'clear', // wipe to clearValue before drawing
storeOp: 'store', // keep the result (vs 'discard')
}],
});
pass.setPipeline(pipeline);
pass.setBindGroup(0, bind); // group 0 → the uniform
pass.setVertexBuffer(0, vbuf); // slot 0 → positions+colors
pass.setIndexBuffer(ibuf, 'uint16'); // u16 indices — must match the array!
pass.drawIndexed(indexCount); // or pass.draw(vertexCount) when un-indexed
pass.end();
device.queue.submit([ enc.finish() ]); // hand the command buffer to the GPU
requestAnimationFrame(frame);
}
The order matters: setPipeline first, then bind groups and buffers, then
draw. Forgetting setVertexBuffer before a draw is the rookie crash
— the slot is empty and WebGPU validates it away. And note Stage 1, which has no index
buffer, calls plain draw(3) instead of drawIndexed; the rest of
the stages are indexed.
Common pitfalls
- Stride / offset don't match the data. If
arrayStrideisn't the real byte size of one vertex, or an attribute'soffsetis wrong, the GPU reads color bytes as position (and vice versa). Symptom: a smeared, jittering, or off-screen mess. Count your floats × 4 and make the layout say exactly that. @locationin WGSL ≠shaderLocationin the layout. These integers are the wires connecting buffer attributes to shader inputs. If color is@location(1)in the shader butshaderLocation: 2in the layout, the input is unfed. Keep them in lockstep.- Index format mismatch. A
Uint16ArrayneedssetIndexBuffer(buf, 'uint16'); aUint32Arrayneeds'uint32'. Pickuint16for ≤ 65,535 vertices (half the memory),uint32above that. Cross them and triangles knit themselves wrong. - Winding vs cullMode. With
cullMode: 'back'andfrontFace: 'ccw', a triangle whose indices wind clockwise faces away and vanishes. If geometry disappears the moment you enable culling, flip the index order — or setcullMode: 'none'while you debug, as this demo does. - Uniform alignment. A
mat2x2fwants 8-byte columns but uniform structs follow 16-byte rules; a barevec3faligns to 16 too. Pad explicitly (we add a float after each matrix column) or your shader reads shifted garbage. When in doubt, lay fields out invec4-sized slots. - Forgetting
setVertexBufferbeforedraw. The pipeline declares it expects a buffer in slot 0; if you never set it, the draw is invalid and WebGPU rejects the pass. Same forsetIndexBufferbeforedrawIndexed.
Exercises
- Add a real per-vertex z-wobble. Give the vertex a third position
component, write
out.clip.zfrom a time-drivensin(), add adepthStencilto the pipeline and a depth texture to the pass, and watch parts of the shape pass in front of others. (This is the bridge to 3D in Episode 04.) - Switch to
line-listtopology for a true wireframe. Build an index buffer of edge pairs (for the N-gon: center→rim spokes plus rim→rim segments) and a second pipeline withtopology: 'line-list'. Compare it to the cheap wireframe toggle already in the demo — which edges does each one show? - Pulse the scale with time. In the frame loop, set the uniform
scaleto0.7 + 0.2 * Math.sin(t)and remove the slider's hold on it. The shape breathes — and you've confirmed that any uniform can be animated from JS without re-uploading a single vertex.
What's next
Episode 03 — WGSL, the language. We've been treating the shaders as
small black boxes: vec2f in, color out. Next we open the box and live inside
it — types and the no-implicit-cast rule, built-in functions, control flow, structs, and
the vertex/fragment split — in a little pattern playground where you edit fragment WGSL and
watch the pixels change instantly. The pipeline was the skeleton; WGSL is the muscle.