WebGPU From Zero · Episode 14

MSAA & Render Targets

MSAA & Render Targets is Episode 14 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 14 · WebGPU From Zero · Season 2

Here is the same spinning object, twice. On the left, every edge is a flight of jagged little stairs — and as it rotates, the stairs crawl, shimmering and reshuffling pixel by pixel. On the right, the exact same geometry, the exact same shader, the exact same frame — but the edges are razor-clean, smooth as a vector drawing. The difference between those two pictures is one number: a sample count of 1 versus 4.

That number turns on MSAA — multisample anti-aliasing — and it is the single highest impact-per-line change in all of real-time 3D. In this episode we build it from the metal: a multisampled color render target the GPU draws into at 4× coverage, a resolve step that averages those samples down into the swapchain, and a depth texture that must agree on the sample count or WebGPU refuses to run. Flip the toggle in the demo and watch the staircase vanish.

0 fps
spins on its own · flip sample count to feel it
WebGPU · 4× MSAA
sampleCount 1 — raw aliasing. Watch the edges crawl as it spins.

The object is a thin-spoked star prism: lots of long, near-diagonal silhouette edges, which is exactly where aliasing screams the loudest. The camera holds still; the object auto-rotates so the staircase is always in motion. Step through the six stages with the stage dropdown — each one maps to a heading below.

What you're looking at

Every stage renders the same star prism with the same pipeline. What changes is the plumbing behind the final pixel:

  • Stages 1–2 swap the sample count on the render target and the pipeline so you can see jagged versus smooth back to back.
  • Stage 3 is the payoff: the multisampled target is resolved into the canvas, which is the step that actually produces the clean image you see on screen.
  • Stage 4 proves the depth texture has to match: it draws an intersecting blade so depth testing matters, with a 4× depth buffer behind it.
  • Stage 5 is the trade-off view — toggle samples between 1 and 4 and watch the fps counter move.
  • Stage 6 turns on split view: aliased on the left half, antialiased on the right, divided by a hard seam down the middle.

Why edges are jagged — the sampling problem

A triangle's edge is a perfectly straight mathematical line, but a pixel is a little square with one location at its center. The rasterizer asks a yes/no question for each pixel: is my center inside the triangle? One sample, one answer. A pixel the edge slices through is either fully the triangle's color or fully the background — there is no "60% covered." String those binary decisions along a diagonal and you get a staircase. Rotate the object and the staircase reshuffles every frame: that crawling shimmer is temporal aliasing, and it is the most distracting artifact in real-time rendering.

The fix is conceptually trivial: ask the coverage question more than once per pixel, at several sub-pixel locations, then average the answers. A pixel where 2 of 4 sample points land inside the triangle becomes a 50% blend of edge color and background. The staircase dissolves into a smooth gradient. That is multisampling, and the GPU has dedicated hardware for it — you just have to ask.

1 sample / pixel 4 samples / pixel (MSAA) ┌───┬───┬───┐ ┌───┬───┬───┐ │ ■ │ ■ │ │ edge → │ ■ │ ■ │ ▓ │ ▓ = partial coverage ├───┼───┼───┤ hard ├───┼───┼───┤ (averaged → smooth) │ ■ │ │ │ on/off │ ■ │ ▓ │ · │ └───┴───┴───┘ └───┴───┴───┘ staircase anti-aliased ramp

Stage 1 — Jagged (sampleCount 1)

This is the baseline: a normal single-sampled pipeline drawing straight into the swapchain texture. The render pass has one colorAttachment whose view is context.getCurrentTexture().createView() — exactly the pipeline from Episodes 09–13. The pipeline's multisample.count is 1 (the default). Lean in: every silhouette edge is a hard staircase, and as the prism spins the steps slide and pop. It runs fast and looks cheap. This is what "no anti-aliasing" looks like, and it is the thing every other stage is trying to kill.

Stage 2 — The multisampled color target

To anti-alias, the GPU needs somewhere to store the per-sample results, so it can average them later. The swapchain texture only has one sample per pixel, so we allocate a second texture that has four: a multisampled color target. It is the same size and format as the canvas, but with sampleCount: 4. The pipeline is told to match with multisample: { count: 4 }. At this stage we draw into that 4× target but don't resolve yet — internally the prism is being shaded at four sample points per pixel; what reaches the screen is the resolve we add next.

Stage 3 — Resolve → crisp edges

