TExcelTAD

Water

Water is a classic shader showcase because it combines almost everything in this course: animated waves from layered functions, normals from a height field, Fresnel reflection, and color that depends on depth. There is no single "water shader". A stylized pond, an open ocean and a puddle on a street use very different tricks. This lesson builds the common core, step by step, on a flat plane viewed from a low camera.

Step 1: a plane seen in perspective

Before waves, we need a surface. For each pixel, shoot a ray from the camera and intersect it with the plane y = 0 (the Ray–Plane test): t = -ro.y / rd.y, valid when the ray points down. The hit point's xz are the water coordinates for that pixel.

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    vec3 ro = vec3(0.0, 1.0, 0.0);
    vec3 rd = normalize(vec3(p.x, p.y - 0.15, -1.0));

    vec3 color = mix(vec3(0.85, 0.85, 0.9), vec3(0.3, 0.5, 0.85), clamp(rd.y * 3.0, 0.0, 1.0));  // sky
    if (rd.y < 0.0) {
        float t = -ro.y / rd.y;
        vec2 xz = (ro + rd * t).xz;
        float grid = step(0.95, max(fract(xz.x), fract(xz.y)));   // grid lines every 1 unit
        color = mix(vec3(0.05, 0.2, 0.3), vec3(0.8), grid);
    }
    fragColor = vec4(color, 1.0);
}

The grid shows the perspective: lines bunch up toward the horizon, and far away they shimmer because many grid cells fall inside one pixel (aliasing). Remember that; water has the same problem with small waves.

Step 2: waves as a sum of sines

A single sine wave looks like corrugated metal. Several waves with different directions, wavelengths and speeds add up to something that reads as water. Each wave is amplitude * sin(dot(direction, xz) * frequency + time * speed). Real swell follows a dispersion rule (longer waves travel faster, speed ∝ sqrt(frequency)), which we use here.

glsl
float waves(vec2 xz, float time) {
    float h = 0.0, amp = 0.12, freq = 1.0;
    vec2 dir = vec2(1.0, 0.0);
    for (int i = 0; i < 6; i++) {
        h += amp * sin(dot(dir, xz) * freq + time * sqrt(freq) * 1.5);
        dir = mat2(0.8, 0.6, -0.6, 0.8) * dir;   // rotate each wave
        freq *= 1.8;
        amp *= 0.55;
    }
    return h;
}

