TExcelTAD
Home › Shaders & Graphics Programming › Shaders Exercises

Shaders Exercises

Practice the core moves of shader programming: shaping values with smoothstep, building patterns from fract and floor, hashing and noise, SDFs, lighting and post-processing. Each exercise has a starter that compiles and runs but shows the wrong picture (usually black or a flat color). Edit it, press Ctrl+Enter, and compare with the description. Try for a while before opening the solution.

Tip: When the picture is wrong and you don't know why, output the intermediate value as a color: fragColor = vec4(vec3(d), 1.0); for a distance, vec4(uv, 0.0, 1.0) for coordinates, vec4(n * 0.5 + 0.5, 1.0) for a normal. Debugging Shaders has more of these.

Exercise 1: an anti-aliased ring

Topics: Shapes with SDFs, smoothstep, aspect ratio

Draw a white ring (outer radius 0.4, thickness 0.05, in units of the frame height) centered on a dark blue background. The edges must be smooth, about one pixel wide, at any frame size, and the ring must stay round when the frame is resized.

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = fragCoord / iResolution.xy;          // TODO: centered, aspect-correct coordinates
    float d = 1.0;                                // TODO: signed distance to the ring
    float px = 1.0 / iResolution.y;               // one pixel in these units
    float ring = 0.0;                             // TODO: 1 inside the ring, 0 outside, smooth edge
    vec3 color = mix(vec3(0.05, 0.07, 0.2), vec3(1.0), ring);
    fragColor = vec4(color, 1.0);
}
Show solution

A ring is the absolute value of a circle's distance, minus half the thickness: abs(length(p) - r) - w.

glsl
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y * 0.5;   // y from -0.5 to 0.5
    float d = abs(length(p) - 0.4) - 0.025;
    float px = 1.0 / iResolution.y;
    float ring = 1.0 - smoothstep(-px, px, d);
    vec3 color = mix(vec3(0.05, 0.07, 0.2), vec3(1.0), ring);
    fragColor = vec4(color, 1.0);
}

Exercise 2: a rotating checkerboard

Topics: Patterns and Tiling, Animating with iTime, 2D rotation

Fill the frame with a black-and-white checkerboard of 8 squares per frame height that rotates slowly (one turn every 20 seconds) around the center of the frame.

glsl · try it yourself
mat2 rot(float a) {
    return mat2(1.0);                             // TODO: a 2D rotation matrix
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;   // -1..1 vertically
    p = rot(0.0) * p;                             // TODO: angle from iTime
    float checker = 0.0;                          // TODO: 0 or 1 per square
    fragColor = vec4(vec3(checker), 1.0);
}
Show solution

floor(p * 4.0) gives integer cell coordinates (8 cells across the 2-unit height); their sum is even or odd, alternating like a chessboard.

glsl
mat2 rot(float a) {
    float c = cos(a), s = sin(a);
    return mat2(c, s, -s, c);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    p = rot(iTime * 6.2831853 / 20.0) * p;
    vec2 cell = floor(p * 4.0);
    float checker = mod(cell.x + cell.y, 2.0);
    fragColor = vec4(vec3(checker), 1.0);
}

Exercise 3: hash and value noise

Topics: Noise: Value, Perlin and fbm

Implement value noise: a pseudo-random value at every integer lattice point, smoothly interpolated in between. Use the hash given. The result should look like soft grey blobs, about 8 per frame height, drifting to the left.

