WebGPU From Zero · Episode 12
Textures, Mipmaps & Reflections
Textures, Mipmaps & Reflections is Episode 12 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Slap a texture on a plane and tilt it away from the camera, and the far end
boils — a shimmering mess of aliasing as a thousand texels fight for a
single pixel. The fix is one of the oldest tricks in real-time graphics:
mipmaps, a pre-shrunk pyramid of the texture so the GPU can read a
level that already matches the pixel size. WebGPU, unlike WebGL, gives you
no generateMipmap — you build that pyramid yourself. Today we
do exactly that, and the far plane snaps from a shimmering haze to glass-crisp.
Then we go further than flat surfaces. We build a cube map — a procedural sky the camera sits inside — and hang a chrome sphere in the middle of it that reflects its surroundings, sampled by the reflected view vector. Six stages, one machine: a textured plane with no mips, the downsample chain that builds the pyramid, crisp mipmapped sampling, anisotropic filtering at grazing angles, the skybox, and finally the mirror sphere. By the end you'll know textures done right — and have a reflective object floating in a sky you generated from a handful of numbers.
What you're looking at
Every stage draws the same scene — a textured ground plane stretching to the
horizon, sometimes a skybox, sometimes a sphere — but each one flips a single switch
in the texturing pipeline so you can feel what that switch does. Stage 1 is
the disease (aliasing); stages 2–4 are the cure (mipmaps and anisotropy); stages 5–6
are the reward (a cube map and a mirror). The mipmaps and
anisotropy checkboxes let you A/B the sampler live on the plane stages;
the reflectivity slider blends the chrome sphere between matte and
mirror. Backend badge bottom-left, fps top-left.
There are no image files anywhere in this page. The checker texture is drawn pixel-by-pixel into a buffer in JavaScript, and the six faces of the sky are painted procedurally — a gradient, a sun, a horizon glow. WebGPU never touches the network.
Stage 1 — A textured plane, no mipmaps
We lay a checkerboard texture on a plane and tilt the camera so it recedes toward a vanishing point. Up close it's fine. Far away — where dozens of black-and-white texels collapse into one screen pixel — it turns into a writhing moiré of noise that crawls as the camera moves. This is minification aliasing: the GPU is point-sampling (or bilinear-sampling) a texture far denser than the pixel grid, so which texel "wins" flickers frame to frame.
Bilinear filtering can't save you here. It blends the four nearest texels, but when one pixel covers sixty texels, four of them is a random sample. We need the texture pre-averaged down to roughly the pixel's footprint. That pre-averaged pyramid is a mipmap.
Stage 2 — Build the mip chain (the downsample pyramid)
A mipmap is the same image stored at every halving: full size, half, quarter, eighth… down to a single pixel. The count is fixed:
mipLevelCount = floor(log2(max(width, height))) + 1
A 512×512 texture has floor(log2(512)) + 1 = 10 levels (512, 256, …,
1). WebGL gave you gl.generateMipmap() to fill them. WebGPU has
no such call. You allocate the texture with the right
mipLevelCount, upload level 0, then generate levels 1…N yourself by
repeatedly downsampling — each level rendered (or computed) from the one above. This
stage visualizes that pyramid: it tiles levels 0, 1, 2, 3… across the plane
so you can watch the texture get blurrier and tinier at each step. Those blurry small
levels are exactly what the far plane will sample in Stage 3.
Stage 3 — Mipmapped sampling (crisp at any distance)
Now we point the sampler at the pyramid. We set mipmapFilter: 'linear'
so the GPU picks the right level for each pixel's footprint — and blends between two
adjacent levels (trilinear) so there's no visible seam where it switches. The far
plane that boiled in Stage 1 is now calm. The checker fades smoothly to grey
at the horizon instead of strobing, because at that distance the GPU is reading a
level that's already been averaged to grey. Toggle mipmaps off and the
shimmer comes roaring back — that's the whole episode in one checkbox.
Stage 4 — Anisotropic filtering (sharper at grazing angles)
Mipmaps fix shimmer but introduce a new compromise: at a grazing angle a
pixel's footprint is a long thin ellipse — wide across the texture but narrow along
it. Plain mipmapping picks one square level for the whole footprint, so it over-blurs
along the short axis. The result is a road that goes mushy in the distance.
Anisotropic filtering takes several samples along the long axis of
that ellipse and averages them, recovering detail the isotropic mip would have smeared
away. You ask for it with one sampler field: maxAnisotropy: 16. Toggle
anisotropy on at a shallow camera angle and the distant checker tightens
up noticeably.
Stage 5 — A cube map (a procedural sky)
A cube map is six square textures arranged as the inside faces of
a box: +X, −X, +Y, −Y, +Z, −Z. You sample it not with a 2D UV but with a 3D
direction vector — the GPU figures out which face that ray hits and where.
That's perfect for a sky: render a cube around the camera, and in the fragment shader
sample the cube map by the direction from the camera through each pixel. We paint all
six faces procedurally — a blue-to-white vertical gradient, a warm horizon band, and a
bright sun disc on one face — and upload them as the six layers of a
cube-dimension texture. The camera sits inside, auto-rotating, and you're
surrounded by a sky that's nothing but math.
Stage 6 — Environment reflection (a chrome sphere)
Here's the payoff. We put a sphere in the middle of the sky and make it a perfect
mirror. For each pixel on the sphere we have a world-space surface
normal and the view direction from the camera. The
reflected ray is reflect(viewDir, normal) — and we sample the cube map by
that direction. Suddenly the sphere shows the sky bent around it: the sun
sweeps across its surface as it rotates, the horizon wraps its equator. Drag the
reflectivity slider down and it fades from chrome to a dull grey ball;
push it up and it's a flawless mirror of its surroundings. This is environment mapping,
the technique behind every chrome teapot and car-paint shader you've ever seen.
The code — creating a texture with mip levels
The base texture is drawn in JS (a checkerboard) and uploaded to level 0. The key
is allocating all the mip levels up front and adding the
RENDER_ATTACHMENT usage — because we'll render into the smaller
levels to generate them:
// floor(log2(max(w,h))) + 1 — the only correct mip count
function mipCount(w, h) { return 1 + Math.floor(Math.log2(Math.max(w, h))); }
const tex = device.createTexture({
size: [W, H],
format: 'rgba8unorm',
mipLevelCount: mipCount(W, H),
usage: GPUTextureUsage.TEXTURE_BINDING // sampled in shaders
| GPUTextureUsage.COPY_DST // receives the base upload
| GPUTextureUsage.RENDER_ATTACHMENT, // we render into smaller levels
});
// upload the base image (level 0) from a JS Uint8Array of RGBA bytes
device.queue.writeTexture(
{ texture: tex, mipLevel: 0 },
basePixels, // Uint8Array, W*H*4 bytes
{ bytesPerRow: W * 4, rowsPerImage: H },
{ width: W, height: H },
);
The code — generating the mip chain (downsample passes)
No generateMipmap means we loop over the levels and render each one
from its parent with a fullscreen pass that samples the bigger level with linear
filtering. The render target is a view of a single mip level
(baseMipLevel: i); the bind group samples the previous level
(baseMipLevel: i - 1). A linear sampler does the 2×2 box average for us:
// a pipeline whose fragment shader just samples the source and writes it out
const blit = device.createRenderPipeline({
layout: 'auto',
vertex: { module: blitMod, entryPoint: 'vs' },
fragment: { module: blitMod, entryPoint: 'fs', targets: [{ format: 'rgba8unorm' }] },
primitive:{ topology: 'triangle-list' },
});
const linear = device.createSampler({ magFilter: 'linear', minFilter: 'linear' });
const enc = device.createCommandEncoder();
for (let i = 1; i < mipLevelCount; i++) {
const src = tex.createView({ baseMipLevel: i - 1, mipLevelCount: 1 });
const dst = tex.createView({ baseMipLevel: i, mipLevelCount: 1 });
const bind = device.createBindGroup({ layout: blit.getBindGroupLayout(0),
entries: [{ binding: 0, resource: linear }, { binding: 1, resource: src }] });
const pass = enc.beginRenderPass({ colorAttachments: [{
view: dst, loadOp: 'clear', storeOp: 'store', clearValue: { r:0,g:0,b:0,a:1 } }] });
pass.setPipeline(blit); pass.setBindGroup(0, bind);
pass.draw(3); // fullscreen triangle; the linear sampler box-filters 2x2
pass.end();
}
device.queue.submit([enc.finish()]);
Each iteration depends on the previous level being finished, but they're recorded
into one encoder and run in order — level 1 is done before level 2 reads it. The blit
shader is trivial: a fullscreen triangle and a single textureSample.
The code — the sampler (mip filter + anisotropy)
The sampler is where mipmaps and anisotropy actually turn on. mipmapFilter:
'linear' blends between mip levels (trilinear); maxAnisotropy asks
the hardware for up to N taps along the footprint's long axis. Note: anisotropy is a
hint — drivers clamp it to what they support, and only when min/mag/mipmap are
all linear:
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
mipmapFilter: useMips ? 'linear' : 'nearest', // 'nearest' = pin to level 0
addressModeU: 'repeat',
addressModeV: 'repeat',
maxAnisotropy: useAniso ? 16 : 1, // driver clamps to its max (often 16)
});
To disable mipmaps without rebuilding the texture, we keep two samplers and
swap the bind group — or, as a teaching trick, set mipmapFilter:'nearest'
and clamp the LOD to 0. In WGSL you can also force a level with
textureSampleLevel(tex, smp, uv, 0.0), which is how the "no mips" stage
pins sampling to the full-resolution level.
The code — the cube map (six procedural faces)
A cube map is a 2D texture with six array layers and
dimension implied by a cube view. We paint each face
into its own Uint8Array and write it to the matching layer
(origin: [0, 0, face]). Layer order is fixed by the spec: 0=+X,
1=−X, 2=+Y, 3=−Y, 4=+Z, 5=−Z:
const sky = device.createTexture({
size: [FACE, FACE, 6], // width, height, 6 layers
format: 'rgba8unorm',
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
});
for (let face = 0; face < 6; face++) {
const px = paintSkyFace(face, FACE); // gradient + horizon + sun → Uint8Array
device.queue.writeTexture(
{ texture: sky, origin: [0, 0, face] },
px, { bytesPerRow: FACE * 4, rowsPerImage: FACE },
{ width: FACE, height: FACE });
}
// the magic is the VIEW: dimension 'cube' lets WGSL sample by a vec3 direction
const skyView = sky.createView({ dimension: 'cube' });
In WGSL the cube sampler is a distinct type — texture_cube<f32> —
and you sample it with a direction, not a UV.
The code — the reflection vector
The skybox shader samples the cube by the camera-to-pixel direction. The chrome sphere goes one step further: it reflects that direction off the surface normal. Both live in the same fragment shader, branching on whether we're drawing the box or the sphere:
// fragment shader (WGSL) — shared by skybox and chrome sphere
@group(0) @binding(1) var envSampler: sampler;
@group(0) @binding(2) var envTex: texture_cube<f32>;
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
// view direction: from the camera toward this world-space point
let viewDir = normalize(in.worldPos - u.camPos);
if (u.isSky > 0.5) {
// skybox: sample straight along the view ray
return textureSample(envTex, envSampler, viewDir);
}
// sphere: reflect the view ray about the world-space normal, sample THAT
let N = normalize(in.worldNormal);
let R = reflect(viewDir, N); // the mirror direction
let env = textureSample(envTex, envSampler, R).rgb;
let base = vec3f(0.18); // dull grey when not reflective
return vec4f(mix(base, env, u.reflectivity), 1.0);
}
Two things make or break this: the normal must be in world space (transform it by the model's rotation, not the full model-view-projection), and the view direction must use the real camera position, also in world space. Mix those spaces up and the reflection slides around as the camera moves instead of sticking to the surface.
Common pitfalls
- Reaching for
generateMipmap. It doesn't exist in WebGPU. There is no shortcut: you allocatemipLevelCountlevels and fill 1…N yourself with downsample passes (render or compute). Forgetting this gives you a texture with one level and no anti-aliasing benefit at all. - Wrong mip count. It's
floor(log2(max(w,h))) + 1— easy to off-by-one. Too few and the deepest levels are missing (the far surface still shimmers); too many and texture creation throws a validation error. Always size frommax(w,h), not width alone. - Missing
RENDER_ATTACHMENTusage. If you generate mips by rendering into the smaller levels, the texture must includeRENDER_ATTACHMENTin its usage flags — otherwise creating a render-pass view of a mip level fails validation. - Cube-map face order / orientation. The six layers are a fixed order (+X,−X,+Y,−Z…). Get the order wrong and the sky is scrambled; get a single face's up-vector wrong and one wall of the world is sideways or mirrored. Build a one-face-per-color debug sky first to confirm your orientation before painting anything pretty.
- Reflection in the wrong space.
reflect()needs the world-space normal and a world-space view direction. A common bug is using the view-space normal (so the reflection is glued to the camera) or forgetting to re-normalize the interpolated normal (so it shrinks and the reflection warps). - Anisotropy support varies.
maxAnisotropyis a hint; drivers clamp it (16 is common, some go to 2). It also requires linear min/mag/mipmap filtering — setmaxAnisotropy > 1with a nearest filter and it's either ignored or a validation error. Never assume a specific factor took effect.
Exercises
- Add a normal map. Generate a second procedural texture encoding surface bumps as RGB normals, sample it on the plane, and perturb the shading normal before lighting. Watch a flat plane grow texture under a moving light. (You'll want the tangent-space basics from Episode 10's lighting.)
- Roughness-based mip LOD for blurry reflections. Mip the cube map
too, then sample the sphere's reflection with
textureSampleLevel(env, smp, R, roughness * maxLOD). Add a roughness slider: at 0 it's a mirror, at 1 it's a soft satin sphere — a cheap stand-in for real prefiltered environment maps. - A procedural gradient sky. Replace the painted faces with a sky
computed entirely in the fragment shader from the view direction: a zenith-to-horizon
color ramp plus a soft sun where
dot(viewDir, sunDir)is high. No cube texture at all — and the reflection still works if you factor the sky into a function both the box and the sphere call.
What's next
Episode 13 — Post-Processing. We stop rendering straight to the screen and render into an offscreen texture instead, then run full-frame shader passes over it: bloom that makes that chrome sphere's sun-glint bleed, tone mapping, vignette, and a tiny FXAA. Once you can render to a texture and sample it back, the whole world of screen-space effects opens up — and it's the same render-to-texture muscle you just used to build the mip chain.