This is the same "octaves" idea as fbm in the Noise lesson, with sines instead of noise. Ocean renderers use Gerstner waves (which also move points sideways, sharpening the crests) or an FFT of a measured ocean spectrum (Tessendorf's method, used in many AAA oceans), but a sine sum is the right place to start.

Step 3: normals and lighting

A flat-shaded plane with a moving height still looks flat from above. What sells water is how its normals change: they tilt the reflection and the specular highlight. Take the gradient of the height with finite differences, exactly as in 2D Lighting with SDF Normals, but on the xz plane with y up:

glsl · try it yourself
float waves(vec2 xz, float time) {
    float h = 0.0, amp = 0.12, freq = 1.0;
    vec2 dir = vec2(1.0, 0.0);
    for (int i = 0; i < 6; i++) {
        h += amp * sin(dot(dir, xz) * freq + time * sqrt(freq) * 1.5);
        dir = mat2(0.8, 0.6, -0.6, 0.8) * dir;
        freq *= 1.8;
        amp *= 0.55;
    }
    return h;
}
vec3 waterNormal(vec2 xz, float time) {
    float e = 0.01;
    float hx = waves(xz + vec2(e, 0.0), time) - waves(xz - vec2(e, 0.0), time);
    float hz = waves(xz + vec2(0.0, e), time) - waves(xz - vec2(0.0, e), time);
    return normalize(vec3(-hx, 2.0 * e, -hz));
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    vec3 ro = vec3(0.0, 1.0, 0.0);
    vec3 rd = normalize(vec3(p.x, p.y - 0.15, -1.0));
    vec3 sunDir = normalize(vec3(0.0, 0.25, -1.0));

    vec3 color = vec3(0.6, 0.75, 0.95);
    if (rd.y < 0.0) {
        vec2 xz = (ro + rd * (-ro.y / rd.y)).xz;
        vec3 n = waterNormal(xz, iTime);
        float diffuse = max(dot(n, sunDir), 0.0);
        float spec = pow(max(dot(reflect(rd, n), sunDir), 0.0), 200.0);
        color = vec3(0.0, 0.15, 0.25) * (0.3 + diffuse) + vec3(1.0, 0.9, 0.7) * spec * 3.0;
    }
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}

The sun's reflection breaks into a glittering path because each wave tilts the normal a little. That one line, pow(dot(reflect(rd, n), sunDir), 200), does most of the work.

Step 4: Fresnel and sky reflection

Water is a weak mirror straight down and a strong one at grazing angles (see Rim Light and Fresnel, water's F0 ≈ 0.02). Blend between the deep water color (light scattered back from below the surface) and the reflected sky with Schlick's Fresnel term. Fade the waves' influence with distance as well, which hides the shimmering aliasing near the horizon:

glsl · try it yourself
float waves(vec2 xz, float time) {
    float h = 0.0, amp = 0.12, freq = 1.0;
    vec2 dir = vec2(1.0, 0.0);
    for (int i = 0; i < 6; i++) {
        h += amp * sin(dot(dir, xz) * freq + time * sqrt(freq) * 1.5);
        dir = mat2(0.8, 0.6, -0.6, 0.8) * dir;
        freq *= 1.8;
        amp *= 0.55;
    }
    return h;
}
vec3 waterNormal(vec2 xz, float time, float dist) {
    float e = 0.01;
    float hx = waves(xz + vec2(e, 0.0), time) - waves(xz - vec2(e, 0.0), time);
    float hz = waves(xz + vec2(0.0, e), time) - waves(xz - vec2(0.0, e), time);
    vec3 n = normalize(vec3(-hx, 2.0 * e, -hz));
    return normalize(mix(n, vec3(0.0, 1.0, 0.0), clamp(dist / 40.0, 0.0, 0.9)));  // calmer far away
}
vec3 sky(vec3 d, vec3 sunDir) {
    vec3 c = mix(vec3(0.85, 0.8, 0.75), vec3(0.25, 0.45, 0.8), clamp(d.y * 2.5, 0.0, 1.0));
    return c + vec3(1.0, 0.85, 0.6) * pow(max(dot(d, sunDir), 0.0), 300.0) * 8.0;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    vec3 ro = vec3(0.0, 1.0, 0.0);
    vec3 rd = normalize(vec3(p.x, p.y - 0.15, -1.0));
    vec3 sunDir = normalize(vec3(0.3, 0.2, -1.0));

    vec3 color = sky(rd, sunDir);
    if (rd.y < 0.0) {
        float t = -ro.y / rd.y;
        vec2 xz = (ro + rd * t).xz;
        vec3 n = waterNormal(xz, iTime, t);

        float cosTheta = max(dot(n, -rd), 0.0);
        float F = 0.02 + 0.98 * pow(1.0 - cosTheta, 5.0);
        vec3 r = reflect(rd, n);
        r.y = abs(r.y);                                    // waves can reflect below the horizon
        vec3 deep = vec3(0.0, 0.07, 0.1);
        vec3 scatter = vec3(0.0, 0.25, 0.25) * max(waves(xz, iTime) + 0.1, 0.0);   // brighter crests
        color = mix(deep + scatter, sky(r, sunDir), F);
        color = mix(color, sky(rd, sunDir), 1.0 - exp(-t * 0.02));   // haze toward the horizon
    }
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}

Near the camera you look down into dark water; toward the horizon the surface turns into a mirror of the sky. The scatter term fakes light passing through the thin wave crests, which is why the tops of waves look greener.

What full game water adds

Feature Technique Needs
geometry that actually moves Gerstner waves in the vertex shader on a dense mesh a tessellated plane (see Vertex Shaders)
real reflections of the scene screen-space reflections or a planar reflection render target Render Targets
refraction of the bottom sample the scene color buffer, offset by the normal the opaque scene texture (URP Opaque Texture, Unreal SceneColor in translucent materials, Godot hint_screen_texture)
depth-based color and shore foam compare water depth with the scene depth buffer the depth texture
detail ripples scrolling normal-map textures, two layers in different directions textures
interaction a ripple simulation in a render target, or decals render targets

Notice the last column: nearly every step beyond this lesson needs a texture of something else that was rendered first. That is why water is usually one of the last shaders written for a game, and why the Post-Processing section comes next.

Test yourself

Why sum several sine waves with different directions and frequencies?

  1. One sine is too slow to compute
  2. A single sine looks like regular corrugation; several irregular layers read as natural water
  3. WebGL requires it
  4. To compute normals

Why does water look dark when you look straight down and bright near the horizon?

  1. The sky is darker above
  2. Fresnel: reflection is about 2% at normal incidence and approaches 100% at grazing angles
  3. Waves are bigger far away
  4. Gamma correction

What does the glittering path of sunlight come from in this shader?

  1. A texture
  2. The specular term computed with wave-tilted normals
  3. The sky color
  4. Bloom