2D Lighting with SDF Normals
Flat shapes come alive when light hits them. To light a surface you need its normal: the direction the surface faces at each point. A 2D shader has no mesh and no normals, but it has something just as good: a function you can sample anywhere. The slope (the gradient) of a height function or an SDF gives you the normal, and with a normal you can light it like 3D.
This lesson is the bridge to the 3D Lighting section: the same three steps (normal, light direction, dot) light every surface in this course.
Normals from a height function
Picture the shape as a little hill: height 0 outside, rising toward the middle. At each pixel, measure how fast the height changes in x and in y with finite differences (sample one small step to each side). A surface tilted by (dx, dy) has the normal normalize(vec3(-dx, -dy, 1)), where z points out of the screen at the viewer.
Here the height comes from a circle SDF, shaped into a dome. The light direction follows the mouse (or circles around when there is no click):
float height(vec2 p) {
float d = length(p) - 0.3; // circle SDF
return sqrt(max(0.0, -d * (0.6 + d))); // a dome of radius 0.3 inside the circle
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
vec2 m = (iMouse.xy - 0.5 * iResolution.xy) / iResolution.y;
if (iMouse.xy == vec2(0.0)) m = 0.6 * vec2(cos(iTime), sin(iTime));
float e = 0.002; // finite-difference step
float dx = (height(p + vec2(e, 0)) - height(p - vec2(e, 0))) / (2.0 * e);
float dy = (height(p + vec2(0, e)) - height(p - vec2(0, e))) / (2.0 * e);
vec3 n = normalize(vec3(-dx, -dy, 1.0));
vec3 lightDir = normalize(vec3(m, 0.5)); // from the surface toward the light
float diffuse = max(dot(n, lightDir), 0.0); // Lambert
vec3 albedo = height(p) > 0.0 ? vec3(0.9, 0.4, 0.3) : vec3(0.35, 0.4, 0.45);
vec3 color = albedo * (0.15 + 0.85 * diffuse);
fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}The key line is max(dot(n, lightDir), 0.0): the cosine of the angle between the normal and the light. Faces pointing at the light get 1, faces at 90° get 0, and faces pointing away are clamped to 0 instead of going negative. This is Lambert's cosine law, covered fully in Diffuse Lighting.
Note: Finite differences need about four extra samples of the height function per pixel. For an analytic function you can compute the derivative by hand instead; for anything procedural (noise, fbm, combined SDFs), finite differences are the practical choice.
Bumpy surfaces from noise
Any height function works. Feed in fbm noise and the same code lights a rough stone or embossed metal. The surface is still flat; only the normals change. That is exactly what a normal map does on a 3D mesh (see Normal Maps and Tangent Space).
float hash12(vec2 p) {
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
float noise(vec2 p) {
vec2 i = floor(p), f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x),
mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
}
float height(vec2 p) {
float h = 0.0, a = 0.5;
for (int i = 0; i < 5; i++) { h += a * noise(p); p *= 2.0; a *= 0.5; }
return h;
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 p = fragCoord / iResolution.y * 6.0;
float e = 0.01, bump = 0.4;
float hx = height(p + vec2(e, 0)) - height(p - vec2(e, 0));
float hy = height(p + vec2(0, e)) - height(p - vec2(0, e));
vec3 n = normalize(vec3(-hx * bump / (2.0 * e), -hy * bump / (2.0 * e), 1.0));
vec3 lightDir = normalize(vec3(cos(iTime), sin(iTime), 0.6));
float diffuse = max(dot(n, lightDir), 0.0);
vec3 color = vec3(0.6, 0.55, 0.5) * (0.1 + 0.9 * diffuse);
fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}Change bump to 0.1 and 1.5 to see the strength of the effect. It scales the slope, and with it how strongly the normals tilt.
Point lights and falloff
A directional light (the sun) has the same direction everywhere. A point light (a torch, a lamp) sits at a position: the direction to it changes per pixel, and its brightness falls off with distance. Physically the falloff is 1 / distance²; games often use a smoother, artist-friendly curve that reaches zero at a chosen radius so lights can be culled.
float sdBox(vec2 p, vec2 b) {
vec2 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
}
float scene(vec2 p) {
float d = sdBox(p - vec2(-0.3, -0.05), vec2(0.12, 0.2));
d = min(d, length(p - vec2(0.35, 0.1)) - 0.12);
return d;
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
vec2 lightPos = vec2(0.6 * sin(iTime * 0.7), 0.3);
vec2 toLight = lightPos - p;
float dist = length(toLight);
float radius = 0.9;
float atten = pow(clamp(1.0 - dist / radius, 0.0, 1.0), 2.0); // 1 at the light, 0 at radius
float d = scene(p);
vec3 color = (d < 0.0 ? vec3(0.8, 0.7, 0.5) : vec3(0.25, 0.3, 0.35)) * (0.05 + atten);
color += vec3(1.0, 0.9, 0.6) * 0.002 / (dist * dist + 0.0005); // the bulb itself
fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}Soft shadows by marching the SDF
The floor in the last example is lit even behind the objects. To cast shadows, walk from each pixel toward the light and check whether a shape is in the way. With an SDF you don't need tiny fixed steps: at every point, the SDF tells you how far you can move without hitting anything. This is sphere tracing, the same algorithm the raymarching lessons use in 3D.
Track the closest miss along the way, relative to the distance travelled, and you get a soft penumbra for free:
float sdBox(vec2 p, vec2 b) {
vec2 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
}
float scene(vec2 p) {
float d = sdBox(p - vec2(-0.3, -0.05), vec2(0.12, 0.2));
d = min(d, length(p - vec2(0.35, 0.1)) - 0.12);
return d;
}
float softShadow(vec2 p, vec2 lightPos, float k) {
vec2 dir = normalize(lightPos - p);
float maxT = length(lightPos - p);
float t = 0.01, light = 1.0;
for (int i = 0; i < 48; i++) {
float d = scene(p + dir * t);
if (d < 0.0005) return 0.0; // blocked
light = min(light, k * d / t); // near miss -> partial shadow
t += d;
if (t > maxT) break; // reached the light
}
return clamp(light, 0.0, 1.0);
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
vec2 m = (iMouse.xy - 0.5 * iResolution.xy) / iResolution.y;
vec2 lightPos = iMouse.xy == vec2(0.0) ? vec2(0.6 * sin(iTime * 0.7), 0.35) : m;
float dist = length(lightPos - p);
float atten = pow(clamp(1.0 - dist / 1.2, 0.0, 1.0), 2.0);
float d = scene(p);
vec3 color;
if (d < 0.0) color = vec3(0.8, 0.7, 0.5) * 0.3;
else color = vec3(0.3, 0.35, 0.4) * (0.03 + atten * softShadow(p, lightPos, 8.0));
color += vec3(1.0, 0.9, 0.6) * 0.002 / (dist * dist + 0.0005);
fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}Raise k from 8 to 32 for harder shadows; lower it to 2 for very soft ones. Click and drag to move the light. The loop costs up to 48 SDF evaluations per pixel, which is why real 2D engines usually render shadows into a separate low-resolution buffer.
A swizzle mistake
Swizzles (.xy, .zyx, .rgb) can only name components the vector actually has. Asking for .z of a vec2 is a compile error, and a very common one when 2D code is upgraded to 3D or back:
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 p = fragCoord / iResolution.xy;
float depth = p.z; // copied from a 3D shader
fragColor = vec4(p, depth, 1.0);
}Shader compile error:
ERROR: line 3: 'z' : vector field selection out of range
A vec2 only has x and y (or r, g / s, t), so the compiler names the offending selection and stops. The fix depends on intent: give the shader a real third value (float depth = 0.5;), or make p a vec3 where it is created. When a selection with several letters is wrong, such as p.xz, the message quotes the whole swizzle, and the next lines often add follow-up errors such as 'constructor' : not enough data provided for construction: fix the first one and rerun.
Test yourself
How do you get a surface normal from a 2D height function h(x, y)?
- normalize(vec3(h, h, 1))
- normalize(vec3(-dh/dx, -dh/dy, 1)) using finite differences
- vec3(0, 0, 1) always
- cross(x, y)
Why is the Lambert term written max(dot(n, l), 0.0)?
- To normalize the light
- So surfaces facing away from the light get no light instead of negative light
- To make it faster
- Because dot can exceed 1
In SDF shadow marching, how far does each step move?
- A fixed tiny step
- The SDF value at the current point, the largest step that cannot hit anything
- Always to the light in one step
- Half the distance to the light