Here is the moment. You cannot show a multisampled texture on screen directly — the monitor wants one color per pixel, not four. So the color attachment gets a second field, resolveTarget, pointing at the swapchain view. When the render pass ends, the GPU resolves the 4-sample target into the 1-sample swapchain, averaging each pixel's samples in one fixed-function step that's effectively free. The view is the MSAA texture (where drawing happens); the resolveTarget is the canvas (where the averaged result lands). Flip to this stage and the crawling staircase collapses into clean, stable edges. Same geometry, same shader — one extra field.

Stage 4 — MSAA + depth (the counts MUST match)

The instant you have more than one opaque surface, you need a depth buffer (Episode 10) — and here is the rule that trips up everyone: the depth texture's sampleCount must equal the color target's. A 4× color target with a 1× depth texture is an immediate validation error; the pass won't even begin. The GPU runs the depth test per sample, not per pixel, so the depth attachment has to carry four samples too. This stage adds an intersecting blade through the prism so depth sorting visibly matters, with a depth texture created at sampleCount: 4. The seam where the two solids cross is anti-aliased right along with the silhouette.

Stage 5 — Cost vs quality

MSAA is not free, it's just cheap. The fragment shader still runs roughly once per covered pixel (that's the trick that makes MSAA far cheaper than rendering at 4× resolution), but coverage, depth, and the resolve all cost bandwidth and memory that scale with the sample count. Toggle samples between 1 and 4 on this stage and watch the fps readout: on a simple scene like this the cost is tiny, but on a heavy one it's real. 4× is the universal sweet spot. 8× exists and sharpens edges a touch more, but the returns fall off a cliff — most engines ship 4× and spend the rest of the budget elsewhere. (Not every format or device supports 8×; query before you assume it.)

Stage 6 — Split view: aliased | antialiased

The closing argument. Turn on split view and the frame is cut down the middle: the left half is rendered single-sampled, the right half 4× MSAA, seamed together so your eye can A/B them in one glance. Same prism, same spin, same instant — the only difference is the sample count on each side. Once you've seen the seam, you can't unsee aliasing anywhere again. (Split view is also auto-enabled when you pick this stage from the dropdown.)

The code that matters

Four pieces carry the whole episode. First, the pipeline's multisample state — this is what tells the GPU to shade at four sample points and produce a target it can resolve:

// (a) Pipeline multisample state — count must match the color target
const pipeline = device.createRenderPipeline({
  layout: 'auto',
  vertex:   { module, entryPoint: 'vs', buffers: [vbLayout] },
  fragment: { module, entryPoint: 'fs', targets: [{ format }] },
  primitive: { topology: 'triangle-list', cullMode: 'none' },
  depthStencil: { format: 'depth24plus', depthWriteEnabled: true, depthCompare: 'less' },
  multisample: { count: sampleCount },   // 1 = off, 4 = MSAA
});

