Shader

Underwater

Eight meters down on pale sand, looking a little up. Water takes red away within a few meters and blue last, so sunlight arrives blue and anything far off fades into the water's own glow, the light it scatters toward the eye, summed along each ray in closed form. Waves on the surface gather sunlight into a moving net of bright lines on the sand, and the same net, read along the light's slanted path, lights shafts in the water. Overhead, the whole sky is squeezed into a bright window in the surface, with a mirror of the deep water outside it; bubbles rise and swell, marine snow drifts down, and every motion comes round in a minute.

· Atmosphere · Fragment shader

Teaches Light absorbed with depth, shafts from the surface, caustics on the sand

Builds on Flowing Color Field (hash21, value noise), Glass Orb, Kiln Floor Tiles (wrap into a period), Smoke Stack, Ocean Waves, Lighthouse, Plucked Strings (time in the loop)

Watch

The idea

Clear water is not clear for long. Each meter of it keeps a share of the light going through and takes the rest, and the share differs by color: here a meter keeps 66% of red, 92% of green and 94% of blue. After ten meters 1.5% of the red is left and more than half of the blue. That is why everything under water turns blue-green with distance and depth, and it is Beer and Lambert's law, exp(−c · length) for each color, as in Smoke Stack, with a c of its own for red, green and blue.

The water also glows. A little of the sunlight in it is scattered aside, and some of that is sent toward the eye, so every ray picks up light all along its way, more where it is long, and anything far off fades into that glow. The water sends most of what it scatters nearly straight on, so the glow is brightest looking toward the sun.

On top of that, two things come from the waves. Each wave is a weak lens, so the surface gathers sunlight into a net of bright lines on the sand, the caustics; and the water under a bright line holds more light than the water under a dark one, so seen from the side the net becomes shafts. Looking up, the surface itself is a bright round window with a mirror round it, Snell's window, because light can only get out of water within 48.6° of straight up.

The eye floats 1.4 m over pale sand, 8 m down at the default depth, looking 17.6° up. All lengths are in meters. Every motion makes a whole number of cycles in a minute, so the picture and the sound loop at 60 seconds. It is built in four steps, each a shader you can run on its own, and then finished.

Stage 1 · Light absorbed with depth

Each pixel's place s runs from −1 to 1 up the picture (wider across), and the ray from the eye is normalize(s.x, s.y + TILT, FOCAL): TILT is 0.35 and FOCAL 1.1, so the middle of the picture looks 17.6° above level. A ray going up ends on the surface, z0 / rd.y away, where z0 is how far the eye is under it, depth − EYE, 6.6 m. For now a ray going down goes on 300 m (FAR), into the dark.

lossOf is all a meter takes from a beam, c: what clear water absorbs (ABSORB, 0.4 for red, 0.06 for green, 0.012 for blue), what it scatters aside (scatterOf, 0.012, 0.018 and 0.028, a little more blue, times murk), and for murky water a little more absorbed, most of it blue (0.005, 0.004 and 0.02 times murk), so murky water turns green. At murk 1 that adds up to 0.42, 0.08 and 0.06: red is taken seven times as fast as blue.

The sun comes from sunInAir, sun degrees over the horizon, ahead and a little to the right. Going into the water it is bent toward straight up by Snell's law, sine in water = sine in air / 1.333 (sunInWater): at 60° up, it is 22° from straight up under water, so its light crosses 1 / L.y, 1.08 m of water for each meter of depth.

glow adds up the light the water sends to the eye along the ray. At s meters out, the ray is z0 − rd.y · s under the surface; sunlight reached that point after slant times that much water, and its share scattered toward the eye then crosses s meters more. Multiplied out, that is exp(−c · slant · z0), which is the same all along the ray, times exp(−m · s) with m = c · (1 − slant · rd.y). So the sum along the ray needs no steps: the sum of exp(−m · s) for s from 0 to len is (1 − exp(−m · len)) / m (along), worked out for each color. Lighthouse summed its fog's thinning with height the same way, in closed form. Skylight, coming in from all over, is taken to cross 1.2 times the depth on its way down.

forward is Henyey and Greenstein's phase function, as in Smoke Stack and Lighthouse, here with g = 0.7 and without the 1/(4π), which only scales it: light carried straight on is 67 times as bright as light turned a quarter turn and about 180 times as bright as light sent straight back. Only the sunlight gets it; the skylight comes from every way and is scattered every way alike.

The surface is a flat, bright 0.5 · SUNLIGHT + 2 · SKYLIGHT for now, dimmed by the water between it and the eye. The picture is that plus the glow: bright above, brightest toward the sun, deep blue below. Last, the eye: 1 − exp(−light · open) keeps bright light from clipping, where open is 1.3 · exp(0.035 · depth), 1.72 at 8 m, opening a little in deeper water as an eye does; a gamma of 2.2; and a speck of noise, half a level of 255 either way, to keep the deep blues from banding.

The sound for now is the sea's rumble, described below.

stage-1-light-absorbed-with-depth.metal
// Stage 1 · Light absorbed with depth
// Each meter of water keeps exp(-c) of a color: c is 0.42 for red,
// 0.08 for green, 0.06 for blue. The light the water scatters toward
// the eye, summed in closed form, is bright above and deep blue below.

// @param depth 8 3 20 How deep the sand lies under the surface, in meters
// @param murk 1 0.2 4 How much the water scatters: more is hazier and greener
// @param sun 60 25 90 The sun's height over the horizon, in degrees
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float LOOP = 60.0;
// The eye floats 1.4 m over the sand, looking a little up.
constant float EYE = 1.4;
constant float TILT = 0.35;
constant float FOCAL = 1.1;
constant float FAR = 300.0;
// What a meter of clear water absorbs of red, green, blue.
constant float3 ABSORB = float3(0.4, 0.06, 0.012);
// Sunlight and the sky's light as they enter the water.
constant float3 SUNLIGHT = float3(1.0, 0.92, 0.8);
constant float3 SKYLIGHT = float3(0.1, 0.16, 0.26);
// Light bends by this ratio going from air into water.
constant float WATER_N = 1.333;

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// Toward the sun in the sky, from its height in degrees.
float3 sunInAir(constant Params& p) {
    float e = p.sun * TAU / 360.0;
    return float3(0.35 * cos(e), sin(e), 0.94 * cos(e));
}

// Under water Snell's law bends it toward straight up.
float3 sunInWater(constant Params& p) {
    float3 s = sunInAir(p);
    float bent = length(s.xz) / WATER_N;
    float2 across = normalize(s.xz) * bent;
    return float3(across.x, sqrt(1.0 - bent * bent), across.y);
}

// What a meter of water scatters aside, a little more blue.
float3 scatterOf(constant Params& p) {
    return float3(0.012, 0.018, 0.028) * p.murk;
}

// All a meter takes from a beam: absorbed plus scattered.
float3 lossOf(constant Params& p) {
    float3 murky = float3(0.005, 0.004, 0.02) * p.murk;
    return ABSORB + murky + scatterOf(p);
}

// Water scatters mostly forward: Henyey-Greenstein, g = 0.7.
float forward(float mu) {
    float g = 0.7;
    return (1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * mu, 1.5);
}

// The sum of exp(-m s) for s from 0 to len, in closed form.
float along(float m, float len) {
    float x = m * len;
    if (abs(x) < 0.0001) return len;
    return (1.0 - exp(-x)) / m;
}

// Light scattered to the eye along a ray from depth z0.
float3 glow(float z0, float dy, float len, float slant, float3 c) {
    // At s it came slant (z0 - dy s) m down, then s m to the eye.
    float3 m = c * (1.0 - slant * dy);
    float3 sum = float3(along(m.x, len), along(m.y, len),
                        along(m.z, len));
    return exp(-c * slant * z0) * sum;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution / u.resolution.y * 2.0;
    float3 rd = normalize(float3(s.x, s.y + TILT, FOCAL));
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    // The eye is z0 meters under the surface.
    float z0 = p.depth - EYE;

    // The ray ends on the surface, or goes on far down.
    float len = FAR;
    if (rd.y > 0.0) len = z0 / rd.y;

    // The water's own glow: sunlight and skylight scattered.
    float3 water = forward(dot(rd, L)) * SUNLIGHT
                 * glow(z0, rd.y, len, 1.0 / L.y, c);
    water += SKYLIGHT * glow(z0, rd.y, len, 1.2, c);
    water *= scatterOf(p);

    float3 end = float3(0.0);
    if (rd.y > 0.0) {
        // The surface: daylight coming in from above.
        end = 0.5 * SUNLIGHT + 2.0 * SKYLIGHT;
    }
    float3 light = end * exp(-c * len) + water;
    // A number from 0 to 1 that differs from pixel to pixel.
    float2 at = floor(uv * u.resolution);
    float jitter = fract(52.98 * fract(dot(at, float2(0.0671, 0.00584))));

    // The eye opens a little in deeper water.
    float open = 1.3 * exp(0.035 * p.depth);
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    // A speck of noise keeps the deep blues from banding.
    col += (jitter - 0.5) / 255.0;
    return float4(col, 1.0);
}

