Diffuse Lighting (Lambert)
Hold a sheet of paper under a lamp and tilt it. Facing the lamp it is bright; tilted away it darkens; edge-on it gets almost nothing. That is Lambertian (diffuse) reflection, the base of almost every lighting model in games. Matte surfaces such as chalk, plaster, unpolished wood and skin are close to Lambertian: they scatter light equally in all directions, so they look the same from wherever you view them.
The rule: N · L
The brightness depends only on the angle between the surface normal N and the direction to the light L. A beam of light hitting a tilted surface spreads over a larger area, so each point receives less energy, by exactly the cosine of the angle. Both vectors are unit length, so the cosine is a dot product:
diffuse = max(dot(N, L), 0.0) * lightColor * albedomax(..., 0) throws away the negative values on the back side, where the surface faces away from the light. albedo is the surface's own color: the fraction of each color channel it reflects.
for (const deg of [0, 30, 45, 60, 80, 90, 120]) {
const a = (deg * Math.PI) / 180;
const N = [0, 1, 0];
const L = [Math.sin(a), Math.cos(a), 0]; // light tilted 'deg' degrees from the normal
const ndotl = N[0] * L[0] + N[1] * L[1] + N[2] * L[2];
const lit = Math.max(ndotl, 0);
console.log(`${String(deg).padStart(3)}° N·L = ${ndotl.toFixed(3).padStart(6)} diffuse = ${lit.toFixed(3)}`);
} 0° N·L = 1.000 diffuse = 1.000
30° N·L = 0.866 diffuse = 0.866
45° N·L = 0.707 diffuse = 0.707
60° N·L = 0.500 diffuse = 0.500
80° N·L = 0.174 diffuse = 0.174
90° N·L = 0.000 diffuse = 0.000
120° N·L = -0.500 diffuse = 0.000
At 60° a surface already receives half the light. That fast falloff is what gives spheres their round look.
Lambert in the raymarched scene
The scene from Normal Estimation, now lit by a sun that circles overhead. Everything not facing the sun is pure black, which looks harsh, as on the Moon, where there is no sky to fill the shadows.
float map(vec3 p) {
float sphere = length(p - vec3(0.0, 1.0, 0.0)) - 1.0;
return min(sphere, p.y);
}
vec3 calcNormal(vec3 p) {
const vec2 k = vec2(1.0, -1.0);
const float e = 0.001;
return normalize(k.xyy * map(p + k.xyy * e) + k.yyx * map(p + k.yyx * e) +
k.yxy * map(p + k.yxy * e) + k.xxx * map(p + k.xxx * e));
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
vec3 ro = vec3(0.0, 1.6, -4.0);
vec3 rd = normalize(vec3(uv, 1.6) + vec3(0.0, -0.15, 0.0));
float t = 0.0;
bool hit = false;
for (int i = 0; i < 100; i++) {
float d = map(ro + rd * t);
if (d < 0.001) { hit = true; break; }
t += d;
if (t > 40.0) break;
}
vec3 color = vec3(0.0);
if (hit) {
vec3 p = ro + rd * t;
vec3 n = calcNormal(p);
vec3 l = normalize(vec3(cos(iTime), 0.8, sin(iTime))); // direction TO the sun
vec3 albedo = p.y < 0.01 ? vec3(0.6) : vec3(0.9, 0.3, 0.2);
float diffuse = max(dot(n, l), 0.0);
color = albedo * diffuse;
}
fragColor = vec4(color, 1.0);
}Ambient: light from the sky
On Earth, the shaded side of an object is lit by the sky and by light bouncing off the ground. The cheapest model of that is a constant ambient term, but a constant looks flat. A hemisphere light is nearly as cheap and far better: blend between a sky color for normals pointing up and a ground color for normals pointing down.
vec3 hemi = mix(groundColor, skyColor, 0.5 + 0.5 * n.y);
vec3 color = albedo * (sunColor * max(dot(n, l), 0.0) + hemi);Linear light and gamma
All lighting math (adding lights, multiplying by albedo) is correct only in linear space, where the number is proportional to the amount of light. Monitors expect sRGB-encoded values, which spend more precision on dark tones. So the last step of a shader that writes to the screen converts linear to sRGB. The exact sRGB curve has a short linear toe; pow(c, vec3(1.0 / 2.2)) is the common approximation.
Without it, a surface at N·L = 0.5 shows as 50% of the signal, which a display turns into roughly 22% of the light: the falloff looks far too dark and the terminator (the line between lit and unlit) too sharp. This version adds a warm sun, a hemisphere sky, and gamma correction, and splits the screen so you can compare: left half without gamma, right half with it.
float map(vec3 p) {
float sphere = length(p - vec3(0.0, 1.0, 0.0)) - 1.0;
return min(sphere, p.y);
}
vec3 calcNormal(vec3 p) {
const vec2 k = vec2(1.0, -1.0);
const float e = 0.001;
return normalize(k.xyy * map(p + k.xyy * e) + k.yyx * map(p + k.yyx * e) +
k.yxy * map(p + k.yxy * e) + k.xxx * map(p + k.xxx * e));
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
vec3 ro = vec3(0.0, 1.6, -4.0);
vec3 rd = normalize(vec3(uv, 1.6) + vec3(0.0, -0.15, 0.0));
vec3 sky = vec3(0.35, 0.55, 0.9);
vec3 color = sky; // background (already linear)
float t = 0.0;
for (int i = 0; i < 100; i++) {
float d = map(ro + rd * t);
if (d < 0.001) {
vec3 p = ro + rd * t;
vec3 n = calcNormal(p);
vec3 l = normalize(vec3(cos(iTime * 0.7), 0.9, sin(iTime * 0.7)));
vec3 albedo = p.y < 0.01 ? vec3(0.5) : vec3(0.8, 0.15, 0.1);
vec3 sun = vec3(1.0, 0.9, 0.75) * 1.4 * max(dot(n, l), 0.0);
vec3 hemi = mix(vec3(0.15, 0.1, 0.08), sky * 0.5, 0.5 + 0.5 * n.y);
color = albedo * (sun + hemi);
break;
}
t += d;
if (t > 40.0) break;
}
if (fragCoord.x > 0.5 * iResolution.x) color = pow(color, vec3(1.0 / 2.2)); // linear -> display
if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) color = vec3(1.0); // divider
fragColor = vec4(color, 1.0);
}The right half looks like a real object in daylight: soft falloff, colored shadows. The Field Notes come back to linear vs gamma, because getting it wrong is one of the most common bugs in hand-written shaders.
Note: Engines handle this for you when the project is set to linear color space (Unity's default for new projects, Unreal and Godot always): textures marked sRGB are decoded on sampling, and the frame is encoded on output. In hand-written WebGL or a playground, you do it yourself.
Several lights
Light adds up. For several lights, sum each light's contribution; for point lights, compute L per pixel and dim the light with distance:
vec3 toLight = lightPos - p;
float dist = length(toLight);
vec3 l = toLight / dist;
float attenuation = 1.0 / (dist * dist); // physically correct inverse square
color += albedo * lightColor * max(dot(n, l), 0.0) * attenuation;Engines add a smooth cut-off at the light's range so a light can be skipped beyond it.
Test yourself
In the Lambert term max(dot(N, L), 0.0), what is L?
- The direction from the light to the surface
- The unit direction from the surface toward the light
- The view direction
- The light color
Why apply pow(color, vec3(1.0/2.2)) at the end?
- To make colors more saturated
- To encode linear lighting results for an sRGB display
- To normalize the color
- To add ambient light
A hemisphere ambient light blends between two colors based on what?
- The distance to the camera
- The normal's y component
- The time
- N·L