glsl · try it yourself
float hash(vec2 p) {
    p = fract(p * vec2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

float valueNoise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    // TODO: hash the 4 corners of the cell, smooth f with 3f² - 2f³, and mix
    return hash(i);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = fragCoord / iResolution.y * 8.0;
    p.x += iTime;
    fragColor = vec4(vec3(valueNoise(p)), 1.0);
}
Show solution

The starter shows blocky squares: one value per cell. Interpolating the four corners with a smoothed f removes the blocks and the visible grid lines.

glsl
float valueNoise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    float a = hash(i);
    float b = hash(i + vec2(1.0, 0.0));
    float c = hash(i + vec2(0.0, 1.0));
    float d = hash(i + vec2(1.0, 1.0));
    vec2 u = f * f * (3.0 - 2.0 * f);            // smoothstep curve: no kinks at cell borders
    return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

Exercise 4: fbm clouds

Topics: fractal Brownian motion, octaves, mix

Using your value noise from exercise 3 (it is included here, solved), write fbm with 5 octaves: each octave doubles the frequency and halves the amplitude. Then color the sky: mix from blue to white by the fbm value, so clouds appear where it is high.

glsl · try it yourself
float hash(vec2 p) {
    p = fract(p * vec2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

float valueNoise(vec2 p) {
    vec2 i = floor(p), f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
               mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);
}

float fbm(vec2 p) {
    float sum = 0.0;
    // TODO: 5 octaves
    return sum;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = fragCoord / iResolution.y * 3.0 + vec2(iTime * 0.2, 0.0);
    float clouds = fbm(p);
    vec3 color = vec3(0.25, 0.45, 0.85);         // TODO: blend toward white where clouds are thick
    fragColor = vec4(color, 1.0);
}
Show solution

The amplitudes 0.5 + 0.25 + 0.125 + … add up to just under 1, so fbm stays in 0..1. smoothstep sharpens the cloud edges.

glsl
float fbm(vec2 p) {
    float sum = 0.0, amp = 0.5;
    for (int i = 0; i < 5; i++) {
        sum += amp * valueNoise(p);
        p *= 2.0;
        amp *= 0.5;
    }
    return sum;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = fragCoord / iResolution.y * 3.0 + vec2(iTime * 0.2, 0.0);
    float clouds = smoothstep(0.4, 0.75, fbm(p));
    vec3 color = mix(vec3(0.25, 0.45, 0.85), vec3(1.0), clouds);
    fragColor = vec4(color, 1.0);
}

Exercise 5: read the error

Topics: compiler errors, GLSL types

This shader is meant to draw a pulsing orange circle, but it does not compile. The error is shown below it. Fix the shader without changing what it draws, then explain each error line to yourself.

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    float r = 0.5 + 0.1 * sin(iTime * 3);
    float circle = 1.0 - smoothstep(r - 0.01, r + 0.01, length(p));
    fragColor = vec4(vec3(1.0, 0.5, 0.1) * circle, 1.0);
}
Shader compile error:
ERROR: line 3: '*' : wrong operand types - no operation '*' exists that takes a left-hand operand of type 'uniform highp float' and a right operand of type 'const int' (or there is no acceptable conversion)
Show solution

iTime * 3 multiplies a float by an int, and GLSL ES never converts implicitly. The message spells out both operand types: 'uniform highp float' (that's iTime) and 'const int' (the literal 3). Write 3.0:

glsl
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    float r = 0.5 + 0.1 * sin(iTime * 3.0);
    float circle = 1.0 - smoothstep(r - 0.01, r + 0.01, length(p));
    fragColor = vec4(vec3(1.0, 0.5, 0.1) * circle, 1.0);
}

Exercise 6: light the sphere

Topics: Diffuse Lighting, Specular, gamma

The raymarcher below finds the sphere and its normal, but shades it flat white. Add Lambert diffuse with a light from the upper left (normalize(vec3(-1.0, 1.0, -1.0))), an ambient term of 0.1, a white Blinn-Phong highlight with shininess 64, an albedo of vec3(0.2, 0.5, 0.9), and gamma-correct the final color.

glsl · try it yourself
float map(vec3 p) { return length(p) - 1.0; }

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    vec3 ro = vec3(0.0, 0.0, -3.0);
    vec3 rd = normalize(vec3(uv, 1.5));

    vec3 color = vec3(0.1);
    float t = 0.0;
    for (int i = 0; i < 64; i++) {
        vec3 p = ro + rd * t;
        float d = map(p);
        if (d < 0.001) {
            vec3 n = normalize(p);                // exact normal of a sphere at the origin
            color = vec3(1.0);                    // TODO: Lambert + ambient + Blinn-Phong
            break;
        }
        t += d;
        if (t > 10.0) break;
    }
    fragColor = vec4(color, 1.0);                 // TODO: gamma
}
Show solution
glsl
            vec3 l = normalize(vec3(-1.0, 1.0, -1.0));
            vec3 v = -rd;
            vec3 h = normalize(l + v);
            float diff = max(dot(n, l), 0.0);
            float spec = pow(max(dot(n, h), 0.0), 64.0) * step(0.0, dot(n, l));
            color = vec3(0.2, 0.5, 0.9) * (diff + 0.1) + vec3(spec);
            break;
        }
        t += d;
        if (t > 10.0) break;
    }
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);