Second, the multisampled color texture and the render pass that uses it. The MSAA texture is the view we draw into; the swapchain view becomes the resolveTarget. When count === 1 we skip the MSAA texture and draw straight to the canvas (you can't resolve a single-sample target):

// (b) Multisampled color target + render pass with a resolveTarget
const msaaColor = device.createTexture({
  size: [canvas.width, canvas.height],
  format,                              // same format as the swapchain
  sampleCount: 4,
  usage: GPUTextureUsage.RENDER_ATTACHMENT,
});

const swapView = context.getCurrentTexture().createView();
const colorAttachment = sampleCount === 4
  ? { view: msaaColor.createView(), resolveTarget: swapView,   // draw 4×, resolve to canvas
      clearValue: { r:0.03, g:0.04, b:0.07, a:1 }, loadOp: 'clear', storeOp: 'store' }
  : { view: swapView,                                            // count 1: straight to canvas
      clearValue: { r:0.03, g:0.04, b:0.07, a:1 }, loadOp: 'clear', storeOp: 'store' };
With storeOp:'store' on a resolved pass you'd also write the fat 4× target back to memory — usually wasteful. If you only need the resolved image, set storeOp:'discard' on the MSAA attachment: keep the resolve, drop the multisampled copy. The demo uses store for clarity.

Third, the multisampled depth texture. Its sampleCount is not optional decoration — it must be identical to the color target's, or pipeline and pass validation fail:

// (c) Depth texture — sampleCount MUST equal the color sampleCount
const depthTex = device.createTexture({
  size: [canvas.width, canvas.height],
  format: 'depth24plus',
  sampleCount: sampleCount,             // 4 here ⇒ depth tested per-sample
  usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
// ...passed as the pass's depthStencilAttachment.view
// A 4× color target + a 1× depth texture = validation error. They are a matched pair.

Fourth, the 1-vs-4 switch. There is no way to "turn MSAA on" at draw time — the sample count is baked into both the pipeline and the textures. Changing it means rebuilding all three. The same teardown runs on resize, because the targets must track the canvas size:

// (d) Switching sample count (or resizing) = recreate pipeline + targets
function rebuild(count) {
  sampleCount = count;
  msaaColor?.destroy(); depthTex?.destroy();   // free the old GPU memory
  depthTex = device.createTexture({ /* ...sampleCount: count... */ });
  msaaColor = count === 4
    ? device.createTexture({ /* ...sampleCount: 4... */ })
    : null;                              // no MSAA texture when count is 1
  pipeline = device.createRenderPipeline({ /* ...multisample:{count}... */ });
}
samplesSelect.addEventListener('change', () => rebuild(+samplesSelect.value));
// on resize: reconfigure the context, then rebuild(sampleCount) to resize targets

The WGSL never changes between 1× and 4×. MSAA is a property of the render target, not the shader — the fragment shader writes one color and the hardware handles coverage. (The one exception, @interpolate sampling mode, is in the exercises.)

Common pitfalls

  • Depth sampleCount must equal color sampleCount. The most common MSAA error, full stop. multisample.count on the pipeline, the color target's sampleCount, and the depth texture's sampleCount are one matched number. Any mismatch throws a validation error before a single pixel draws.
  • You cannot sample or blit a multisampled texture directly. An MSAA texture can't be a TEXTURE_BINDING you read in a shader and it can't be the source of a copy. Resolve it first (into a normal 1-sample texture), then sample that. Trying to bind a 4× texture to a regular texture_2d<f32> is an error — multisampled textures need texture_multisampled_2d and explicit per-sample loads, which is rarely what you want.
  • resolveTarget is required to present. If your color attachment's view is the MSAA texture and you forget resolveTarget, nothing reaches the swapchain — you get a black or stale canvas. The resolve is how the image gets onto the screen.
  • Cost scales with sample count. 4× quadruples the color and depth memory and the coverage/resolve bandwidth (the fragment shader cost stays roughly 1×). It's cheap, not free — budget it, and don't reach for 8× reflexively.
  • Recreate targets on resize and on count change. MSAA and depth textures are fixed-size; they don't auto-grow with the canvas. After any resize or a 1↔4 switch, destroy and recreate both (and the pipeline, since count is baked in), or you'll hit a size-mismatch error on the next pass.
  • Format must match the swapchain. The MSAA color target's format has to be the same as the canvas format (and the pipeline target), or the resolve is invalid. Use navigator.gpu.getPreferredCanvasFormat() for both.

Exercises

  1. Alpha-to-coverage. Add alphaToCoverageEnabled: true to the pipeline's multisample block and output a fractional alpha from the fragment shader (say, a soft circular cutout). The GPU converts that alpha into a coverage mask over the four samples — instant order-independent transparency on edges, perfect for foliage and chain-link, no blend state required. Compare it to plain alpha blending on the prism's edges.
  2. An FXAA post pass. Render single-sampled into an offscreen color texture (Episode 13's render-to-texture), then run a fullscreen pass that does FXAA — a cheap edge-detect-and-blur in the shader. Put it side by side with 4× MSAA. You'll feel the difference: MSAA nails geometry edges and stays crisp; FXAA also smooths shader/texture aliasing but softens the whole image. Real engines often run both.
  3. Centroid sampling. When MSAA is on, an interpolated varying is evaluated at the pixel center by default — which can fall outside the triangle on a partially covered edge pixel, producing extrapolated (sometimes wrong) values. Mark a varying @interpolate(perspective, centroid) in WGSL so it's sampled at the covered samples' centroid instead, and observe where it changes the shading along thin edges.

What's next

Episode 15 — Loading Real Geometry. We've been spinning procedural cubes, spheres, and star prisms for the whole season; now we load an actual model. We'll embed a tiny inline OBJ/glTF string in the page, write the parser that turns it into vertex and index buffers, and render real authored geometry — with our hard-won MSAA and depth already in place. Self-contained, no external file, no 404s, just a real mesh on screen.