WebGPU From Zero · Episode 10

Lighting & PBR in WGSL

Lighting & PBR in WGSL is Episode 10 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 10 · WebGPU From Zero · Season 2

Here is the trick that makes 3D look expensive: the same sphere can be polished gold, brushed steel, or a cheap matte plastic toy — and the only difference is two numbers. One says "how metal is this?" The other says "how rough is the surface?" Slide them around in the demo below and watch a hunk of geometry turn into believable materials, live, at 60fps. No textures, no asset packs. Just physics in a fragment shader.

That's physically-based rendering (PBR), and it's the lighting model behind basically every modern game and renderer. The promise of this episode: by the end you'll have written a real Cook-Torrance / GGX microfacet BRDF in WGSL — the distribution, the geometry term, the Fresnel — accumulate it over multiple lights, split albedo and reflectance by a metallic value, tonemap to sRGB, and tune the whole thing with two sliders. Metal will look like metal because the math says it must.

0 fps
a sphere, auto-orbiting · pick a stage →
init…
Many lights + material sliders. Gold, steel, plastic — all the same sphere.

What you're looking at

One UV-sphere, generated in JavaScript into a vertex+index buffer (no model file), spinning so the light rakes across it without you touching anything. The stage dropdown peels the lighting model open one layer at a time — from a flat fill color all the way to the full microfacet shading. The two sliders that matter, metallic and roughness, feed straight into the BRDF; the preset dropdown just snaps them (and a base color) to a recognizable material. lights adds or removes colored point lights orbiting the sphere. The badge bottom-left tells you whether you're on the real WebGPU path or the Canvas2D fallback.

Each stage is a different stageMode value handed to the same fragment shader as a uniform. The geometry, camera, and depth buffer never change — only the math that turns a surface point into a color. That's the whole point: lighting is a function you evaluate per pixel, and PBR is just a particular, physically-motivated choice of that function.

Stage 1 — Flat color

The baseline. Every fragment returns the same albedo, ignoring geometry entirely. The sphere reads as a flat disc — a circle of solid color — because with no lighting there's nothing to tell your eye where the surface curves toward or away from a light. This is the "before" picture. It also proves the pipeline works: geometry, camera, depth test, present. Everything from here is just a smarter fragment shader.

Stage 2 — Normals as RGB

Before we light anything, we have to know which way each point on the surface faces. That's the normal: a unit vector pointing straight out of the surface. Visualizing it as color — rgb = normal * 0.5 + 0.5 — gives the classic candy-coated sphere: +X red, +Y green, +Z blue. This stage is your permanent debugging view. If lighting ever looks wrong, flip to normals: if they look wrong (faceted, discontinuous, wrong-way), your normal matrix or your interpolation is the bug, not the BRDF.

Stage 3 — Diffuse (Lambert N·L)

The simplest real lighting. A perfectly matte surface scatters incoming light equally in every direction, so its brightness depends only on the angle between the surface normal N and the direction to the light L. That's max(dot(N, L), 0) — the Lambert term. Facing the light: full brightness. Grazing it: dark. Facing away: black (clamped, never negative — light can't subtract). Suddenly the disc is a ball. This single dot product is responsible for most of the "it's 3D" signal your brain gets.

Stage 4 — GGX specular highlight

Matte is only half the story. Shiny surfaces also bounce a mirror-ish reflection of the light straight at your eye — the bright hot spot you see on an apple or a car hood. We model it with the GGX / Trowbridge-Reitz microfacet distribution: imagine the surface is a sea of tiny mirrors, and roughness controls how wildly their angles vary. Low roughness → the mirrors mostly agree → a tight, bright highlight. High roughness → they scatter → a broad, dim sheen. Drag the roughness slider here and watch the highlight bloom from a pinpoint to a soft glow.

Stage 5 — Full PBR: metallic, roughness, Fresnel

Now we combine diffuse and specular the physically correct way, and that's where metallic earns its keep. Two facts drive everything:

  • Metals have no diffuse color. Their albedo is zero; all their color comes from tinted specular reflection. Plastic (a "dielectric") is the opposite: a colored diffuse body plus a faint, white, ~4% specular.
  • Everything gets more mirror-like at grazing angles. Look at a lake: straight down it's transparent, but at the horizon it's a perfect mirror. That's the Fresnel effect, and we approximate it with Schlick's equation.