The light's z is negative because the camera sits at z = -3 looking toward +z: a light "in front of" the sphere, on the camera's side, has negative z.

Exercise 7: the BRDF numbers

Topics: PBR, Fresnel, JavaScript as a shader calculator

Shader math is easier to check on the CPU. Write schlick(cosTheta, f0), Schlick's Fresnel approximation f0 + (1 - f0)(1 - cosθ)⁵, and ggx(nDotH, roughness), the GGX normal distribution a² / (π ((n·h)²(a² - 1) + 1)²) with a = roughness². Run it: the expected output is below.

js · try it yourself
function schlick(cosTheta, f0) {
  return 0; // TODO
}

function ggx(nDotH, roughness) {
  return 0; // TODO
}

for (const angle of [0, 45, 80, 89]) {
  const c = Math.cos((angle * Math.PI) / 180);
  console.log(`Fresnel at ${angle}°: water ${schlick(c, 0.02).toFixed(4)}, gold ${schlick(c, 0.95).toFixed(4)}`);
}
for (const r of [0.2, 0.5, 1.0]) {
  console.log(`GGX peak (n·h = 1), roughness ${r}: ${ggx(1, r).toFixed(3)}`);
}

Expected output:

text
Fresnel at 0°: water 0.0200, gold 0.9500
Fresnel at 45°: water 0.0221, gold 0.9501
Fresnel at 80°: water 0.3976, gold 0.9693
Fresnel at 89°: water 0.9174, gold 0.9958
GGX peak (n·h = 1), roughness 0.2: 198.944
GGX peak (n·h = 1), roughness 0.5: 5.093
GGX peak (n·h = 1), roughness 1: 0.318
Show solution
js
function schlick(cosTheta, f0) {
  return f0 + (1 - f0) * Math.pow(1 - cosTheta, 5);
}

function ggx(nDotH, roughness) {
  const a2 = roughness ** 4;                       // a = roughness², a² = roughness⁴
  const d = nDotH * nDotH * (a2 - 1) + 1;
  return a2 / (Math.PI * d * d);
}

Two lessons hide in the numbers: water barely reflects when you look straight down but becomes a mirror at grazing angles (the Fresnel effect), and a smooth surface concentrates its highlight into a peak hundreds of times brighter than a rough one.

Exercise 8: vignette and tone mapping

Topics: Color Grading, Tone Mapping and Vignette

The starter produces an HDR image: a sunset gradient whose sun is 6 times brighter than white. Displayed directly, everything above 1 clips flat. Apply Reinhard tone mapping (c / (1 + c)), then gamma, then a vignette that darkens the corners to about 40%.

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;

    vec3 hdr = mix(vec3(1.2, 0.5, 0.2), vec3(0.1, 0.15, 0.4), uv.y);         // sky
    hdr += vec3(6.0, 4.5, 2.5) * exp(-40.0 * dot(p - vec2(0.0, -0.2), p - vec2(0.0, -0.2)));  // sun

    vec3 color = hdr;                              // TODO: tone map, gamma, vignette
    fragColor = vec4(color, 1.0);
}
Show solution
glsl
    vec3 color = hdr / (1.0 + hdr);                          // Reinhard: 0..∞ -> 0..1
    color = pow(color, vec3(1.0 / 2.2));                     // linear -> display
    float vignette = 1.0 - 0.6 * smoothstep(0.4, 1.4, length(uv - 0.5) * 2.0);
    color *= vignette;
    fragColor = vec4(color, 1.0);

The sun now has a visible gradient instead of a flat white disk, and the sky keeps its color. Reinhard is simple but desaturates bright colors; the mini project uses an ACES-style curve with more contrast.

Test yourself

Which expression gives the signed distance to a ring of radius r and half-thickness w?

  1. length(p) - r - w
  2. abs(length(p) - r) - w
  3. max(length(p) - r, w)
  4. length(p) * r - w

Why is u = f * f * (3.0 - 2.0 * f) used in value noise instead of f?

  1. It is faster
  2. It makes the interpolation smooth at cell borders, hiding the grid
  3. It normalizes the hash
  4. It adds octaves

In fbm, what happens to frequency and amplitude from one octave to the next (typical settings)?

  1. Both double
  2. Frequency doubles, amplitude halves
  3. Frequency halves, amplitude doubles
  4. Both stay the same