// ---- The sound ----
// The sea's rumble: noise with nothing above `rate` Hz.
float murmur(float t, float rate, float seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    float h0 = hash21(float2(i, seed)), h1 = hash21(float2(i + 1.0, seed));
    return mix(h0, h1, f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    float tl = loopTime(t);
    float a = TAU * tl / LOOP;
    // Deeper water, a lower rumble, swelling with the waves.
    float low = 10.0 / (5.0 + p.depth);
    float swell = 0.6 + 0.4 * sin(3.0 * a) * sin(5.0 * a + 1.0);
    float2 rumble = float2(
        0.6 * murmur(tl, 90.0 * low, 1.0) + 0.4 * murmur(tl, 230.0 * low, 2.0),
        0.6 * murmur(tl, 90.0 * low, 3.0) + 0.4 * murmur(tl, 230.0 * low, 4.0));
    rumble *= 0.5 * swell;

    // Silence where the minute comes round, so it joins.
    float turn = min(tl, LOOP - tl);
    float fade = 1.0 - exp(-turn * 30.0);
    return tanh(rumble * 1.2) * p.volume * fade;
}

Stage 2 · The sand

A ray going down now ends on the sand, EYE / −rd.y away. sandHeight gives the sand ripples 3.5 cm high: sin(6 x + 9 z), about 58 cm from crest to crest, bent by Flowing Color Field's value noise (vnoise, from its hash21) so they wander, and made 60% to 100% as tall from place to place by more of it. The slope comes from the height 1 cm to each side, and gives the normal n.

Ripples smaller than a pixel would shimmer, so they fade with distance. foot is how many meters of sand a pixel covers there (more where the ray is long and grazing), and keep = exp(−6 · foot) flattens the normal and the 2.5 cm grain (value noise again, ±15%) toward the far sand.

Sunlight reaching the sand has crossed depth / L.y meters of water, 8.6 m at the defaults, which leaves 2.7% of its red, 49% of its green and 60% of its blue, so the cream SAND is lit blue-green. It is lit by max(dot(n, L), 0), the slope facing the sun bright and the one facing away darker, plus the skylight, a little less where the sand slopes. Then, like the surface, the sand is dimmed by the water between it and the eye, exp(−c · len), and the water's glow along the way is added, so far sand is lost in blue and a soft line runs across the picture where it meets the water.

stage-2-the-sand.metal29 new lines since stage 1
// Stage 2 · The sand
// Pale, rippled sand lies `depth` meters down. Its sunlight crossed
// depth / cos(angle) meters of water, and the water between it and
// the eye fades it into the water's own glow, far sand lost in blue.

// @param depth 8 3 20 How deep the sand lies under the surface, in meters
// @param murk 1 0.2 4 How much the water scatters: more is hazier and greener
// @param sun 60 25 90 The sun's height over the horizon, in degrees
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float LOOP = 60.0;
// The eye floats 1.4 m over the sand, looking a little up.
constant float EYE = 1.4;
constant float TILT = 0.35;
constant float FOCAL = 1.1;
constant float FAR = 300.0;
// What a meter of clear water absorbs of red, green, blue.
constant float3 ABSORB = float3(0.4, 0.06, 0.012);
// Sunlight and the sky's light as they enter the water.
constant float3 SUNLIGHT = float3(1.0, 0.92, 0.8);
constant float3 SKYLIGHT = float3(0.1, 0.16, 0.26);
// Light bends by this ratio going from air into water.
constant float WATER_N = 1.333;
// Pale sand, a warm cream.
constant float3 SAND = float3(0.95, 0.86, 0.7);

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

// Value noise: random values on a grid, blended smoothly.
float vnoise(float2 p) {
    float2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash21(i), b = hash21(i + float2(1, 0));
    float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}

float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// Toward the sun in the sky, from its height in degrees.
float3 sunInAir(constant Params& p) {
    float e = p.sun * TAU / 360.0;
    return float3(0.35 * cos(e), sin(e), 0.94 * cos(e));
}

// Under water Snell's law bends it toward straight up.
float3 sunInWater(constant Params& p) {
    float3 s = sunInAir(p);
    float bent = length(s.xz) / WATER_N;
    float2 across = normalize(s.xz) * bent;
    return float3(across.x, sqrt(1.0 - bent * bent), across.y);
}

// What a meter of water scatters aside, a little more blue.
float3 scatterOf(constant Params& p) {
    return float3(0.012, 0.018, 0.028) * p.murk;
}

// All a meter takes from a beam: absorbed plus scattered.
float3 lossOf(constant Params& p) {
    float3 murky = float3(0.005, 0.004, 0.02) * p.murk;
    return ABSORB + murky + scatterOf(p);
}

// Water scatters mostly forward: Henyey-Greenstein, g = 0.7.
float forward(float mu) {
    float g = 0.7;
    return (1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * mu, 1.5);
}

// The sum of exp(-m s) for s from 0 to len, in closed form.
float along(float m, float len) {
    float x = m * len;
    if (abs(x) < 0.0001) return len;
    return (1.0 - exp(-x)) / m;
}

// Light scattered to the eye along a ray from depth z0.
float3 glow(float z0, float dy, float len, float slant, float3 c) {
    // At s it came slant (z0 - dy s) m down, then s m to the eye.
    float3 m = c * (1.0 - slant * dy);
    float3 sum = float3(along(m.x, len), along(m.y, len),
                        along(m.z, len));
    return exp(-c * slant * z0) * sum;
}

// Ripples in the sand, a few centimeters high.
float sandHeight(float2 q) {
    float bend = 1.6 * vnoise(q * 0.35);
    float r = sin(q.x * 6.0 + q.y * 9.0 + bend * 3.0);
    return 0.035 * r * (0.6 + 0.4 * vnoise(q * 1.3));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution / u.resolution.y * 2.0;
    float3 rd = normalize(float3(s.x, s.y + TILT, FOCAL));
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    // The eye is z0 meters under the surface.
    float z0 = p.depth - EYE;

    // The ray ends on the sand, on the surface, or far off.
    float len = FAR;
    if (rd.y < 0.0) len = EYE / -rd.y;
    if (rd.y > 0.0) len = z0 / rd.y;

    // The water's own glow: sunlight and skylight scattered.
    float3 water = forward(dot(rd, L)) * SUNLIGHT
                 * glow(z0, rd.y, len, 1.0 / L.y, c);
    water += SKYLIGHT * glow(z0, rd.y, len, 1.2, c);
    water *= scatterOf(p);

    float3 end = float3(0.0);
    if (rd.y < 0.0) {
        float3 hit = float3(0.0, EYE, 0.0) + rd * len;
        // Ripples fade out where a pixel covers several.
        float foot = len * 2.0 / u.resolution.y / max(-rd.y, 0.05);
        float keep = exp(-foot * 6.0);
        float e = 0.01;
        float h0 = sandHeight(hit.xz);
        float3 n = normalize(float3(
            -keep * (sandHeight(hit.xz + float2(e, 0.0)) - h0) / e, 1.0,
            -keep * (sandHeight(hit.xz + float2(0.0, e)) - h0) / e));
        // Sunlight reaching the sand came depth / L.y meters.
        float3 sun = SUNLIGHT * exp(-c * p.depth / L.y);
        float3 sky = SKYLIGHT * exp(-c * p.depth * 1.2);
        float grain = 0.85 + 0.3 * mix(0.5, vnoise(hit.xz * 40.0), keep);
        float3 lit = sun * max(dot(n, L), 0.0);
        end = SAND * grain * (lit + sky * (0.6 + 0.4 * n.y));
    } else if (rd.y > 0.0) {
        // The surface: daylight coming in from above.
        end = 0.5 * SUNLIGHT + 2.0 * SKYLIGHT;
    }
    float3 light = end * exp(-c * len) + water;
    // A number from 0 to 1 that differs from pixel to pixel.
    float2 at = floor(uv * u.resolution);
    float jitter = fract(52.98 * fract(dot(at, float2(0.0671, 0.00584))));

    // The eye opens a little in deeper water.
    float open = 1.3 * exp(0.035 * p.depth);
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    // A speck of noise keeps the deep blues from banding.
    col += (jitter - 0.5) / 255.0;
    return float4(col, 1.0);
}

// ---- The sound ----
// The sea's rumble: noise with nothing above `rate` Hz.
float murmur(float t, float rate, float seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    float h0 = hash21(float2(i, seed)), h1 = hash21(float2(i + 1.0, seed));
    return mix(h0, h1, f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    float tl = loopTime(t);
    float a = TAU * tl / LOOP;
    // Deeper water, a lower rumble, swelling with the waves.
    float low = 10.0 / (5.0 + p.depth);
    float swell = 0.6 + 0.4 * sin(3.0 * a) * sin(5.0 * a + 1.0);
    float2 rumble = float2(
        0.6 * murmur(tl, 90.0 * low, 1.0) + 0.4 * murmur(tl, 230.0 * low, 2.0),
        0.6 * murmur(tl, 90.0 * low, 3.0) + 0.4 * murmur(tl, 230.0 * low, 4.0));
    rumble *= 0.5 * swell;

    // Silence where the minute comes round, so it joins.
    float turn = min(tl, LOOP - tl);
    float fade = 1.0 - exp(-turn * 30.0);
    return tanh(rumble * 1.2) * p.volume * fade;
}
1 line from stage 1 that are gone
    if (rd.y > 0.0) {

Stage 3 · Caustics on the sand

The waves overhead gather sunlight into a net of bright lines. Working out which waves send light where would take the surface and every ray through it; caustics draws the net directly. Two wave patterns, each warped twice by sines of the other direction, f and g, are each bright where they cross 0: exp(−|f| · 9) is a thin line along every place f is 0, and the two together cross into a net. The warps and patterns move with a, the minute as an angle, 2π · t / 60, at whole numbers of turns a minute (3 to 7), so the net comes round in 60 seconds. Its lines average 0.24.

Each point of sand reads the net where its own sunlight came through the surface: top = hit.xz + L.xz · depth / L.y, the point followed back up along the sun's slanted path. Then focus = 1 + caustics · 0.5 · (k / 0.24 − 1): at the line's average it is 1, on a line more, between lines less. The waves only move light about, so on average the sand is as bright with caustics as without. At caustics 2 all of the light is in the lines; at 0 the sand is plain. Far off, where a pixel covers several lines, k is blended to its average by exp(−4 · foot), so the far sand doesn't sparkle.

stage-3-caustics-on-the-sand.metal19 new lines since stage 2
// Stage 3 · Caustics on the sand
// Waves gather sunlight into a moving net of bright lines: here two
// warped wave patterns, bright where they cross zero. Each point of
// sand reads the net where its sunlight came in.

// @param depth 8 3 20 How deep the sand lies under the surface, in meters
// @param murk 1 0.2 4 How much the water scatters: more is hazier and greener
// @param sun 60 25 90 The sun's height over the horizon, in degrees
// @param caustics 1 0 2 How much of the sunlight the waves gather into bright lines: 2 is all of it
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float LOOP = 60.0;
// The eye floats 1.4 m over the sand, looking a little up.
constant float EYE = 1.4;
constant float TILT = 0.35;
constant float FOCAL = 1.1;
constant float FAR = 300.0;
// What a meter of clear water absorbs of red, green, blue.
constant float3 ABSORB = float3(0.4, 0.06, 0.012);
// Sunlight and the sky's light as they enter the water.
constant float3 SUNLIGHT = float3(1.0, 0.92, 0.8);
constant float3 SKYLIGHT = float3(0.1, 0.16, 0.26);
// Light bends by this ratio going from air into water.
constant float WATER_N = 1.333;
// Pale sand, a warm cream.
constant float3 SAND = float3(0.95, 0.86, 0.7);

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

// Value noise: random values on a grid, blended smoothly.
float vnoise(float2 p) {
    float2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash21(i), b = hash21(i + float2(1, 0));
    float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}

float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// Toward the sun in the sky, from its height in degrees.
float3 sunInAir(constant Params& p) {
    float e = p.sun * TAU / 360.0;
    return float3(0.35 * cos(e), sin(e), 0.94 * cos(e));
}

// Under water Snell's law bends it toward straight up.
float3 sunInWater(constant Params& p) {
    float3 s = sunInAir(p);
    float bent = length(s.xz) / WATER_N;
    float2 across = normalize(s.xz) * bent;
    return float3(across.x, sqrt(1.0 - bent * bent), across.y);
}

// What a meter of water scatters aside, a little more blue.
float3 scatterOf(constant Params& p) {
    return float3(0.012, 0.018, 0.028) * p.murk;
}

// All a meter takes from a beam: absorbed plus scattered.
float3 lossOf(constant Params& p) {
    float3 murky = float3(0.005, 0.004, 0.02) * p.murk;
    return ABSORB + murky + scatterOf(p);
}

// Water scatters mostly forward: Henyey-Greenstein, g = 0.7.
float forward(float mu) {
    float g = 0.7;
    return (1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * mu, 1.5);
}

// The sum of exp(-m s) for s from 0 to len, in closed form.
float along(float m, float len) {
    float x = m * len;
    if (abs(x) < 0.0001) return len;
    return (1.0 - exp(-x)) / m;
}

// Light scattered to the eye along a ray from depth z0.
float3 glow(float z0, float dy, float len, float slant, float3 c) {
    // At s it came slant (z0 - dy s) m down, then s m to the eye.
    float3 m = c * (1.0 - slant * dy);
    float3 sum = float3(along(m.x, len), along(m.y, len),
                        along(m.z, len));
    return exp(-c * slant * z0) * sum;
}

// Ripples in the sand, a few centimeters high.
float sandHeight(float2 q) {
    float bend = 1.6 * vnoise(q * 0.35);
    float r = sin(q.x * 6.0 + q.y * 9.0 + bend * 3.0);
    return 0.035 * r * (0.6 + 0.4 * vnoise(q * 1.3));
}

// Bright lines where waves focus sunlight, averaging 0.24.
float caustics(float2 q, float a, float sharp) {
    // Two wave patterns, warped, each bright where it is 0.
    float2 w = q;
    w += 0.5 * float2(sin(1.3 * w.y + 5.0 * a), sin(1.1 * w.x - 4.0 * a));
    w += 0.3 * float2(sin(2.3 * w.y - 7.0 * a), sin(2.1 * w.x + 6.0 * a));
    float f = sin(w.x) * sin(0.9 * w.y + 1.3);
    f += 0.6 * sin(1.7 * (w.x + w.y) + 3.0 * a);
    float2 v = q * 1.37 + 3.1;
    v += 0.5 * float2(sin(1.2 * v.y - 4.0 * a), sin(1.4 * v.x + 5.0 * a));
    v += 0.3 * float2(sin(2.2 * v.y + 6.0 * a), sin(2.4 * v.x - 7.0 * a));
    float g = sin(v.x) * sin(1.1 * v.y + 0.4);
    g += 0.6 * sin(1.6 * (v.x - v.y) - 3.0 * a);
    return exp(-abs(f) * sharp) + exp(-abs(g) * sharp);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution / u.resolution.y * 2.0;
    float3 rd = normalize(float3(s.x, s.y + TILT, FOCAL));
    float t = loopTime(u.time);
    float a = TAU * t / LOOP;
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    // The eye is z0 meters under the surface.
    float z0 = p.depth - EYE;

    // The ray ends on the sand, on the surface, or far off.
    float len = FAR;
    if (rd.y < 0.0) len = EYE / -rd.y;
    if (rd.y > 0.0) len = z0 / rd.y;

    // The water's own glow: sunlight and skylight scattered.
    float3 water = forward(dot(rd, L)) * SUNLIGHT
                 * glow(z0, rd.y, len, 1.0 / L.y, c);
    water += SKYLIGHT * glow(z0, rd.y, len, 1.2, c);
    water *= scatterOf(p);

    float3 end = float3(0.0);
    if (rd.y < 0.0) {
        float3 hit = float3(0.0, EYE, 0.0) + rd * len;
        // Ripples fade out where a pixel covers several.
        float foot = len * 2.0 / u.resolution.y / max(-rd.y, 0.05);
        float keep = exp(-foot * 6.0);
        float e = 0.01;
        float h0 = sandHeight(hit.xz);
        float3 n = normalize(float3(
            -keep * (sandHeight(hit.xz + float2(e, 0.0)) - h0) / e, 1.0,
            -keep * (sandHeight(hit.xz + float2(0.0, e)) - h0) / e));
        // Sunlight reaching the sand came depth / L.y meters.
        float3 sun = SUNLIGHT * exp(-c * p.depth / L.y);
        float3 sky = SKYLIGHT * exp(-c * p.depth * 1.2);
        float grain = 0.85 + 0.3 * mix(0.5, vnoise(hit.xz * 40.0), keep);
        // The lines where this sunlight came through the surface.
        float2 top = hit.xz + L.xz * p.depth / L.y;
        float k = mix(0.24, caustics(top * 1.5, a, 9.0), exp(-foot * 4.0));
        float focus = 1.0 + p.caustics * 0.5 * (k / 0.24 - 1.0);
        float3 lit = sun * max(dot(n, L), 0.0) * focus;
        end = SAND * grain * (lit + sky * (0.6 + 0.4 * n.y));
    } else if (rd.y > 0.0) {
        // The surface: daylight coming in from above.
        end = 0.5 * SUNLIGHT + 2.0 * SKYLIGHT;
    }
    float3 light = end * exp(-c * len) + water;
    // A number from 0 to 1 that differs from pixel to pixel.
    float2 at = floor(uv * u.resolution);
    float jitter = fract(52.98 * fract(dot(at, float2(0.0671, 0.00584))));

    // The eye opens a little in deeper water.
    float open = 1.3 * exp(0.035 * p.depth);
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    // A speck of noise keeps the deep blues from banding.
    col += (jitter - 0.5) / 255.0;
    return float4(col, 1.0);
}

// ---- The sound ----
// The sea's rumble: noise with nothing above `rate` Hz.
float murmur(float t, float rate, float seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    float h0 = hash21(float2(i, seed)), h1 = hash21(float2(i + 1.0, seed));
    return mix(h0, h1, f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    float tl = loopTime(t);
    float a = TAU * tl / LOOP;
    // Deeper water, a lower rumble, swelling with the waves.
    float low = 10.0 / (5.0 + p.depth);
    float swell = 0.6 + 0.4 * sin(3.0 * a) * sin(5.0 * a + 1.0);
    float2 rumble = float2(
        0.6 * murmur(tl, 90.0 * low, 1.0) + 0.4 * murmur(tl, 230.0 * low, 2.0),
        0.6 * murmur(tl, 90.0 * low, 3.0) + 0.4 * murmur(tl, 230.0 * low, 4.0));
    rumble *= 0.5 * swell;

    // Silence where the minute comes round, so it joins.
    float turn = min(tl, LOOP - tl);
    float fade = 1.0 - exp(-turn * 30.0);
    return tanh(rumble * 1.2) * p.volume * fade;
}
1 line from stage 2 that are gone
        float3 lit = sun * max(dot(n, L), 0.0);

Stage 4 · Shafts from the surface

Water under a bright line holds more light than water under a dark one, so the net shows in the water too, as shafts. shaftLight takes 32 steps along the first 20 m of each ray. At each it follows the sun's path back up to the surface, as the sand did, and reads a softer net there (sharpness 4, whose lines average 0.51): k = caustics(…) / 0.51 − 1 is how far above or below average the light at that point is, positive under a line and negative between. Each step adds k times the light that came down to it and goes on to the eye, exp(−c · (z / L.y + s)), and the sum is scattered and turned toward the eye as the glow was.

Because k averages 0, the shafts move the water's light about without adding to it: at shafts 0 and 1 the water above the sand has the same average brightness. Each shaft lies along the sun's direction under water, so in the picture they all fan out from where the sun is, and they wave and drift as the net does.

32 steps would leave bands where a shaft falls between them. As in Lighthouse, each pixel starts its steps a different part of a step along (jitter, Jorge Jimenez's interleaved gradient noise, which spreads those parts evenly over nearby pixels), and the bands turn into grain too fine to notice. The same jitter is the speck of noise in the colors.

stage-4-shafts-from-the-surface.metal17 new lines since stage 3
// Stage 4 · Shafts from the surface
// The shafts are the same net, seen in the water: 32 steps along each
// ray read the lines where their sunlight came in. Water under a
// bright line scatters more, so streaks fan out from the sun.

// @param depth 8 3 20 How deep the sand lies under the surface, in meters
// @param murk 1 0.2 4 How much the water scatters: more is hazier and greener
// @param sun 60 25 90 The sun's height over the horizon, in degrees
// @param caustics 1 0 2 How much of the sunlight the waves gather into bright lines: 2 is all of it
// @param shafts 0.8 0 1 How much of the sunlight in the water gathers into shafts: 1 is all of it
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float LOOP = 60.0;
// The eye floats 1.4 m over the sand, looking a little up.
constant float EYE = 1.4;
constant float TILT = 0.35;
constant float FOCAL = 1.1;
constant float FAR = 300.0;
// What a meter of clear water absorbs of red, green, blue.
constant float3 ABSORB = float3(0.4, 0.06, 0.012);
// Sunlight and the sky's light as they enter the water.
constant float3 SUNLIGHT = float3(1.0, 0.92, 0.8);
constant float3 SKYLIGHT = float3(0.1, 0.16, 0.26);
// Light bends by this ratio going from air into water.
constant float WATER_N = 1.333;
// Pale sand, a warm cream.
constant float3 SAND = float3(0.95, 0.86, 0.7);

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

// Value noise: random values on a grid, blended smoothly.
float vnoise(float2 p) {
    float2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash21(i), b = hash21(i + float2(1, 0));
    float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}

float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// Toward the sun in the sky, from its height in degrees.
float3 sunInAir(constant Params& p) {
    float e = p.sun * TAU / 360.0;
    return float3(0.35 * cos(e), sin(e), 0.94 * cos(e));
}

// Under water Snell's law bends it toward straight up.
float3 sunInWater(constant Params& p) {
    float3 s = sunInAir(p);
    float bent = length(s.xz) / WATER_N;
    float2 across = normalize(s.xz) * bent;
    return float3(across.x, sqrt(1.0 - bent * bent), across.y);
}

// What a meter of water scatters aside, a little more blue.
float3 scatterOf(constant Params& p) {
    return float3(0.012, 0.018, 0.028) * p.murk;
}

// All a meter takes from a beam: absorbed plus scattered.
float3 lossOf(constant Params& p) {
    float3 murky = float3(0.005, 0.004, 0.02) * p.murk;
    return ABSORB + murky + scatterOf(p);
}

// Water scatters mostly forward: Henyey-Greenstein, g = 0.7.
float forward(float mu) {
    float g = 0.7;
    return (1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * mu, 1.5);
}

// The sum of exp(-m s) for s from 0 to len, in closed form.
float along(float m, float len) {
    float x = m * len;
    if (abs(x) < 0.0001) return len;
    return (1.0 - exp(-x)) / m;
}

// Light scattered to the eye along a ray from depth z0.
float3 glow(float z0, float dy, float len, float slant, float3 c) {
    // At s it came slant (z0 - dy s) m down, then s m to the eye.
    float3 m = c * (1.0 - slant * dy);
    float3 sum = float3(along(m.x, len), along(m.y, len),
                        along(m.z, len));
    return exp(-c * slant * z0) * sum;
}

// Ripples in the sand, a few centimeters high.
float sandHeight(float2 q) {
    float bend = 1.6 * vnoise(q * 0.35);
    float r = sin(q.x * 6.0 + q.y * 9.0 + bend * 3.0);
    return 0.035 * r * (0.6 + 0.4 * vnoise(q * 1.3));
}

// Bright lines where waves focus sunlight, averaging 0.24.
float caustics(float2 q, float a, float sharp) {
    // Two wave patterns, warped, each bright where it is 0.
    float2 w = q;
    w += 0.5 * float2(sin(1.3 * w.y + 5.0 * a), sin(1.1 * w.x - 4.0 * a));
    w += 0.3 * float2(sin(2.3 * w.y - 7.0 * a), sin(2.1 * w.x + 6.0 * a));
    float f = sin(w.x) * sin(0.9 * w.y + 1.3);
    f += 0.6 * sin(1.7 * (w.x + w.y) + 3.0 * a);
    float2 v = q * 1.37 + 3.1;
    v += 0.5 * float2(sin(1.2 * v.y - 4.0 * a), sin(1.4 * v.x + 5.0 * a));
    v += 0.3 * float2(sin(2.2 * v.y + 6.0 * a), sin(2.4 * v.x - 7.0 * a));
    float g = sin(v.x) * sin(1.1 * v.y + 0.4);
    g += 0.6 * sin(1.6 * (v.x - v.y) - 3.0 * a);
    return exp(-abs(f) * sharp) + exp(-abs(g) * sharp);
}

// Shafts: the same lines, read all along the ray.
float3 shaftLight(float3 rd, float len, float3 L, float a, float jitter,
                  constant Params& p) {
    float3 c = lossOf(p);
    float reach = min(len, 20.0);
    float ds = reach / 32.0;
    float3 sum = float3(0.0);
    for (int i = 0; i < 32; i++) {
        float s = (float(i) + jitter) * ds;
        float3 x = float3(0.0, EYE, 0.0) + rd * s;
        float z = p.depth - x.y;
        // Back up the sun's path to where it came in.
        float2 top = x.xz + L.xz * z / L.y;
        // Softer lines, above or below their average of 0.51.
        float k = caustics(top * 1.5, a, 4.0) / 0.51 - 1.0;
        sum += exp(-c * (z / L.y + s)) * k * ds;
    }
    return sum * scatterOf(p) * forward(dot(rd, L)) * SUNLIGHT;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution / u.resolution.y * 2.0;
    float3 rd = normalize(float3(s.x, s.y + TILT, FOCAL));
    float t = loopTime(u.time);
    float a = TAU * t / LOOP;
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    // The eye is z0 meters under the surface.
    float z0 = p.depth - EYE;

    // The ray ends on the sand, on the surface, or far off.
    float len = FAR;
    if (rd.y < 0.0) len = EYE / -rd.y;
    if (rd.y > 0.0) len = z0 / rd.y;

    // The water's own glow: sunlight and skylight scattered.
    float3 water = forward(dot(rd, L)) * SUNLIGHT
                 * glow(z0, rd.y, len, 1.0 / L.y, c);
    water += SKYLIGHT * glow(z0, rd.y, len, 1.2, c);
    water *= scatterOf(p);

    float3 end = float3(0.0);
    if (rd.y < 0.0) {
        float3 hit = float3(0.0, EYE, 0.0) + rd * len;
        // Ripples fade out where a pixel covers several.
        float foot = len * 2.0 / u.resolution.y / max(-rd.y, 0.05);
        float keep = exp(-foot * 6.0);
        float e = 0.01;
        float h0 = sandHeight(hit.xz);
        float3 n = normalize(float3(
            -keep * (sandHeight(hit.xz + float2(e, 0.0)) - h0) / e, 1.0,
            -keep * (sandHeight(hit.xz + float2(0.0, e)) - h0) / e));
        // Sunlight reaching the sand came depth / L.y meters.
        float3 sun = SUNLIGHT * exp(-c * p.depth / L.y);
        float3 sky = SKYLIGHT * exp(-c * p.depth * 1.2);
        float grain = 0.85 + 0.3 * mix(0.5, vnoise(hit.xz * 40.0), keep);
        // The lines where this sunlight came through the surface.
        float2 top = hit.xz + L.xz * p.depth / L.y;
        float k = mix(0.24, caustics(top * 1.5, a, 9.0), exp(-foot * 4.0));
        float focus = 1.0 + p.caustics * 0.5 * (k / 0.24 - 1.0);
        float3 lit = sun * max(dot(n, L), 0.0) * focus;
        end = SAND * grain * (lit + sky * (0.6 + 0.4 * n.y));
    } else if (rd.y > 0.0) {
        // The surface: daylight coming in from above.
        end = 0.5 * SUNLIGHT + 2.0 * SKYLIGHT;
    }
    float3 light = end * exp(-c * len) + water;
    // A number from 0 to 1 that differs from pixel to pixel.
    float2 at = floor(uv * u.resolution);
    float jitter = fract(52.98 * fract(dot(at, float2(0.0671, 0.00584))));
    // Shafts: each pixel starts its steps a different bit along.
    light += p.shafts * shaftLight(rd, len, L, a, jitter, p);

    // The eye opens a little in deeper water.
    float open = 1.3 * exp(0.035 * p.depth);
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    // A speck of noise keeps the deep blues from banding.
    col += (jitter - 0.5) / 255.0;
    return float4(col, 1.0);
}

// ---- The sound ----
// The sea's rumble: noise with nothing above `rate` Hz.
float murmur(float t, float rate, float seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    float h0 = hash21(float2(i, seed)), h1 = hash21(float2(i + 1.0, seed));
    return mix(h0, h1, f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    float tl = loopTime(t);
    float a = TAU * tl / LOOP;
    // Deeper water, a lower rumble, swelling with the waves.
    float low = 10.0 / (5.0 + p.depth);
    float swell = 0.6 + 0.4 * sin(3.0 * a) * sin(5.0 * a + 1.0);
    float2 rumble = float2(
        0.6 * murmur(tl, 90.0 * low, 1.0) + 0.4 * murmur(tl, 230.0 * low, 2.0),
        0.6 * murmur(tl, 90.0 * low, 3.0) + 0.4 * murmur(tl, 230.0 * low, 4.0));
    rumble *= 0.5 * swell;

    // Silence where the minute comes round, so it joins.
    float turn = min(tl, LOOP - tl);
    float fade = 1.0 - exp(-turn * 30.0);
    return tanh(rumble * 1.2) * p.volume * fade;
}

Stage 5 · Underwater

The finished shader adds the window, the bubbles and the snow.

  • Snell's window. windowLight tilts the surface a little with small waves (a slope of about 0.02, less far off) and bends the ray out through it with refract(rd, −n, 1.333). Past 48.6° from straight up, where sin 48.6° = 1 / 1.333, nothing gets out: refract gives a zero vector, and the surface reflects all the light back down, total internal reflection, as at the wall in Glass Orb. There it shows what the reflected ray sees, the water's own glow going down. Inside the window is the sky, the whole of it squeezed into 97°: pale near its horizon, at the window's edge, bluer overhead. The share reflected even inside is Schlick's, 0.02 + 0.98 · (1 − cos)⁵ with the angle the ray has in the air, as on Ocean Waves' water from above, so the window's rim turns to mirror. The window is the same size at any depth, since its edge is an angle. The sun is a small disc in it, kiln(0.97), with a soft halo; at the default 60° it is above the top of the picture, and a sun 30° or lower shows in the window near its edge, moved about by the waves.
  • Bubbles. Three vents in the sand, 1.9, 3.4 and 5.5 m away, let go of bubbles 2.4, 3 and 3.5 cm in radius, 46, 34 and 27 a minute: releaseTime(k, i) is when bubble k leaves, a random bit late, its randomness hashed from k wrapped to the minute (wrap, from Kiln Floor Tiles), so the same bubbles come round each loop. They rise 0.3 m a second, swaying 5 cm side to side, and are gone just under the surface. On the way up they swell: the water's weight on a bubble h above the sand is about (10 + depth − h) / 10 atmospheres, the volume goes as one over that (Boyle's law), and the radius as its cube root, grow. A bubble reaching the surface from 8 m is about a fifth wider than when it left. Each is a ring of light, a silver rim brighter toward its edge and a gold glint up and to the right, lit by sunlight that came down to its height and dimmed by the water to the eye; the water behind it is dimmed by 30%. bubbles sets how many vents let them go, 0 to 3.
  • Marine snow. Specks of drifting matter in four sheets, 1.5 m to 8 m away, each cut into 30 cm squares. In one square in seven or so a speck sinks through it over 20 seconds, about 1 cm a second, fading in and out, swaying a little; then a new one starts somewhere else in the square, three in a minute. A speck is about 4 mm across, and one smaller than a pixel is drawn a pixel wide, so it doesn't flicker.
the kiln palette and shade(), from the finished shader
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution / u.resolution.y * 2.0;
    float3 rd = normalize(float3(s.x, s.y + TILT, FOCAL));
    float t = loopTime(u.time);
    float a = TAU * t / LOOP;
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    // The eye is z0 meters under the surface.
    float z0 = p.depth - EYE;

    // The ray ends on the sand, on the surface, or far off.
    float len = FAR;
    if (rd.y < 0.0) len = EYE / -rd.y;
    if (rd.y > 0.0) len = z0 / rd.y;

    // The water's own glow: sunlight and skylight scattered.
    float3 water = forward(dot(rd, L)) * SUNLIGHT
                 * glow(z0, rd.y, len, 1.0 / L.y, c);
    water += SKYLIGHT * glow(z0, rd.y, len, 1.2, c);
    water *= scatterOf(p);

    float3 end = float3(0.0);
    if (rd.y < 0.0) {
        float3 hit = float3(0.0, EYE, 0.0) + rd * len;
        // Ripples fade out where a pixel covers several.
        float foot = len * 2.0 / u.resolution.y / max(-rd.y, 0.05);
        float keep = exp(-foot * 6.0);
        float e = 0.01;
        float h0 = sandHeight(hit.xz);
        float3 n = normalize(float3(
            -keep * (sandHeight(hit.xz + float2(e, 0.0)) - h0) / e, 1.0,
            -keep * (sandHeight(hit.xz + float2(0.0, e)) - h0) / e));
        // Sunlight reaching the sand came depth / L.y meters.
        float3 sun = SUNLIGHT * exp(-c * p.depth / L.y);
        float3 sky = SKYLIGHT * exp(-c * p.depth * 1.2);
        float grain = 0.85 + 0.3 * mix(0.5, vnoise(hit.xz * 40.0), keep);
        // The lines where this sunlight came through the surface.
        float2 top = hit.xz + L.xz * p.depth / L.y;
        float k = mix(0.24, caustics(top * 1.5, a, 9.0), exp(-foot * 4.0));
        float focus = 1.0 + p.caustics * 0.5 * (k / 0.24 - 1.0);
        float3 lit = sun * max(dot(n, L), 0.0) * focus;
        end = SAND * grain * (lit + sky * (0.6 + 0.4 * n.y));
    } else if (rd.y > 0.0) {
        end = windowLight(rd, len, a, p);
    }
    float3 light = end * exp(-c * len) + water;
    // A number from 0 to 1 that differs from pixel to pixel.
    float2 at = floor(uv * u.resolution);
    float jitter = fract(52.98 * fract(dot(at, float2(0.0671, 0.00584))));
    // Shafts: each pixel starts its steps a different bit along.
    light += p.shafts * shaftLight(rd, len, L, a, jitter, p);

    // Marine snow sinking, then bubbles rising in front.
    float px = 2.0 / u.resolution.y;
    light += snowAt(s, t, len, a, px, p);
    int streams = int(clamp(floor(p.bubbles + 0.5), 0.0, 3.0));
    for (int i = 2; i >= 0; i--) {
        if (i >= streams) continue;
        float4 b = bubbleAt(s, t, len, 1.5 * px, i, p);
        light = mix(light, light * 0.7 + b.rgb, b.a);
    }

    // The eye opens a little in deeper water.
    float open = 1.3 * exp(0.035 * p.depth);
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    // A speck of noise keeps the deep blues from banding.
    col += (jitter - 0.5) / 255.0;
    return float4(col, 1.0);
}
underwater.metal, the whole file132 new lines since stage 4
// Ray Kiln · Underwater
//
// @episode Underwater
// @length 60
// @variation 30
// @variations 1,2,4,5,8,9,11,12
// @still 21
// @teaches Light absorbed with depth, shafts from the surface, caustics on the sand
// @category Fragment
// @tags underwater, Beer-Lambert law, absorption, scattering, Henyey-Greenstein, caustics, god rays, Snell's window, total internal reflection, procedural sound
// @final Underwater | Bubbles rise from the sand, marine snow drifts down, and the sky shows through a bright window in the surface.
//
// Water takes light away as it goes: each meter keeps exp(-c) of each
// color, and c is about seven times larger for red than for blue. Sunlight
// that has come down through the water is blue, and the water between the
// eye and anything far off adds a glow of its own, the light it scatters
// toward the eye, worked out in closed form along each ray. The sand lies
// a few meters down. Waves on the surface focus sunlight into a moving net
// of bright lines on it, and the same net, read along the light's slanted
// path, lights shafts in the water. Every motion makes whole cycles in a
// minute, so the picture loops.
// Each @param line below becomes a slider in the host app and a row in the page's parameters table:
//   // @param name default min max description

// @param depth 8 3 20 How deep the sand lies under the surface, in meters
// @param murk 1 0.2 4 How much the water scatters: more is hazier and greener
// @param sun 60 25 90 The sun's height over the horizon, in degrees
// @param caustics 1 0 2 How much of the sunlight the waves gather into bright lines: 2 is all of it
// @param shafts 0.8 0 1 How much of the sunlight in the water gathers into shafts: 1 is all of it
// @param bubbles 3 0 3 How many streams of bubbles rise from the sand
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float LOOP = 60.0;
// The eye floats 1.4 m over the sand, looking a little up.
constant float EYE = 1.4;
constant float TILT = 0.35;
constant float FOCAL = 1.1;
constant float FAR = 300.0;
// What a meter of clear water absorbs of red, green, blue.
constant float3 ABSORB = float3(0.4, 0.06, 0.012);
// Sunlight and the sky's light as they enter the water.
constant float3 SUNLIGHT = float3(1.0, 0.92, 0.8);
constant float3 SKYLIGHT = float3(0.1, 0.16, 0.26);
// Light bends by this ratio going from air into water.
constant float WATER_N = 1.333;
// Pale sand, a warm cream.
constant float3 SAND = float3(0.95, 0.86, 0.7);

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

// Value noise: random values on a grid, blended smoothly.
float vnoise(float2 p) {
    float2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash21(i), b = hash21(i + float2(1, 0));
    float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// x wrapped into 0 to m, so a count repeats each loop.
float wrap(float x, float m) {
    return x - m * floor(x / m);
}

// Toward the sun in the sky, from its height in degrees.
float3 sunInAir(constant Params& p) {
    float e = p.sun * TAU / 360.0;
    return float3(0.35 * cos(e), sin(e), 0.94 * cos(e));
}

// Under water Snell's law bends it toward straight up.
float3 sunInWater(constant Params& p) {
    float3 s = sunInAir(p);
    float bent = length(s.xz) / WATER_N;
    float2 across = normalize(s.xz) * bent;
    return float3(across.x, sqrt(1.0 - bent * bent), across.y);
}

// What a meter of water scatters aside, a little more blue.
float3 scatterOf(constant Params& p) {
    return float3(0.012, 0.018, 0.028) * p.murk;
}

// All a meter takes from a beam: absorbed plus scattered.
float3 lossOf(constant Params& p) {
    float3 murky = float3(0.005, 0.004, 0.02) * p.murk;
    return ABSORB + murky + scatterOf(p);
}

// Water scatters mostly forward: Henyey-Greenstein, g = 0.7.
float forward(float mu) {
    float g = 0.7;
    return (1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * mu, 1.5);
}

// The sum of exp(-m s) for s from 0 to len, in closed form.
float along(float m, float len) {
    float x = m * len;
    if (abs(x) < 0.0001) return len;
    return (1.0 - exp(-x)) / m;
}

// Light scattered to the eye along a ray from depth z0.
float3 glow(float z0, float dy, float len, float slant, float3 c) {
    // At s it came slant (z0 - dy s) m down, then s m to the eye.
    float3 m = c * (1.0 - slant * dy);
    float3 sum = float3(along(m.x, len), along(m.y, len),
                        along(m.z, len));
    return exp(-c * slant * z0) * sum;
}

// Ripples in the sand, a few centimeters high.
float sandHeight(float2 q) {
    float bend = 1.6 * vnoise(q * 0.35);
    float r = sin(q.x * 6.0 + q.y * 9.0 + bend * 3.0);
    return 0.035 * r * (0.6 + 0.4 * vnoise(q * 1.3));
}

// Bright lines where waves focus sunlight, averaging 0.24.
float caustics(float2 q, float a, float sharp) {
    // Two wave patterns, warped, each bright where it is 0.
    float2 w = q;
    w += 0.5 * float2(sin(1.3 * w.y + 5.0 * a), sin(1.1 * w.x - 4.0 * a));
    w += 0.3 * float2(sin(2.3 * w.y - 7.0 * a), sin(2.1 * w.x + 6.0 * a));
    float f = sin(w.x) * sin(0.9 * w.y + 1.3);
    f += 0.6 * sin(1.7 * (w.x + w.y) + 3.0 * a);
    float2 v = q * 1.37 + 3.1;
    v += 0.5 * float2(sin(1.2 * v.y - 4.0 * a), sin(1.4 * v.x + 5.0 * a));
    v += 0.3 * float2(sin(2.2 * v.y + 6.0 * a), sin(2.4 * v.x - 7.0 * a));
    float g = sin(v.x) * sin(1.1 * v.y + 0.4);
    g += 0.6 * sin(1.6 * (v.x - v.y) - 3.0 * a);
    return exp(-abs(f) * sharp) + exp(-abs(g) * sharp);
}

// Shafts: the same lines, read all along the ray.
float3 shaftLight(float3 rd, float len, float3 L, float a, float jitter,
                  constant Params& p) {
    float3 c = lossOf(p);
    float reach = min(len, 20.0);
    float ds = reach / 32.0;
    float3 sum = float3(0.0);
    for (int i = 0; i < 32; i++) {
        float s = (float(i) + jitter) * ds;
        float3 x = float3(0.0, EYE, 0.0) + rd * s;
        float z = p.depth - x.y;
        // Back up the sun's path to where it came in.
        float2 top = x.xz + L.xz * z / L.y;
        // Softer lines, above or below their average of 0.51.
        float k = caustics(top * 1.5, a, 4.0) / 0.51 - 1.0;
        sum += exp(-c * (z / L.y + s)) * k * ds;
    }
    return sum * scatterOf(p) * forward(dot(rd, L)) * SUNLIGHT;
}

// The surface from below: Snell's window.
float3 windowLight(float3 rd, float len, float a, constant Params& p) {
    // Small waves tilt the surface, rippling the window's edge.
    float2 q = rd.xz * len * 2.5;
    float2 tilt = float2(sin(q.x + 1.7 * q.y + 4.0 * a),
                         sin(1.3 * q.y - q.x - 5.0 * a));
    tilt += 0.6 * float2(sin(2.3 * q.y - 1.1 * q.x + 7.0 * a),
                         sin(2.1 * q.x + 0.7 * q.y - 6.0 * a));
    tilt *= 0.022 * exp(-len * 0.05);
    float3 n = normalize(float3(tilt.x, 1.0, tilt.y));
    // Past 48.6 degrees from straight up, none gets out.
    float3 out = refract(rd, -n, WATER_N);
    float3 down = reflect(rd, -n);
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    float3 seen = forward(dot(down, L)) * SUNLIGHT
                * glow(0.0, down.y, FAR, 1.0 / L.y, c);
    seen = (seen + SKYLIGHT * glow(0.0, down.y, FAR, 1.2, c))
         * scatterOf(p);
    if (length(out) < 0.5) return seen;
    // Inside, the sky; more reflected toward the edge.
    float cosOut = max(out.y, 0.0001);
    float r = 0.02 + 0.98 * pow(1.0 - cosOut, 5.0);
    float3 air = mix(float3(2.0, 1.95, 1.8), float3(0.5, 0.8, 1.4),
                     sqrt(cosOut));
    // The sun, broken into glints by the waves.
    float sunDot = dot(out, sunInAir(p));
    air += kiln(0.97) * 12.0 * smoothstep(0.9996, 0.9999, sunDot);
    air += kiln(0.85) * 0.6 * pow(max(sunDot, 0.0), 200.0);
    return mix(air, seen, r);
}

// A vent: across, away, bubble radius, bubbles a minute.
float4 ventOf(int i) {
    if (i == 0) return float4(-0.15, 1.9, 0.024, 46.0);
    if (i == 1) return float4(0.55, 3.4, 0.03, 34.0);
    return float4(-1.1, 5.5, 0.035, 27.0);
}

// When bubble k leaves the sand, a random bit late.
float releaseTime(float k, int i) {
    float4 v = ventOf(i);
    // Hashing k wrapped to the loop repeats the same bubbles.
    float jitter = hash21(float2(wrap(k, v.w), float(i) * 7.1));
    return (k + 0.7 * jitter) * LOOP / v.w;
}

// The one bubble of a stream that could be at this height.
float4 bubbleAt(float2 s, float t, float len, float px, int i,
                constant Params& p) {
    float4 v = ventOf(i);
    float gap = LOOP / v.w;
    // Bubbles rise 0.3 m a second: this height, this age.
    float y = (s.y + TILT) * v.y / FOCAL + EYE;
    float k0 = floor((t - y / 0.3) / gap);
    float4 hit = float4(0.0);
    for (int j = -1; j <= 1; j++) {
        float k = k0 + float(j);
        float age = t - releaseTime(k, i);
        float h = 0.3 * age;
        if (age < 0.0 || h > p.depth - 0.02) continue;
        // They swell as the water's weight on them lessens.
        float grow = pow((10.0 + p.depth) / (10.0 + p.depth - h), 0.333);
        float r = v.z * grow * FOCAL / v.y;
        float side = hash21(float2(wrap(k, v.w), 3.3 + float(i)));
        float x = v.x + 0.05 * sin(age * 6.0 + TAU * side);
        float2 at = float2(x, h - EYE) * FOCAL / v.y - float2(0.0, TILT);
        float d = length(s - at) / r;
        float edge = 1.0 - smoothstep(1.0 - px / r, 1.0, d);
        if (edge <= 0.0 || v.y > len) continue;
        // A silver rim, and the sun caught near the top.
        float rim = 0.4 + 2.0 * pow(d, 4.0);
        float2 g = (s - at) / r - float2(0.25, 0.45);
        float glint = exp(-dot(g, g) * 30.0);
        float3 lit = SUNLIGHT * exp(-lossOf(p) * (p.depth - h + v.y));
        hit = float4(lit * rim + kiln(0.92) * glint * lit * 2.0, edge);
    }
    return hit;
}

// Marine snow: specks in four sheets, 1.5 m to 8 m away.
float3 snowAt(float2 s, float t, float len, float a, float px,
              constant Params& p) {
    float3 sum = float3(0.0);
    for (int j = 0; j < 4; j++) {
        float dist = 1.5 * pow(1.75, float(j));
        if (dist > len) break;
        // Each sheet is cut into squares 30 cm across.
        float2 w = (s + float2(0.0, TILT)) * dist / FOCAL / 0.3;
        w += float2(13.1, 7.7) * float(j);
        float2 id = floor(w);
        float h = hash21(id);
        // A speck sinks through its square for 20 s, then a new one.
        float life = fract(t / 20.0 + h);
        float n = wrap(floor(t / 20.0 + h), 3.0);
        float2 r = float2(hash21(id + n * 17.0 + 9.0),
                          hash21(id + n * 31.0 + 5.0));
        if (r.x > 0.15) continue;
        float2 spot = float2(0.2 + 0.6 * r.y, 0.85 - 0.7 * life);
        spot.x += 0.08 * sin(3.0 * a + TAU * h);
        float2 off = (fract(w) - spot) * 0.3 * FOCAL / dist;
        float size = max(0.004 * FOCAL / dist, px);
        float y = EYE + (s.y + TILT) * dist / FOCAL;
        float3 lit = SUNLIGHT * exp(-lossOf(p) * (p.depth - y + dist));
        float speck = exp(-dot(off, off) / (size * size));
        sum += lit * speck * sin(life * 3.14159) * 1.5 * min(px / size, 1.0);
    }
    return sum;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution / u.resolution.y * 2.0;
    float3 rd = normalize(float3(s.x, s.y + TILT, FOCAL));
    float t = loopTime(u.time);
    float a = TAU * t / LOOP;
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    // The eye is z0 meters under the surface.
    float z0 = p.depth - EYE;

    // The ray ends on the sand, on the surface, or far off.
    float len = FAR;
    if (rd.y < 0.0) len = EYE / -rd.y;
    if (rd.y > 0.0) len = z0 / rd.y;

    // The water's own glow: sunlight and skylight scattered.
    float3 water = forward(dot(rd, L)) * SUNLIGHT
                 * glow(z0, rd.y, len, 1.0 / L.y, c);
    water += SKYLIGHT * glow(z0, rd.y, len, 1.2, c);
    water *= scatterOf(p);

    float3 end = float3(0.0);
    if (rd.y < 0.0) {
        float3 hit = float3(0.0, EYE, 0.0) + rd * len;
        // Ripples fade out where a pixel covers several.
        float foot = len * 2.0 / u.resolution.y / max(-rd.y, 0.05);
        float keep = exp(-foot * 6.0);
        float e = 0.01;
        float h0 = sandHeight(hit.xz);
        float3 n = normalize(float3(
            -keep * (sandHeight(hit.xz + float2(e, 0.0)) - h0) / e, 1.0,
            -keep * (sandHeight(hit.xz + float2(0.0, e)) - h0) / e));
        // Sunlight reaching the sand came depth / L.y meters.
        float3 sun = SUNLIGHT * exp(-c * p.depth / L.y);
        float3 sky = SKYLIGHT * exp(-c * p.depth * 1.2);
        float grain = 0.85 + 0.3 * mix(0.5, vnoise(hit.xz * 40.0), keep);
        // The lines where this sunlight came through the surface.
        float2 top = hit.xz + L.xz * p.depth / L.y;
        float k = mix(0.24, caustics(top * 1.5, a, 9.0), exp(-foot * 4.0));
        float focus = 1.0 + p.caustics * 0.5 * (k / 0.24 - 1.0);
        float3 lit = sun * max(dot(n, L), 0.0) * focus;
        end = SAND * grain * (lit + sky * (0.6 + 0.4 * n.y));
    } else if (rd.y > 0.0) {
        end = windowLight(rd, len, a, p);
    }
    float3 light = end * exp(-c * len) + water;
    // A number from 0 to 1 that differs from pixel to pixel.
    float2 at = floor(uv * u.resolution);
    float jitter = fract(52.98 * fract(dot(at, float2(0.0671, 0.00584))));
    // Shafts: each pixel starts its steps a different bit along.
    light += p.shafts * shaftLight(rd, len, L, a, jitter, p);

    // Marine snow sinking, then bubbles rising in front.
    float px = 2.0 / u.resolution.y;
    light += snowAt(s, t, len, a, px, p);
    int streams = int(clamp(floor(p.bubbles + 0.5), 0.0, 3.0));
    for (int i = 2; i >= 0; i--) {
        if (i >= streams) continue;
        float4 b = bubbleAt(s, t, len, 1.5 * px, i, p);
        light = mix(light, light * 0.7 + b.rgb, b.a);
    }

    // The eye opens a little in deeper water.
    float open = 1.3 * exp(0.035 * p.depth);
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    // A speck of noise keeps the deep blues from banding.
    col += (jitter - 0.5) / 255.0;
    return float4(col, 1.0);
}

// ---- The sound ----
// The sea's rumble: noise with nothing above `rate` Hz.
float murmur(float t, float rate, float seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    float h0 = hash21(float2(i, seed)), h1 = hash21(float2(i + 1.0, seed));
    return mix(h0, h1, f) * 2.0 - 1.0;
}

// A bubble's note: Minnaert's 3.26 / radius Hz, sliding up.
float blip(float since, float radius) {
    if (since < 0.0 || since > 0.3) return 0.0;
    float f = 3.26 / radius;
    float env = smoothstep(0.0, 0.004, since) * exp(-since / 0.035);
    return env * sin(TAU * f * (since + 10.0 * since * since));
}

float2 sound(float t, constant Params& p) {
    float tl = loopTime(t);
    float a = TAU * tl / LOOP;
    // Deeper water, a lower rumble, swelling with the waves.
    float low = 10.0 / (5.0 + p.depth);
    float swell = 0.6 + 0.4 * sin(3.0 * a) * sin(5.0 * a + 1.0);
    float2 rumble = float2(
        0.6 * murmur(tl, 90.0 * low, 1.0) + 0.4 * murmur(tl, 230.0 * low, 2.0),
        0.6 * murmur(tl, 90.0 * low, 3.0) + 0.4 * murmur(tl, 230.0 * low, 4.0));
    rumble *= 0.5 * swell;

    // A blip for each bubble the picture lets go.
    float2 bubbles = float2(0.0);
    int streams = int(clamp(floor(p.bubbles + 0.5), 0.0, 3.0));
    for (int i = 0; i < 3; i++) {
        if (i >= streams) continue;
        float4 v = ventOf(i);
        float k = floor(tl * v.w / LOOP);
        float b = blip(tl - releaseTime(k, i), v.z)
                + blip(tl - releaseTime(k - 1.0, i), v.z);
        float pan = 0.5 + 0.6 * v.x * FOCAL / v.y;
        bubbles += b * float2(1.0 - pan, pan) * 0.5;
    }

    // Silence where the minute comes round, so it joins.
    float turn = min(tl, LOOP - tl);
    float fade = 1.0 - exp(-turn * 30.0);
    return tanh((rumble + bubbles) * 1.2) * p.volume * fade;
}
2 lines from stage 4 that are gone
        end = 0.5 * SUNLIGHT + 2.0 * SKYLIGHT;
⋯
    return tanh(rumble * 1.2) * p.volume * fade;

The sound

The sound is the sea at this depth. Its rumble is murmur: a random value from hash21 at each step of the time, rate steps a second, joined smoothly, so there is almost nothing in it above rate Hz. Two of them are mixed, at 90 and 230 times 10 / (5 + depth) steps a second, 69 and 177 at the default 8 m: deeper water, a lower rumble. Each ear has its own, so the rumble is wide. It swells and falls with 0.6 + 0.4 · sin(3a) · sin(5a + 1), the waves overhead, three and five times a minute.

Over it, a blip for each bubble the picture lets go, at the moment it leaves the sand: the sound calls the same releaseTime as the picture, so each blip comes with its bubble, 107 a minute with all three vents. A bubble rings at Minnaert's frequency, 3.26 / radius Hz, which gives 136, 109 and 93 Hz for the three vents' bubbles as they leave. Each blip starts within 4 ms and dies away with a time constant of 35 ms, its pitch sliding up as it rings. Each vent's blips are placed left or right as the vent is in the picture.

Everything goes through tanh(1.2 · …) before volume, and fades to silence over a few hundredths of a second at each end of the minute, so the first and last samples are 0 and the sound loops at 60 seconds with the picture. Over the first 20 seconds at the defaults the peak is −7.4 dBFS and the RMS −20.2 dBFS; over the whole minute, −6.7 dBFS and −18.9 dBFS.

New in Ray Kiln

Play backwards. The playground's speed menu, beside Sound, now also runs the clock backwards, at −¼×, −½×, −1× and −2×; [ steps down past ¼× into them and ] back up. Each frame moves the clock back by the time it would have gone forward, so a frame reached backwards is the frame drawn forward at that moment. With no loop the clock runs down to 0 and holds there; with a loop set on the clock (I and O, or the Loop menu) it goes from the in point back round to the out point. The sound is silent until the speed is forward again. It works for any shader without state between frames; a particle, cells or feedback shader builds each frame on the last, so it keeps the forward speeds only. Exports stay forward at 1×.

This shader can run backwards because it is a pure function of the time: every frame is worked out fresh from u.time and the sliders, with nothing carried over, and loopTime wraps the time into the minute. Open Underwater in the playground, at 40 seconds, and choose −1× in the speed menu. The bubbles sink back down into the sand, each vanishing into its vent at the moment it left, and shrink a little on the way as the water's weight on them grows, since the code grows their radius by Boyle's law on the way up. The marine snow rises through the water, and the net of lines on the sand runs backwards.

Try this

  • Set depth to 3: the window turns nearly white, the water a grayer blue, and the lines on the sand bright and pale. Set it to 20: the water goes deep blue and the sand blue with it. The window is the same size at both.
  • Set murk to 4: the water turns green and hazy, the shafts thick, and the sand dim. At 0.2 it is a clear dark navy, and the far sand meets it in a sharp line.
  • Set sun to 25: the sun shows as a bright disc near the window's edge, and the shafts fan out from it across the picture.
  • Set caustics to 0: the sand is plain, with only its ripples. The shafts stay, since they read their own net.
  • Set shafts to 0: the streaks are gone and the water is an even glow, as bright on average as before.
  • Change ABSORB to float3(0.012, 0.012, 0.012), every color absorbed as little as blue: the water turns gray-white and the sand a warm cream-gold.
  • Change WATER_N to 1.0: light no longer bends at the surface, and the window is gone; the whole surface shows the sky.
  • In shaftLight, change caustics(top * 1.5, a, 4.0) / 0.51 to caustics(top * 1.5, a, 9.0) / 0.24, the sand's own sharp net and its average: the shafts turn thinner and grainier.
  • In the playground, choose −1× in the speed menu beside Sound and watch the bubbles sink back into the sand.

Parameters

ParameterDefaultRangeWhat it does
depth83 to 20How deep the sand lies under the surface, in meters
murk10.2 to 4How much the water scatters: more is hazier and greener
sun6025 to 90The sun's height over the horizon, in degrees
caustics10 to 2How much of the sunlight the waves gather into bright lines: 2 is all of it
shafts0.80 to 1How much of the sunlight in the water gathers into shafts: 1 is all of it
bubbles30 to 3How many streams of bubbles rise from the sand
volume0.80 to 1Loudness of the sound

More from this shader

The same shader 8 more ways: each from a different moment, with different settings, one after another. Each chapter below says which settings moved most, then lists them all.

Wallpapers

A still from the shader, rendered at full size for a desktop or a phone screen. Free to use as your wallpaper.

Clips to post

Fifteen seconds of the shader with its sound, sized for posting: square for feeds, vertical for stories and short videos. Free to post, ideally with a link to this page.

The full source

This is the whole episode: the picture, the parameters and the sound.

underwater.metal
// Ray Kiln · Underwater
//
// @episode Underwater
// @length 60
// @variation 30
// @variations 1,2,4,5,8,9,11,12
// @still 21
// @teaches Light absorbed with depth, shafts from the surface, caustics on the sand
// @category Fragment
// @tags underwater, Beer-Lambert law, absorption, scattering, Henyey-Greenstein, caustics, god rays, Snell's window, total internal reflection, procedural sound
// @final Underwater | Bubbles rise from the sand, marine snow drifts down, and the sky shows through a bright window in the surface.
//
// Water takes light away as it goes: each meter keeps exp(-c) of each
// color, and c is about seven times larger for red than for blue. Sunlight
// that has come down through the water is blue, and the water between the
// eye and anything far off adds a glow of its own, the light it scatters
// toward the eye, worked out in closed form along each ray. The sand lies
// a few meters down. Waves on the surface focus sunlight into a moving net
// of bright lines on it, and the same net, read along the light's slanted
// path, lights shafts in the water. Every motion makes whole cycles in a
// minute, so the picture loops.
// Each @param line below becomes a slider in the host app and a row in the page's parameters table:
//   // @param name default min max description

// @param depth 8 3 20 How deep the sand lies under the surface, in meters
// @param murk 1 0.2 4 How much the water scatters: more is hazier and greener
// @param sun 60 25 90 The sun's height over the horizon, in degrees
// @param caustics 1 0 2 How much of the sunlight the waves gather into bright lines: 2 is all of it
// @param shafts 0.8 0 1 How much of the sunlight in the water gathers into shafts: 1 is all of it
// @param bubbles 3 0 3 How many streams of bubbles rise from the sand
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float LOOP = 60.0;
// The eye floats 1.4 m over the sand, looking a little up.
constant float EYE = 1.4;
constant float TILT = 0.35;
constant float FOCAL = 1.1;
constant float FAR = 300.0;
// What a meter of clear water absorbs of red, green, blue.
constant float3 ABSORB = float3(0.4, 0.06, 0.012);
// Sunlight and the sky's light as they enter the water.
constant float3 SUNLIGHT = float3(1.0, 0.92, 0.8);
constant float3 SKYLIGHT = float3(0.1, 0.16, 0.26);
// Light bends by this ratio going from air into water.
constant float WATER_N = 1.333;
// Pale sand, a warm cream.
constant float3 SAND = float3(0.95, 0.86, 0.7);

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

// Value noise: random values on a grid, blended smoothly.
float vnoise(float2 p) {
    float2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash21(i), b = hash21(i + float2(1, 0));
    float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// x wrapped into 0 to m, so a count repeats each loop.
float wrap(float x, float m) {
    return x - m * floor(x / m);
}

// Toward the sun in the sky, from its height in degrees.
float3 sunInAir(constant Params& p) {
    float e = p.sun * TAU / 360.0;
    return float3(0.35 * cos(e), sin(e), 0.94 * cos(e));
}

// Under water Snell's law bends it toward straight up.
float3 sunInWater(constant Params& p) {
    float3 s = sunInAir(p);
    float bent = length(s.xz) / WATER_N;
    float2 across = normalize(s.xz) * bent;
    return float3(across.x, sqrt(1.0 - bent * bent), across.y);
}

// What a meter of water scatters aside, a little more blue.
float3 scatterOf(constant Params& p) {
    return float3(0.012, 0.018, 0.028) * p.murk;
}

// All a meter takes from a beam: absorbed plus scattered.
float3 lossOf(constant Params& p) {
    float3 murky = float3(0.005, 0.004, 0.02) * p.murk;
    return ABSORB + murky + scatterOf(p);
}

// Water scatters mostly forward: Henyey-Greenstein, g = 0.7.
float forward(float mu) {
    float g = 0.7;
    return (1.0 - g * g) / pow(1.0 + g * g - 2.0 * g * mu, 1.5);
}

// The sum of exp(-m s) for s from 0 to len, in closed form.
float along(float m, float len) {
    float x = m * len;
    if (abs(x) < 0.0001) return len;
    return (1.0 - exp(-x)) / m;
}

// Light scattered to the eye along a ray from depth z0.
float3 glow(float z0, float dy, float len, float slant, float3 c) {
    // At s it came slant (z0 - dy s) m down, then s m to the eye.
    float3 m = c * (1.0 - slant * dy);
    float3 sum = float3(along(m.x, len), along(m.y, len),
                        along(m.z, len));
    return exp(-c * slant * z0) * sum;
}

// Ripples in the sand, a few centimeters high.
float sandHeight(float2 q) {
    float bend = 1.6 * vnoise(q * 0.35);
    float r = sin(q.x * 6.0 + q.y * 9.0 + bend * 3.0);
    return 0.035 * r * (0.6 + 0.4 * vnoise(q * 1.3));
}

// Bright lines where waves focus sunlight, averaging 0.24.
float caustics(float2 q, float a, float sharp) {
    // Two wave patterns, warped, each bright where it is 0.
    float2 w = q;
    w += 0.5 * float2(sin(1.3 * w.y + 5.0 * a), sin(1.1 * w.x - 4.0 * a));
    w += 0.3 * float2(sin(2.3 * w.y - 7.0 * a), sin(2.1 * w.x + 6.0 * a));
    float f = sin(w.x) * sin(0.9 * w.y + 1.3);
    f += 0.6 * sin(1.7 * (w.x + w.y) + 3.0 * a);
    float2 v = q * 1.37 + 3.1;
    v += 0.5 * float2(sin(1.2 * v.y - 4.0 * a), sin(1.4 * v.x + 5.0 * a));
    v += 0.3 * float2(sin(2.2 * v.y + 6.0 * a), sin(2.4 * v.x - 7.0 * a));
    float g = sin(v.x) * sin(1.1 * v.y + 0.4);
    g += 0.6 * sin(1.6 * (v.x - v.y) - 3.0 * a);
    return exp(-abs(f) * sharp) + exp(-abs(g) * sharp);
}

// Shafts: the same lines, read all along the ray.
float3 shaftLight(float3 rd, float len, float3 L, float a, float jitter,
                  constant Params& p) {
    float3 c = lossOf(p);
    float reach = min(len, 20.0);
    float ds = reach / 32.0;
    float3 sum = float3(0.0);
    for (int i = 0; i < 32; i++) {
        float s = (float(i) + jitter) * ds;
        float3 x = float3(0.0, EYE, 0.0) + rd * s;
        float z = p.depth - x.y;
        // Back up the sun's path to where it came in.
        float2 top = x.xz + L.xz * z / L.y;
        // Softer lines, above or below their average of 0.51.
        float k = caustics(top * 1.5, a, 4.0) / 0.51 - 1.0;
        sum += exp(-c * (z / L.y + s)) * k * ds;
    }
    return sum * scatterOf(p) * forward(dot(rd, L)) * SUNLIGHT;
}

// The surface from below: Snell's window.
float3 windowLight(float3 rd, float len, float a, constant Params& p) {
    // Small waves tilt the surface, rippling the window's edge.
    float2 q = rd.xz * len * 2.5;
    float2 tilt = float2(sin(q.x + 1.7 * q.y + 4.0 * a),
                         sin(1.3 * q.y - q.x - 5.0 * a));
    tilt += 0.6 * float2(sin(2.3 * q.y - 1.1 * q.x + 7.0 * a),
                         sin(2.1 * q.x + 0.7 * q.y - 6.0 * a));
    tilt *= 0.022 * exp(-len * 0.05);
    float3 n = normalize(float3(tilt.x, 1.0, tilt.y));
    // Past 48.6 degrees from straight up, none gets out.
    float3 out = refract(rd, -n, WATER_N);
    float3 down = reflect(rd, -n);
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    float3 seen = forward(dot(down, L)) * SUNLIGHT
                * glow(0.0, down.y, FAR, 1.0 / L.y, c);
    seen = (seen + SKYLIGHT * glow(0.0, down.y, FAR, 1.2, c))
         * scatterOf(p);
    if (length(out) < 0.5) return seen;
    // Inside, the sky; more reflected toward the edge.
    float cosOut = max(out.y, 0.0001);
    float r = 0.02 + 0.98 * pow(1.0 - cosOut, 5.0);
    float3 air = mix(float3(2.0, 1.95, 1.8), float3(0.5, 0.8, 1.4),
                     sqrt(cosOut));
    // The sun, broken into glints by the waves.
    float sunDot = dot(out, sunInAir(p));
    air += kiln(0.97) * 12.0 * smoothstep(0.9996, 0.9999, sunDot);
    air += kiln(0.85) * 0.6 * pow(max(sunDot, 0.0), 200.0);
    return mix(air, seen, r);
}

// A vent: across, away, bubble radius, bubbles a minute.
float4 ventOf(int i) {
    if (i == 0) return float4(-0.15, 1.9, 0.024, 46.0);
    if (i == 1) return float4(0.55, 3.4, 0.03, 34.0);
    return float4(-1.1, 5.5, 0.035, 27.0);
}

// When bubble k leaves the sand, a random bit late.
float releaseTime(float k, int i) {
    float4 v = ventOf(i);
    // Hashing k wrapped to the loop repeats the same bubbles.
    float jitter = hash21(float2(wrap(k, v.w), float(i) * 7.1));
    return (k + 0.7 * jitter) * LOOP / v.w;
}

// The one bubble of a stream that could be at this height.
float4 bubbleAt(float2 s, float t, float len, float px, int i,
                constant Params& p) {
    float4 v = ventOf(i);
    float gap = LOOP / v.w;
    // Bubbles rise 0.3 m a second: this height, this age.
    float y = (s.y + TILT) * v.y / FOCAL + EYE;
    float k0 = floor((t - y / 0.3) / gap);
    float4 hit = float4(0.0);
    for (int j = -1; j <= 1; j++) {
        float k = k0 + float(j);
        float age = t - releaseTime(k, i);
        float h = 0.3 * age;
        if (age < 0.0 || h > p.depth - 0.02) continue;
        // They swell as the water's weight on them lessens.
        float grow = pow((10.0 + p.depth) / (10.0 + p.depth - h), 0.333);
        float r = v.z * grow * FOCAL / v.y;
        float side = hash21(float2(wrap(k, v.w), 3.3 + float(i)));
        float x = v.x + 0.05 * sin(age * 6.0 + TAU * side);
        float2 at = float2(x, h - EYE) * FOCAL / v.y - float2(0.0, TILT);
        float d = length(s - at) / r;
        float edge = 1.0 - smoothstep(1.0 - px / r, 1.0, d);
        if (edge <= 0.0 || v.y > len) continue;
        // A silver rim, and the sun caught near the top.
        float rim = 0.4 + 2.0 * pow(d, 4.0);
        float2 g = (s - at) / r - float2(0.25, 0.45);
        float glint = exp(-dot(g, g) * 30.0);
        float3 lit = SUNLIGHT * exp(-lossOf(p) * (p.depth - h + v.y));
        hit = float4(lit * rim + kiln(0.92) * glint * lit * 2.0, edge);
    }
    return hit;
}

// Marine snow: specks in four sheets, 1.5 m to 8 m away.
float3 snowAt(float2 s, float t, float len, float a, float px,
              constant Params& p) {
    float3 sum = float3(0.0);
    for (int j = 0; j < 4; j++) {
        float dist = 1.5 * pow(1.75, float(j));
        if (dist > len) break;
        // Each sheet is cut into squares 30 cm across.
        float2 w = (s + float2(0.0, TILT)) * dist / FOCAL / 0.3;
        w += float2(13.1, 7.7) * float(j);
        float2 id = floor(w);
        float h = hash21(id);
        // A speck sinks through its square for 20 s, then a new one.
        float life = fract(t / 20.0 + h);
        float n = wrap(floor(t / 20.0 + h), 3.0);
        float2 r = float2(hash21(id + n * 17.0 + 9.0),
                          hash21(id + n * 31.0 + 5.0));
        if (r.x > 0.15) continue;
        float2 spot = float2(0.2 + 0.6 * r.y, 0.85 - 0.7 * life);
        spot.x += 0.08 * sin(3.0 * a + TAU * h);
        float2 off = (fract(w) - spot) * 0.3 * FOCAL / dist;
        float size = max(0.004 * FOCAL / dist, px);
        float y = EYE + (s.y + TILT) * dist / FOCAL;
        float3 lit = SUNLIGHT * exp(-lossOf(p) * (p.depth - y + dist));
        float speck = exp(-dot(off, off) / (size * size));
        sum += lit * speck * sin(life * 3.14159) * 1.5 * min(px / size, 1.0);
    }
    return sum;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution / u.resolution.y * 2.0;
    float3 rd = normalize(float3(s.x, s.y + TILT, FOCAL));
    float t = loopTime(u.time);
    float a = TAU * t / LOOP;
    float3 c = lossOf(p);
    float3 L = sunInWater(p);
    // The eye is z0 meters under the surface.
    float z0 = p.depth - EYE;

    // The ray ends on the sand, on the surface, or far off.
    float len = FAR;
    if (rd.y < 0.0) len = EYE / -rd.y;
    if (rd.y > 0.0) len = z0 / rd.y;

    // The water's own glow: sunlight and skylight scattered.
    float3 water = forward(dot(rd, L)) * SUNLIGHT
                 * glow(z0, rd.y, len, 1.0 / L.y, c);
    water += SKYLIGHT * glow(z0, rd.y, len, 1.2, c);
    water *= scatterOf(p);

    float3 end = float3(0.0);
    if (rd.y < 0.0) {
        float3 hit = float3(0.0, EYE, 0.0) + rd * len;
        // Ripples fade out where a pixel covers several.
        float foot = len * 2.0 / u.resolution.y / max(-rd.y, 0.05);
        float keep = exp(-foot * 6.0);
        float e = 0.01;
        float h0 = sandHeight(hit.xz);
        float3 n = normalize(float3(
            -keep * (sandHeight(hit.xz + float2(e, 0.0)) - h0) / e, 1.0,
            -keep * (sandHeight(hit.xz + float2(0.0, e)) - h0) / e));
        // Sunlight reaching the sand came depth / L.y meters.
        float3 sun = SUNLIGHT * exp(-c * p.depth / L.y);
        float3 sky = SKYLIGHT * exp(-c * p.depth * 1.2);
        float grain = 0.85 + 0.3 * mix(0.5, vnoise(hit.xz * 40.0), keep);
        // The lines where this sunlight came through the surface.
        float2 top = hit.xz + L.xz * p.depth / L.y;
        float k = mix(0.24, caustics(top * 1.5, a, 9.0), exp(-foot * 4.0));
        float focus = 1.0 + p.caustics * 0.5 * (k / 0.24 - 1.0);
        float3 lit = sun * max(dot(n, L), 0.0) * focus;
        end = SAND * grain * (lit + sky * (0.6 + 0.4 * n.y));
    } else if (rd.y > 0.0) {
        end = windowLight(rd, len, a, p);
    }
    float3 light = end * exp(-c * len) + water;
    // A number from 0 to 1 that differs from pixel to pixel.
    float2 at = floor(uv * u.resolution);
    float jitter = fract(52.98 * fract(dot(at, float2(0.0671, 0.00584))));
    // Shafts: each pixel starts its steps a different bit along.
    light += p.shafts * shaftLight(rd, len, L, a, jitter, p);

    // Marine snow sinking, then bubbles rising in front.
    float px = 2.0 / u.resolution.y;
    light += snowAt(s, t, len, a, px, p);
    int streams = int(clamp(floor(p.bubbles + 0.5), 0.0, 3.0));
    for (int i = 2; i >= 0; i--) {
        if (i >= streams) continue;
        float4 b = bubbleAt(s, t, len, 1.5 * px, i, p);
        light = mix(light, light * 0.7 + b.rgb, b.a);
    }

    // The eye opens a little in deeper water.
    float open = 1.3 * exp(0.035 * p.depth);
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    // A speck of noise keeps the deep blues from banding.
    col += (jitter - 0.5) / 255.0;
    return float4(col, 1.0);
}

// ---- The sound ----
// The sea's rumble: noise with nothing above `rate` Hz.
float murmur(float t, float rate, float seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    float h0 = hash21(float2(i, seed)), h1 = hash21(float2(i + 1.0, seed));
    return mix(h0, h1, f) * 2.0 - 1.0;
}

// A bubble's note: Minnaert's 3.26 / radius Hz, sliding up.
float blip(float since, float radius) {
    if (since < 0.0 || since > 0.3) return 0.0;
    float f = 3.26 / radius;
    float env = smoothstep(0.0, 0.004, since) * exp(-since / 0.035);
    return env * sin(TAU * f * (since + 10.0 * since * since));
}

float2 sound(float t, constant Params& p) {
    float tl = loopTime(t);
    float a = TAU * tl / LOOP;
    // Deeper water, a lower rumble, swelling with the waves.
    float low = 10.0 / (5.0 + p.depth);
    float swell = 0.6 + 0.4 * sin(3.0 * a) * sin(5.0 * a + 1.0);
    float2 rumble = float2(
        0.6 * murmur(tl, 90.0 * low, 1.0) + 0.4 * murmur(tl, 230.0 * low, 2.0),
        0.6 * murmur(tl, 90.0 * low, 3.0) + 0.4 * murmur(tl, 230.0 * low, 4.0));
    rumble *= 0.5 * swell;

    // A blip for each bubble the picture lets go.
    float2 bubbles = float2(0.0);
    int streams = int(clamp(floor(p.bubbles + 0.5), 0.0, 3.0));
    for (int i = 0; i < 3; i++) {
        if (i >= streams) continue;
        float4 v = ventOf(i);
        float k = floor(tl * v.w / LOOP);
        float b = blip(tl - releaseTime(k, i), v.z)
                + blip(tl - releaseTime(k - 1.0, i), v.z);
        float pan = 0.5 + 0.6 * v.x * FOCAL / v.y;
        bubbles += b * float2(1.0 - pan, pan) * 0.5;
    }

    // Silence where the minute comes round, so it joins.
    float turn = min(tl, LOOP - tl);
    float fade = 1.0 - exp(-turn * 30.0);
    return tanh((rumble + bubbles) * 1.2) * p.volume * fade;
}

Running it in your own project

Every Ray Kiln shader is the same shape. The standalone download above is the shader with the small wrapper around it that the Ray Kiln host adds, so it compiles with the ordinary Metal compiler and runs in your own app. It defines three entry points: rk_vertex (a full-screen triangle), rk_fragment (calls the shader's shade) and, for shaders with sound, the compute kernel rk_sound.

To draw it, pass the uniforms at fragment buffer 0 and the parameter values at buffer 1, in the order they are declared:

Drawing it, in Swift
struct Uniforms {
    var resolution: SIMD2<Float>
    var time: Float
    var timeDelta: Float
    var mouse: SIMD2<Float>
    var frame: UInt32
    var pad: UInt32 = 0
}

let library = try device.makeLibrary(source: standaloneSource, options: nil)
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = library.makeFunction(name: "rk_vertex")
descriptor.fragmentFunction = library.makeFunction(name: "rk_fragment")
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
let pipeline = try device.makeRenderPipelineState(descriptor: descriptor)

// Each frame, inside a render pass:
var uniforms = Uniforms(resolution: size, time: time, timeDelta: dt, mouse: mouse, frame: frame)
var params: [Float] = [8, 1, 60, 1, 0.8, 3, 0.8]     // the @param defaults, in the order they are declared
encoder.setRenderPipelineState(pipeline)
encoder.setFragmentBytes(&uniforms, length: MemoryLayout<Uniforms>.stride, index: 0)
encoder.setFragmentBytes(&params, length: params.count * MemoryLayout<Float>.stride, index: 1)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)

Time is in seconds, mouse is in pixels from the bottom left, and uv in the shader runs 0 to 1 with (0, 0) at the bottom left. Write the output as sRGB: the shader's numbers go to the screen as they are.

Built on later

More in Atmosphere