We encode all of this in one value, F0 — the specular color at head-on incidence — via F0 = mix(vec3(0.04), albedo, metallic). At metallic = 0 you get a 4% white dielectric reflection; at metallic = 1 the surface reflects its own albedo as a tinted metal. Slide metallic from 0 to 1 and the sphere transmutes from plastic to gold in front of you.

Stage 6 — Many lights + material presets

Real scenes have more than one light. Because a BRDF describes the response to a single light direction, multiple lights are trivial: evaluate the BRDF once per light and sum the results. We orbit up to four colored point lights and add them in a loop. The preset dropdown snaps metallic, roughness, and base color to gold, brushed steel, matte plastic, or copper — proof that the same shader, fed different numbers, spans wildly different materials. This is the stage to just sit and play with.

The code: passing normals correctly

A normal is a direction, not a position, and it does not transform by the model matrix. If your model has non-uniform scale, multiplying the normal by the model matrix shears it off the surface. The correct transform is the inverse-transpose of the model's upper 3×3. We compute it on the CPU and pass it as its own uniform, alongside the model matrix (for world position) and the view-projection:

// JS — build the matrices each frame. mat4 helpers are inlined (see §11).
const model = mat4.mul(mat4.rotY(angle), mat4.scale(s, s, s));
const view  = mat4.lookAt(eye, [0,0,0], [0,1,0]);
const proj  = mat4.persp(fovy, aspect, 0.1, 100);
const viewProj = mat4.mul(proj, view);

// Normal matrix = inverse-transpose of the model's 3×3. For a uniform-scaled,
// rotated model the rotation part alone is enough — but do it right so the
// per-pixel roughness exercise (non-uniform scale) still works:
const normalMat = mat3.invTranspose(model);   // stored as 3× vec4 for std140 padding

In the vertex shader we move the position to world space (for the view vector and light vectors) and the normal by the normal matrix, then hand both to the fragment shader as interpolated varyings. The fragment shader must re-normalize the normal — linear interpolation across a triangle shortens it:

struct VSOut {
  @builtin(position) clip : vec4f,
  @location(0)            worldPos : vec3f,
  @location(1)            worldNrm : vec3f,
};

@vertex fn vs(in : VSIn) -> VSOut {
  var o : VSOut;
  let wp   = u.model * vec4f(in.pos, 1.0);
  o.worldPos = wp.xyz;
  o.worldNrm = (u.normalMat * vec4f(in.nrm, 0.0)).xyz;  // w=0: direction
  o.clip     = u.viewProj * wp;
  return o;
}

@fragment fn fs(in : VSOut) -> @location(0) vec4f {
  let N = normalize(in.worldNrm);   // MUST renormalize after interpolation
  let V = normalize(u.camPos - in.worldPos);
  // … lighting from here …
}

The code: the GGX BRDF in WGSL

Here is the heart of the episode — the three functions of the Cook-Torrance specular term. D (distribution) is how many microfacets point the right way to reflect light at your eye. G (geometry / Smith) accounts for microfacets shadowing and masking each other at grazing angles. F (Fresnel / Schlick) is the angle-dependent reflectance. The specular BRDF is D·G·F / (4·(N·V)·(N·L)):

const PI = 3.14159265;

// D — GGX / Trowbridge-Reitz normal distribution
fn distGGX(N : vec3f, H : vec3f, rough : f32) -> f32 {
  let a   = rough * rough;          // perceptual → linear roughness
  let a2  = a * a;
  let nh  = max(dot(N, H), 0.0);
  let d   = (nh * nh) * (a2 - 1.0) + 1.0;
  return a2 / max(PI * d * d, 1e-7);
}

// G — Smith geometry with Schlick-GGX, separable into view & light terms
fn geoSchlickGGX(nx : f32, rough : f32) -> f32 {
  let r = rough + 1.0;
  let k = (r * r) / 8.0;          // direct-light remap of k
  return nx / (nx * (1.0 - k) + k);
}
fn geoSmith(N : vec3f, V : vec3f, L : vec3f, rough : f32) -> f32 {
  let nv = max(dot(N, V), 0.0);
  let nl = max(dot(N, L), 0.0);
  return geoSchlickGGX(nv, rough) * geoSchlickGGX(nl, rough);
}

// F — Fresnel-Schlick: reflectance rises to 1.0 at grazing angles
fn fresnelSchlick(cosTheta : f32, F0 : vec3f) -> vec3f {
  return F0 + (vec3f(1.0) - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
}

The code: the per-light accumulation loop

With D, G, F in hand, lighting one surface point is: for each light, build the half-vector H, evaluate the specular BRDF, split energy between specular and diffuse (Fresnel F is the specular fraction, so diffuse gets 1 − F, and metals kill diffuse entirely), then weight by the light's color, its 1/r² falloff, and the cosine N·L. Sum over all lights:

var Lo = vec3f(0.0);
for (var i = 0u; i < u.lightCount; i = i + 1u) {
  let Lp    = u.lights[i].pos.xyz;
  let toL   = Lp - worldPos;
  let dist  = length(toL);
  let L     = toL / dist;
  let H     = normalize(V + L);
  let atten = 1.0 / (dist * dist);          // inverse-square falloff
  let radiance = u.lights[i].color.rgb * u.lights[i].color.a * atten;

  let nl = max(dot(N, L), 0.0);
  let D  = distGGX(N, H, rough);
  let G  = geoSmith(N, V, L, rough);
  let F  = fresnelSchlick(max(dot(H, V), 0.0), F0);

  let spec = (D * G) * F /
             max(4.0 * max(dot(N, V), 0.0) * nl, 1e-4);

  // energy conservation: diffuse gets what specular didn't reflect,
  // and metals (metallic→1) have no diffuse at all.
  let kd = (vec3f(1.0) - F) * (1.0 - u.metallic);
  let diffuse = kd * albedo / PI;

  Lo = Lo + (diffuse + spec) * radiance * nl;
}

The code: F0, the albedo split, tonemap + gamma

Three small but load-bearing pieces wrap the loop. First, metallic and the base color decide both the specular color F0 and the diffuse albedo — a metal's diffuse is forced toward black. Second — and this is the part everyone gets bitten by — a fully metallic surface lit by only the point lights is almost black: its albedo is zero, so it has no diffuse, and the analytic specular is just a few pinprick highlights where a light lines up with your eye. Real metal isn't black; it's a mirror of its environment. So we add a cheap stand-in for image-based lighting: a hemispherical sky color for the (dielectric) diffuse, plus the same sky reflected along R = reflect(−V, N) and tinted by F0 for the specular. That reflection is what actually lights the gold. Third, all of this happened in linear space, so we scale by an exposure, run a filmic-ish tonemap to tame bright highlights, and convert linear → sRGB with a gamma curve:

// --- before the loop: split base color by metallic ---
let baseCol = u.baseColor.rgb;
let F0      = mix(vec3f(0.04), baseCol, u.metallic);  // 4% dielectric, else tinted metal
let albedo  = baseCol * (1.0 - u.metallic);             // metals have ~no diffuse

// --- after the loop: fake-IBL ambient so metals aren't black ---
let nv      = max(dot(N, V), 0.0);
let R       = reflect(-V, N);                          // view reflected about the normal
let Fenv    = fresnelSchlickRough(nv, F0, roughness);    // roughness-aware grazing reflectance
let kdEnv   = (vec3f(1.0) - Fenv) * (1.0 - u.metallic);
let diffEnv = kdEnv * albedo * envColor(N);              // sky irradiance (dielectrics)
let specEnv = envColor(R) * Fenv;                        // reflected sky, tinted by F0 → the metal
let ambient = (diffEnv + specEnv) * 0.9;

// --- exposure, tonemap, gamma ---
var color = (ambient + Lo) * 1.6;             // exposure
color = color / (color + vec3f(1.0));         // Reinhard tonemap (linear → ~[0,1])
color = pow(color, vec3f(1.0 / 2.2));        // linear → sRGB gamma
return vec4f(color, 1.0);

That environment term is the difference between a believable gold sphere and a dark olive blob: with only point lights a metal has nothing to reflect, so it reads as black. And that pow(color, 1/2.2) at the end is the single most common thing people forget — it's why so many first PBR attempts look like they're rendered in mud. Light math is linear; your monitor is not.

Common pitfalls

  • Normals transformed by the model matrix. Under non-uniform scale a normal multiplied by the model matrix is no longer perpendicular to the surface — your lighting smears. Use the inverse-transpose of the upper 3×3. (For a pure rotation + uniform scale, the rotation alone is fine, but doing it correctly costs nothing and survives the exercises.)
  • Not re-normalizing in the fragment shader. Interpolating a unit normal across a triangle yields a vector shorter than 1. Call normalize() on the interpolated worldNrm before any dot product, or your highlights will pulse and dim across each face.
  • Forgetting gamma / tonemap. All lighting is done in linear space; the framebuffer is displayed as sRGB. End with a tonemap and pow(c, 1/2.2). Forget it and the image is dark and washed out. (If you configure the canvas with an -srgb format you can skip the manual gamma — but be deliberate, never accidental.)
  • Double-counting energy. Fresnel F is the fraction of light reflected specularly; diffuse must use (1 − F), not the full albedo, or the surface emits more light than it received and glows unnaturally. Add the ambient term once, outside the per-light loop.
  • Black metals (no environment term). The textbook trap: a fully metallic surface has zero albedo, so with only analytic point lights it has no diffuse and just a few pinprick specular highlights — it renders as a near-black blob, not gold. Metals are mostly reflections of their surroundings, so you must add an environment/IBL term (even a fake hemispherical sky reflected along R, tinted by F0). Crank a tiny flat ambient instead and your metal stays dark and reads matte. This is the most common "my PBR looks wrong" cause after gamma.
  • Wrong F0. F0 = mix(0.04, albedo, metallic). A common bug is using the albedo as F0 for dielectrics (turning plastic into chrome) or 0.04 for metals (making gold look like grey plastic). The mix by metallic is the whole material model in one line.
  • WGSL won't cast for you. 1.0 is f32, 1u is u32. The loop counter must be 0u and the light count a u32 uniform, or the shader won't compile. No silent int↔float promotion like GLSL.

Exercises

  1. From fake sky to real IBL. The demo already fakes image-based lighting with a procedural hemisphere (envColor) sampled along N for diffuse and along R for specular — that procedural sky is the whole reason the gold reads as gold and not black. Upgrade it: sample a real environment cubemap instead of the gradient, pre-filter it into roughness mips for the specular lobe, and add a split-sum BRDF LUT for the F0·scale + bias term. That's production IBL — and you'll see exactly how much of "good PBR" is really just a good environment.
  2. A clearcoat layer. Many materials (car paint, lacquered wood, soda cans) have a thin glossy coat on top. Add a second, fixed-low-roughness specular lobe with its own F0 = 0.04, evaluate the same GGX BRDF for it, and add it on top of the base response scaled by a clearcoat strength. Watch a sharp secondary highlight appear over a rough base.
  3. Per-pixel roughness from a procedural map. Instead of a single roughness uniform, compute roughness in the fragment shader from world position — e.g. bands via fract(worldPos.y * 6.0) or a value-noise function — so the sphere shows brushed-and-polished stripes. This is exactly what a roughness texture does; you've just generated it in-shader. (This is also where a sloppy normal matrix finally bites, so make sure yours is the real inverse-transpose.)

What's next

Episode 11 — Shadow maps. Our lights currently shine straight through geometry: a sphere never casts a shadow on the ground because each fragment is lit in isolation, with no idea what's between it and the light. We'll fix that by rendering the scene from the light's point of view into a depth texture, then in the main pass asking "is this fragment the closest thing the light can see, or is something blocking it?" It's the first time our two render passes talk to each other through a texture — and the moment flat-lit scenes start to feel like they occupy a real space.