Shader

Sunset

A sky with no colors written into it. Every pixel looks along a ray through a round shell of air and adds up the sunlight the air scatters towards the eye, blue nearly six times as strongly as red. Sunlight that has crossed a lot of air has lost its blue, so the low sun turns orange and red, haze puts a white glow round it, ozone turns the dusk violet, and three rows of hills fade with the air in front of them. The sun sinks under the horizon and rises again once a minute.

· Atmosphere · Fragment shader

Teaches Rayleigh and Mie scattering, a sky from the air it passes through

Builds on Floating 3D Scene, Smoke Stack, Wood & Marble (hash11), Aurora

Watch

The idea

Nothing in this shader says the sky is blue or the sunset is red. It has three numbers for what a kilometer of air scatters of red, green and blue light, a planet, and a sun. The colors come out of adding up.

Sunlight crossing air is scattered a little at a time, in every direction. A pixel looks along a ray and asks, at each step along it, how much sunlight the air there sends towards the eye. Two things decide it: how much air the step holds, and how much of the light survived the trip, first from the sun to the step and then from the step to the eye. Air scatters blue far more than red. So the light that reaches the eye from the side is blue, and the light that has come a long way through air has had its blue taken out. Those are the blue sky and the red sun, from one rule.

It is the stepping of Smoke Stack and Aurora, a ray marched through something with no surface, on the scale of a planet: lengths are in kilometers, the ground is a ball 6,371 km in radius and the air ends 100 km above it. It is built in five steps.

Stage 1 · Air along a ray

The eye stands 300 m up a hill at the top of the planet and looks a little above level. leave finds how far along its ray a pixel leaves the ball of air, and meetGround whether it meets the planet first; reach is the nearer of the two. Both solve the same quadratic for a ray and a ball round the planet's center, with (r − radius) · (r + radius) in place of r² − radius², because the difference of two numbers near forty million loses the few kilometers that matter.

airAlong cuts the ray into 24 steps and adds up the air in each. Air thins with height: exp(−h / 8), so 8 km up there is 37% of it left. The sum is in kilometers of sea-level air, the ray's optical depth before any color comes into it. Straight up it would be about 8. At the top of the picture, 44° above level, it is 11; along the horizon it is over 300, because a level ray stays in the thick air near the ground for hundreds of kilometers. The picture shows that number as gold. Below the horizon the ray stops at the ground, and has crossed little.

stage-1-air-along-a-ray.metal
// Stage 1 · Air along a ray
// The air is a shell 100 km deep round a planet 6,371 km in radius. Each
// pixel looks along a ray and adds up the air on it, in 24 steps: thick
// near the ground, thinner with height. Straight up there are 8 km of it,
// level there are hundreds. The picture is that number.

// @param air 1 0.2 4 How much air there is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// Lengths are in kilometers: the ground's radius and the top of the air.
constant float GROUND = 6371.0;
constant float TOP = 6471.0;
// Air thins with height: 8 km up there is 1/e of it left (about 37%).
constant float AIR_HEIGHT = 8.0;
constant int STEPS = 24;

// How far along the ray it leaves a ball of this radius round the planet.
float leave(float3 from, float3 rd, float radius) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - radius) * (r + radius);
    return -b + sqrt(max(b * b - c, 0.0));
}

// Where it meets the ground, or -1 if it never does.
float meetGround(float3 from, float3 rd) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - GROUND) * (r + GROUND);
    float h = b * b - c;
    if (b > 0.0 || h < 0.0) return -1.0;
    return -b - sqrt(h);
}

// The air along the ray out to `reach` km, as kilometers of sea-level air.
float airAlong(float3 eye, float3 rd, float reach, constant Params& p) {
    float ds = reach / float(STEPS);
    float airDepth = 0.0;
    for (int i = 0; i < STEPS; i++) {
        float3 pos = eye + rd * (float(i) + 0.5) * ds;
        float h = length(pos) - GROUND;
        // How much air this step holds: it thins as it gets higher.
        float airHere = exp(-h / AIR_HEIGHT) * ds * p.air;
        airDepth += airHere;
    }
    return airDepth;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 s = (uv - 0.5) * u.resolution * px;
    // The eye stands 300 m up a hill and looks a little above level.
    float3 eye = float3(0.0, GROUND + 0.3, 0.0);
    float3 rd = normalize(float3(s.x, s.y + 0.55, 1.6));

    // How far the ray goes: to the top of the air, or to the ground.
    float reach = leave(eye, rd, TOP);
    float hit = meetGround(eye, rd);
    if (hit > 0.0) reach = hit;

    float airPath = airAlong(eye, rd, reach, p);
    // More air, more gold: 8 km of it straight up, hundreds level.
    float3 gold = float3(1.0, 0.69, 0.38);
    float3 col = gold * (1.0 - exp(-airPath / 60.0));
    return float4(col, 1.0);
}

// The sound: a chord of ten whole-number partials over 72 Hz, the sunlight
// before the air has touched it.

float2 sound(float t, constant Params& p) {
    float chordL = 0.0, chordR = 0.0;
    for (int k = 1; k <= 10; k++) {
        float f = 72.0 * float(k);
        float level = 1.0 / float(k);
        // Each partial drifts slowly between the ears.
        float pan = 0.5 + 0.35 * sin(float(k) * 2.4 + TAU * t / 60.0);
        float tone = sin(TAU * f * t) * level;
        chordL += tone * (1.0 - pan);
        chordR += tone * pan;
    }
    float swell = 0.75 + 0.25 * sin(TAU * t / 12.0);
    float2 chord = float2(chordL, chordR) * 0.26 * swell;
    float2 all = chord;
    // Silence where the minute comes round, so it joins without a click.
    float turn = fract(t / 60.0);
    float fade = 1.0 - exp(-min(turn, 1.0 - turn) * 60.0 * 30.0);
    return tanh(all * 1.4) * p.volume * fade;
}

Stage 2 · Rayleigh: the blue

RAYLEIGH is what a kilometer of sea-level air scatters: 0.58% of the red light crossing it, 1.35% of the green, 3.31% of the blue. Molecules are much smaller than the waves of light, and scattering that small goes with the fourth power of the frequency, which is why blue gets nearly six times what red gets.

skylight now adds, at each step, the light its air sends to the eye: airHere, times what is left of that light after the air between the step and the eye, exp(−RAYLEIGH · airDepth), a number for each color. At the end it is multiplied by RAYLEIGH (blue is scattered most, so most of what arrives is blue) and by the phase function, 3/(16π) · (1 + μ²), where μ is the cosine of the angle between the ray and the sun: air sends as much light back as on, and half as much to the sides. 1 − exp(−light) keeps bright light from clipping, and the power of 1/2.2 is the screen's curve.

The sky is blue, and pale along the horizon, where so much air is in the way that every color has been scattered and the sum comes out near white. The sun moves, 18° up at the start and 4° under the horizon half a minute later, but nothing reddens: its light arrives as bright wherever it comes from, even through the ground.

stage-2-rayleigh-the-blue.metal35 new lines since stage 1
// Stage 2 · Rayleigh: the blue
// Air molecules scatter sunlight in every direction, and blue nearly six
// times as strongly as red: Rayleigh scattering. Each step of the ray adds
// the sunlight its air sends towards the eye. The sky comes out blue, and
// pale near the horizon where there is so much air that every color has
// been scattered. The sun moves, but its light is still as bright
// wherever it comes from.

// @param height 7 -4 50 The sun's middle height over the horizon, in degrees
// @param swing 11 0 25 How far the sun rises and sinks from there, in degrees
// @param air 1 0.2 4 How much air there is: Rayleigh scattering, the blue and the red
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The sun goes down and comes back once in this many seconds.
constant float LOOP = 60.0;
// Lengths are in kilometers: the ground's radius and the top of the air.
constant float GROUND = 6371.0;
constant float TOP = 6471.0;
// Air thins with height: 8 km up there is 1/e of it left (about 37%).
constant float AIR_HEIGHT = 8.0;
// What a kilometer of sea-level air scatters of red, green and blue.
constant float3 RAYLEIGH = float3(0.0058, 0.0135, 0.0331);
constant float SUN_POWER = 18.0;
constant int STEPS = 24;

// How far along the ray it leaves a ball of this radius round the planet.
float leave(float3 from, float3 rd, float radius) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - radius) * (r + radius);
    return -b + sqrt(max(b * b - c, 0.0));
}

// Where it meets the ground, or -1 if it never does.
float meetGround(float3 from, float3 rd) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - GROUND) * (r + GROUND);
    float h = b * b - c;
    if (b > 0.0 || h < 0.0) return -1.0;
    return -b - sqrt(h);
}

// The sun's height at time t, in radians: it swings once a loop.
float sunHeight(float t, constant Params& p) {
    return (p.height + p.swing * cos(TAU * t / LOOP)) * PI / 180.0;
}

float3 sunAt(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // It slides a little sideways as it sinks, as a real sunset does.
    float a = 0.35 * (e - p.height * PI / 180.0);
    return normalize(float3(sin(a) * cos(e), sin(e), cos(a) * cos(e)));
}

// The sunlight the air scatters towards the eye along the ray. `through`
// is the share of each color that crosses it unscattered.
float3 skylight(float3 eye, float3 rd, float reach, float3 sun,
                constant Params& p, thread float3& through,
                thread float& airPath) {
    float ds = reach / float(STEPS);
    float airDepth = 0.0;
    float3 airLight = float3(0.0);
    for (int i = 0; i < STEPS; i++) {
        float3 pos = eye + rd * (float(i) + 0.5) * ds;
        float h = length(pos) - GROUND;
        // How much air this step holds: it thins as it gets higher.
        float airHere = exp(-h / AIR_HEIGHT) * ds * p.air;
        airDepth += airHere;
        // Light from here loses some of each color on its way to the eye.
        float3 lost = RAYLEIGH * airDepth;
        float3 left = exp(-lost);
        airLight += airHere * left;
    }
    through = exp(-RAYLEIGH * airDepth);
    airPath = airDepth;
    // Air sends as much light back as on, and half as much to the sides.
    float mu = dot(rd, sun);
    float airPhase = 3.0 / (16.0 * PI) * (1.0 + mu * mu);
    return SUN_POWER * airLight * RAYLEIGH * airPhase;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 s = (uv - 0.5) * u.resolution * px;
    // The eye stands 300 m up a hill and looks a little above level.
    float3 eye = float3(0.0, GROUND + 0.3, 0.0);
    float3 rd = normalize(float3(s.x, s.y + 0.55, 1.6));
    float3 sun = sunAt(u.time, p);

    // How far the ray goes: to the top of the air, or to the ground.
    float reach = leave(eye, rd, TOP);
    float hit = meetGround(eye, rd);
    if (hit > 0.0) reach = hit;

    float3 through = float3(1.0);
    float airPath = 0.0;
    float3 light = skylight(eye, rd, reach, sun, p, through, airPath);

    // Bright light goes to white, then the screen's curve.
    float3 col = 1.0 - exp(-light);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// The sound: the air takes the chord's high partials first, as it takes
// blue: each fades by its frequency to the fourth power.

float2 sound(float t, constant Params& p) {
    float mass = 3.0;
    float chordL = 0.0, chordR = 0.0;
    for (int k = 1; k <= 10; k++) {
        float f = 72.0 * float(k);
        float ratio = f / 720.0;
        float r4 = ratio * ratio * ratio * ratio;
        float kept = exp(-0.11 * p.air * mass * r4);
        float level = kept / float(k);
        // Each partial drifts slowly between the ears.
        float pan = 0.5 + 0.35 * sin(float(k) * 2.4 + TAU * t / 60.0);
        float tone = sin(TAU * f * t) * level;
        chordL += tone * (1.0 - pan);
        chordR += tone * pan;
    }
    float swell = 0.75 + 0.25 * sin(TAU * t / 12.0);
    float2 chord = float2(chordL, chordR) * 0.26 * swell;
    float2 all = chord;
    // Silence where the minute comes round, so it joins without a click.
    float turn = fract(t / 60.0);
    float fade = 1.0 - exp(-min(turn, 1.0 - turn) * 60.0 * 30.0);
    return tanh(all * 1.4) * p.volume * fade;
}
6 lines from stage 1 that are gone
float airAlong(float3 eye, float3 rd, float reach, constant Params& p) {
⋯
    return airDepth;
⋯
    float airPath = airAlong(eye, rd, reach, p);
⋯
    float3 gold = float3(1.0, 0.69, 0.38);
    float3 col = gold * (1.0 - exp(-airPath / 60.0));
⋯
        float level = 1.0 / float(k);

Stage 3 · The light's own path

The light had a trip of its own before it reached the ray. So each of the 24 steps looks towards the sun and adds up the air on that line too, in 8 steps (sunAir), and what is lost is now RAYLEIGH · (airDepth + sunAir): both stretches together. With the sun high, that second stretch is short and nothing changes. With the sun low, its light skims the ground for hundreds of kilometers before it gets to the ray, and arrives with almost no blue and little green. What the air then sends to the eye is orange along the horizon, and the sky overhead goes dim.

The planet's shadow needs no test of its own. A line towards a sun below the horizon dips under the ground, and there the height is negative and exp(−h / 8) grows fast (the height is held at −40 km so it can't overflow): the sum becomes huge and nothing is left of the light. The sun's disc is drawn where the ray points within about a degree and a half of it, over five times its real width so that it reads on a screen, and it is multiplied by through, what crosses the whole ray unscattered: that is why the disc itself turns yellow as it goes down.

stage-3-the-light-s-own-path.metal15 new lines since stage 2
// Stage 3 · The light's own path
// Sunlight has crossed air before it reaches a step of the ray, and lost
// blue there too. So each step looks towards the sun and adds up that air
// as well. A high sun crosses little; a low one crosses hundreds of
// kilometers and arrives orange, then red. Below the horizon its light
// would have to cross the ground: the planet's shadow rises.

// @param height 7 -4 50 The sun's middle height over the horizon, in degrees
// @param swing 11 0 25 How far the sun rises and sinks from there, in degrees
// @param air 1 0.2 4 How much air there is: Rayleigh scattering, the blue and the red
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The sun goes down and comes back once in this many seconds.
constant float LOOP = 60.0;
// Lengths are in kilometers: the ground's radius and the top of the air.
constant float GROUND = 6371.0;
constant float TOP = 6471.0;
// Air thins with height: 8 km up there is 1/e of it left (about 37%).
constant float AIR_HEIGHT = 8.0;
// What a kilometer of sea-level air scatters of red, green and blue.
constant float3 RAYLEIGH = float3(0.0058, 0.0135, 0.0331);
constant float SUN_POWER = 18.0;
constant int STEPS = 24;
constant int SUN_STEPS = 8;

// How far along the ray it leaves a ball of this radius round the planet.
float leave(float3 from, float3 rd, float radius) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - radius) * (r + radius);
    return -b + sqrt(max(b * b - c, 0.0));
}

// Where it meets the ground, or -1 if it never does.
float meetGround(float3 from, float3 rd) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - GROUND) * (r + GROUND);
    float h = b * b - c;
    if (b > 0.0 || h < 0.0) return -1.0;
    return -b - sqrt(h);
}

// The sun's height at time t, in radians: it swings once a loop.
float sunHeight(float t, constant Params& p) {
    return (p.height + p.swing * cos(TAU * t / LOOP)) * PI / 180.0;
}

float3 sunAt(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // It slides a little sideways as it sinks, as a real sunset does.
    float a = 0.35 * (e - p.height * PI / 180.0);
    return normalize(float3(sin(a) * cos(e), sin(e), cos(a) * cos(e)));
}

// The sunlight the air scatters towards the eye along the ray. `through`
// is the share of each color that crosses it unscattered.
float3 skylight(float3 eye, float3 rd, float reach, float3 sun,
                constant Params& p, thread float3& through,
                thread float& airPath) {
    float ds = reach / float(STEPS);
    float airDepth = 0.0;
    float3 airLight = float3(0.0);
    for (int i = 0; i < STEPS; i++) {
        float3 pos = eye + rd * (float(i) + 0.5) * ds;
        float h = length(pos) - GROUND;
        // How much air this step holds: it thins as it gets higher.
        float airHere = exp(-h / AIR_HEIGHT) * ds * p.air;
        airDepth += airHere;
        // The same sum from here towards the sun: what its light crossed.
        float sunDs = leave(pos, sun, TOP) / float(SUN_STEPS);
        float sunAir = 0.0;
        for (int j = 0; j < SUN_STEPS; j++) {
            float3 q = pos + sun * (float(j) + 0.5) * sunDs;
            // Under the ground the air gets thick fast: the planet's shadow.
            float qh = max(length(q) - GROUND, -40.0);
            sunAir += exp(-qh / AIR_HEIGHT) * sunDs * p.air;
        }
        // The light loses some of each color on both stretches.
        float3 lost = RAYLEIGH * (airDepth + sunAir);
        float3 left = exp(-lost);
        airLight += airHere * left;
    }
    through = exp(-RAYLEIGH * airDepth);
    airPath = airDepth;
    // Air sends as much light back as on, and half as much to the sides.
    float mu = dot(rd, sun);
    float airPhase = 3.0 / (16.0 * PI) * (1.0 + mu * mu);
    return SUN_POWER * airLight * RAYLEIGH * airPhase;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 s = (uv - 0.5) * u.resolution * px;
    // The eye stands 300 m up a hill and looks a little above level.
    float3 eye = float3(0.0, GROUND + 0.3, 0.0);
    float3 rd = normalize(float3(s.x, s.y + 0.55, 1.6));
    float3 sun = sunAt(u.time, p);

    // How far the ray goes: to the top of the air, or to the ground.
    float reach = leave(eye, rd, TOP);
    float land = 0.0;
    float hit = meetGround(eye, rd);
    if (hit > 0.0) { reach = hit; land = 1.0; }

    float3 through = float3(1.0);
    float airPath = 0.0;
    float3 light = skylight(eye, rd, reach, sun, p, through, airPath);
    // The sun's disc, over five times its real width, seen through the air.
    float disc = smoothstep(0.99955, 0.99975, dot(rd, sun));
    light += (1.0 - land) * disc * through * SUN_POWER * 4.0;

    // Bright light goes to white, then the screen's curve.
    float3 col = 1.0 - exp(-light);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// The sound: the lower the sun, the more air its light crosses, and the
// more of the chord's high partials are gone.

float2 sound(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // The air the sun's light crosses, 1 overhead and about 38 level.
    float mass = 1.0 / (max(sin(e), 0.0) + 0.026);
    float chordL = 0.0, chordR = 0.0;
    for (int k = 1; k <= 10; k++) {
        float f = 72.0 * float(k);
        float ratio = f / 720.0;
        float r4 = ratio * ratio * ratio * ratio;
        float kept = exp(-0.11 * p.air * mass * r4);
        float level = kept / float(k);
        // Each partial drifts slowly between the ears.
        float pan = 0.5 + 0.35 * sin(float(k) * 2.4 + TAU * t / 60.0);
        float tone = sin(TAU * f * t) * level;
        chordL += tone * (1.0 - pan);
        chordR += tone * pan;
    }
    float swell = 0.75 + 0.25 * sin(TAU * t / 12.0);
    float2 chord = float2(chordL, chordR) * 0.26 * swell;
    float2 all = chord;
    // Silence where the minute comes round, so it joins without a click.
    float turn = fract(t / 60.0);
    float fade = 1.0 - exp(-min(turn, 1.0 - turn) * 60.0 * 30.0);
    return tanh(all * 1.4) * p.volume * fade;
}
3 lines from stage 2 that are gone
        float3 lost = RAYLEIGH * airDepth;
⋯
    if (hit > 0.0) reach = hit;
⋯
    float mass = 3.0;

Stage 4 · Mie: the haze

Dust and droplets are bigger than the waves of light, and scatter differently: every color alike (MIE, 0.4% a kilometer), and most of it nearly straight on. Haze stays low, with 37% of it left 1.2 km up. It gets its own sums beside the air's (hazeDepth, sunHaze, hazeLight) and its own phase function, Henyey and Greenstein's: with glare at 0.76, a ray pointing at the sun gets several hundred times the light of one pointing away. That is the white glow round the sun, which the air alone can't make. The 1.1 on its loss is for the light haze absorbs as well as scatters.

stage-4-mie-the-haze.metal31 new lines since stage 3
// Stage 4 · Mie: the haze
// Dust and droplets are bigger than the waves of light. They scatter every
// color alike, and most of it nearly straight on: Mie scattering. Haze
// stays in the lowest kilometer or two. It makes the white glow round the
// sun and the pale band along the horizon.

// @param height 7 -4 50 The sun's middle height over the horizon, in degrees
// @param swing 11 0 25 How far the sun rises and sinks from there, in degrees
// @param air 1 0.2 4 How much air there is: Rayleigh scattering, the blue and the red
// @param haze 1 0 6 How much haze there is: Mie scattering, the glow round the sun
// @param glare 0.76 0 0.95 How much of the haze's light goes straight on
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The sun goes down and comes back once in this many seconds.
constant float LOOP = 60.0;
// Lengths are in kilometers: the ground's radius and the top of the air.
constant float GROUND = 6371.0;
constant float TOP = 6471.0;
// Air thins with height: 8 km up there is 1/e of it left (about 37%).
constant float AIR_HEIGHT = 8.0;
// Haze stays low: 1.2 km up there is 1/e of it left.
constant float HAZE_HEIGHT = 1.2;
// What a kilometer of sea-level air scatters of red, green and blue.
constant float3 RAYLEIGH = float3(0.0058, 0.0135, 0.0331);
// What a kilometer of haze scatters, of every color alike.
constant float MIE = 0.004;
constant float SUN_POWER = 18.0;
constant int STEPS = 24;
constant int SUN_STEPS = 8;

float hash11(float n) {
    return fract(sin(n * 12.9898) * 43758.5453);
}

// How far along the ray it leaves a ball of this radius round the planet.
float leave(float3 from, float3 rd, float radius) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - radius) * (r + radius);
    return -b + sqrt(max(b * b - c, 0.0));
}

// Where it meets the ground, or -1 if it never does.
float meetGround(float3 from, float3 rd) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - GROUND) * (r + GROUND);
    float h = b * b - c;
    if (b > 0.0 || h < 0.0) return -1.0;
    return -b - sqrt(h);
}

// The sun's height at time t, in radians: it swings once a loop.
float sunHeight(float t, constant Params& p) {
    return (p.height + p.swing * cos(TAU * t / LOOP)) * PI / 180.0;
}

float3 sunAt(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // It slides a little sideways as it sinks, as a real sunset does.
    float a = 0.35 * (e - p.height * PI / 180.0);
    return normalize(float3(sin(a) * cos(e), sin(e), cos(a) * cos(e)));
}

// The sunlight the air scatters towards the eye along the ray. `through`
// is the share of each color that crosses it unscattered.
float3 skylight(float3 eye, float3 rd, float reach, float3 sun,
                constant Params& p, thread float3& through,
                thread float& airPath) {
    float ds = reach / float(STEPS);
    float airDepth = 0.0, hazeDepth = 0.0;
    float3 airLight = float3(0.0), hazeLight = float3(0.0);
    for (int i = 0; i < STEPS; i++) {
        float3 pos = eye + rd * (float(i) + 0.5) * ds;
        float h = length(pos) - GROUND;
        // How much air this step holds: it thins as it gets higher.
        float airHere = exp(-h / AIR_HEIGHT) * ds * p.air;
        airDepth += airHere;
        float hazeHere = exp(-h / HAZE_HEIGHT) * ds * p.haze;
        hazeDepth += hazeHere;
        // The same sum from here towards the sun: what its light crossed.
        float sunDs = leave(pos, sun, TOP) / float(SUN_STEPS);
        float sunAir = 0.0, sunHaze = 0.0;
        for (int j = 0; j < SUN_STEPS; j++) {
            float3 q = pos + sun * (float(j) + 0.5) * sunDs;
            // Under the ground the air gets thick fast: the planet's shadow.
            float qh = max(length(q) - GROUND, -40.0);
            sunAir += exp(-qh / AIR_HEIGHT) * sunDs * p.air;
            sunHaze += exp(-qh / HAZE_HEIGHT) * sunDs * p.haze;
        }
        // The light loses some of each color on both stretches.
        float3 lost = RAYLEIGH * (airDepth + sunAir)
                    + MIE * 1.1 * (hazeDepth + sunHaze);
        float3 left = exp(-lost);
        airLight += airHere * left;
        hazeLight += hazeHere * left;
    }
    through = exp(-(RAYLEIGH * airDepth + MIE * 1.1 * hazeDepth));
    airPath = airDepth;
    // Air sends as much light back as on, and half as much to the sides.
    float mu = dot(rd, sun);
    float airPhase = 3.0 / (16.0 * PI) * (1.0 + mu * mu);
    // Haze sends most of its light nearly straight on.
    float g = p.glare;
    float hazePhase = (1.0 - g * g)
        / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * mu, 1.5));
    return SUN_POWER * (airLight * RAYLEIGH * airPhase
                        + hazeLight * MIE * hazePhase);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 s = (uv - 0.5) * u.resolution * px;
    // The eye stands 300 m up a hill and looks a little above level.
    float3 eye = float3(0.0, GROUND + 0.3, 0.0);
    float3 rd = normalize(float3(s.x, s.y + 0.55, 1.6));
    float3 sun = sunAt(u.time, p);

    // How far the ray goes: to the top of the air, or to the ground.
    float reach = leave(eye, rd, TOP);
    float land = 0.0;
    float hit = meetGround(eye, rd);
    if (hit > 0.0) { reach = hit; land = 1.0; }

    float3 through = float3(1.0);
    float airPath = 0.0;
    float3 light = skylight(eye, rd, reach, sun, p, through, airPath);
    // The sun's disc, over five times its real width, seen through the air.
    float disc = smoothstep(0.99955, 0.99975, dot(rd, sun));
    light += (1.0 - land) * disc * through * SUN_POWER * 4.0;

    // Bright light goes to white, then the screen's curve.
    float3 col = 1.0 - exp(-light);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// The sound: the haze is wind, noise with the highs taken off, under the
// chord.

// Noise with nothing above about `rate` Hz in it, from hashes of the time.
float wind(float t, float rate) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    return mix(hash11(i), hash11(i + 1.0), f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // The air the sun's light crosses, 1 overhead and about 38 level.
    float mass = 1.0 / (max(sin(e), 0.0) + 0.026);
    float chordL = 0.0, chordR = 0.0;
    for (int k = 1; k <= 10; k++) {
        float f = 72.0 * float(k);
        float ratio = f / 720.0;
        float r4 = ratio * ratio * ratio * ratio;
        float kept = exp(-0.11 * p.air * mass * r4);
        float level = kept / float(k);
        // Each partial drifts slowly between the ears.
        float pan = 0.5 + 0.35 * sin(float(k) * 2.4 + TAU * t / 60.0);
        float tone = sin(TAU * f * t) * level;
        chordL += tone * (1.0 - pan);
        chordR += tone * pan;
    }
    float swell = 0.75 + 0.25 * sin(TAU * t / 12.0);
    float2 chord = float2(chordL, chordR) * 0.26 * swell;

    float gust = 0.6 + 0.4 * sin(TAU * t / 20.0 + 1.0);
    float hiss = 0.6 * wind(t, 900.0) + 0.4 * wind(t + 7.3, 2600.0);
    float2 air = float2(hiss, 0.6 * hiss + 0.4 * wind(t + 3.1, 1400.0));
    air *= min(p.haze, 3.0) * 0.045 * gust;

    float2 all = chord + air;
    // Silence where the minute comes round, so it joins without a click.
    float turn = fract(t / 60.0);
    float fade = 1.0 - exp(-min(turn, 1.0 - turn) * 60.0 * 30.0);
    return tanh(all * 1.4) * p.volume * fade;
}
7 lines from stage 3 that are gone
    float airDepth = 0.0;
    float3 airLight = float3(0.0);
⋯
        float sunAir = 0.0;
⋯
        float3 lost = RAYLEIGH * (airDepth + sunAir);
⋯
    through = exp(-RAYLEIGH * airDepth);
⋯
    return SUN_POWER * airLight * RAYLEIGH * airPhase;
⋯
    float2 all = chord;

Stage 5 · Sunset

Three things finish it. Ozone, a layer thickest 25 km up, absorbs orange and green and scatters nothing (OZONE, ozoneLayer). By day it hardly shows. At dusk the light that still reaches the high air has run a long way through that layer, and what it takes out leaves the sky violet instead of gray.

The hills are three outlines of smooth noise along the horizon, at 3, 9 and 25 km. A ray under an outline stops there: reach is that distance, and the land itself is black. What you see of a hill is only the light the air in front of it scatters, so the far row is paler and bluer than the near one by day, and all three go dark at dusk. That is aerial perspective, with no fog color chosen for it. Within a pixel of an outline, other is how far the ray would go on the outline's other side (the sky or a farther hill behind it, or the hill itself just below), and the pixel works out that light too and mixes the two, so the edge is smooth.

The eye opens as the light goes: the exposure rises to six times as the sun sinks from 8° to 6° under the horizon, or the dusk would be nearly black beside the day. height and swing set where the sun swings, air and haze how much of each there is, and the minute loops: the frame at 60 s is the first frame.

shade(), from the finished shader
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 s = (uv - 0.5) * u.resolution * px;
    // The eye stands 300 m up a hill and looks a little above level.
    float3 eye = float3(0.0, GROUND + 0.3, 0.0);
    float3 rd = normalize(float3(s.x, s.y + 0.55, 1.6));
    float3 sun = sunAt(u.time, p);

    // How far the ray goes: to the top of the air, or to the ground.
    float reach = leave(eye, rd, TOP);
    float land = 0.0;
    float hit = meetGround(eye, rd);
    if (hit > 0.0) { reach = hit; land = 1.0; }
    // Or to one of three rows of hills, 3, 9 and 25 km away.
    float up = asin(rd.y);
    float around = atan2(rd.x, rd.z);
    // Within a pixel of an outline, `other` is how far the ray would go
    // on its other side.
    float edge = 1.0, other = reach;
    for (int row = 2; row >= 0; row--) {
        float over = up - hills(around, float(row));
        float away = row == 0 ? 3.0 : (row == 1 ? 9.0 : 25.0);
        float close = min(abs(over) / (px * 0.6), 1.0);
        if (over < 0.0) {
            other = reach;
            edge = close;
            reach = away;
            land = 1.0;
        } else if (close < edge) {
            other = away;
            edge = close;
        }
    }

    float3 through = float3(1.0);
    float airPath = 0.0;
    float3 light = skylight(eye, rd, reach, sun, p, through, airPath);
    // The sun's disc, over five times its real width, seen through the air.
    float disc = smoothstep(0.99955, 0.99975, dot(rd, sun));
    light += (1.0 - land) * disc * through * SUN_POWER * 4.0;

    // On an outline, mix in the other side's light, so the edge is smooth.
    if (edge < 1.0) {
        float3 through2 = float3(1.0);
        float path2 = 0.0;
        float3 light2 = skylight(eye, rd, other, sun, p, through2, path2);
        // Only open sky is more than 99 km deep: the disc shows there.
        light2 += step(99.0, other) * disc * through2 * SUN_POWER * 4.0;
        light = mix(light2, light, 0.5 + 0.5 * edge);
    }

    // The eye opens as the light goes: up to six times as the sun sets.
    float low = 1.0 - smoothstep(-0.1, 0.14, sunHeight(u.time, p));
    float open = p.exposure * (1.0 + 5.0 * low * low);
    // Bright light goes to white, then the screen's curve.
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}
sunset.metal, the whole file57 new lines since stage 4
// Ray Kiln · Sunset
//
// @episode Sunset
// @length 60
// @variation 30
// @variations 1,2,3,4,7,8,10,11
// @sweeps height, air, haze
// @still 18
// @teaches Rayleigh and Mie scattering, a sky from the air it passes through
// @category Fragment
// @tags atmospheric scattering, Rayleigh scattering, Mie scattering, optical depth, raymarching, sky, procedural sound
// @final Sunset | Ozone turns the dusk violet, hills stand in the haze, and the eye opens as the light goes.
//
// A sky with no colors written into it. Every pixel looks along a ray
// through a round shell of air, 100 km deep on a planet 6,371 km in radius,
// and adds up the sunlight the air throws towards the eye. Air molecules
// scatter blue nearly six times as strongly as red (Rayleigh), so the sky
// is blue, and sunlight that crosses a lot of air has lost its
// blue, so a low sun is red. Haze scatters every color alike and mostly
// straight on (Mie), which makes the white glow round the sun. The sun
// sinks under the horizon and rises again once a minute.
// 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 height 7 -4 50 The sun's middle height over the horizon, in degrees
// @param swing 11 0 25 How far the sun rises and sinks from there, in degrees
// @param air 1 0.2 4 How much air there is: Rayleigh scattering, the blue and the red
// @param haze 1 0 6 How much haze there is: Mie scattering, the glow round the sun
// @param glare 0.76 0 0.95 How much of the haze's light goes straight on
// @param exposure 1 0.25 4 How bright the picture is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The sun goes down and comes back once in this many seconds.
constant float LOOP = 60.0;
// Lengths are in kilometers: the ground's radius and the top of the air.
constant float GROUND = 6371.0;
constant float TOP = 6471.0;
// Air thins with height: 8 km up there is 1/e of it left (about 37%).
constant float AIR_HEIGHT = 8.0;
// Haze stays low: 1.2 km up there is 1/e of it left.
constant float HAZE_HEIGHT = 1.2;
// What a kilometer of sea-level air scatters of red, green and blue.
constant float3 RAYLEIGH = float3(0.0058, 0.0135, 0.0331);
// What a kilometer of haze scatters, of every color alike.
constant float MIE = 0.004;
// What a kilometer of the ozone layer absorbs: mostly orange and green.
constant float3 OZONE = float3(0.00065, 0.00188, 0.000085);
constant float SUN_POWER = 18.0;
constant int STEPS = 24;
constant int SUN_STEPS = 8;

float hash11(float n) {
    return fract(sin(n * 12.9898) * 43758.5453);
}

// Smooth noise along a line: a random height at each whole number.
float ridgeNoise(float x) {
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    return mix(hash11(i), hash11(i + 1.0), f);
}

// How far along the ray it leaves a ball of this radius round the planet.
float leave(float3 from, float3 rd, float radius) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - radius) * (r + radius);
    return -b + sqrt(max(b * b - c, 0.0));
}

// Where it meets the ground, or -1 if it never does.
float meetGround(float3 from, float3 rd) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - GROUND) * (r + GROUND);
    float h = b * b - c;
    if (b > 0.0 || h < 0.0) return -1.0;
    return -b - sqrt(h);
}

// The sun's height at time t, in radians: it swings once a loop.
float sunHeight(float t, constant Params& p) {
    return (p.height + p.swing * cos(TAU * t / LOOP)) * PI / 180.0;
}

float3 sunAt(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // It slides a little sideways as it sinks, as a real sunset does.
    float a = 0.35 * (e - p.height * PI / 180.0);
    return normalize(float3(sin(a) * cos(e), sin(e), cos(a) * cos(e)));
}

// Ozone at a height: most 25 km up, none 15 km from that.
float ozoneLayer(float h) {
    return max(1.0 - abs(h - 25.0) / 15.0, 0.0);
}

// A row of hills' outline: how high it stands, as an angle.
float hills(float around, float row) {
    float x = around * (9.0 + 5.0 * row) + row * 31.7;
    float h = ridgeNoise(x) + 0.5 * ridgeNoise(x * 2.3 + 4.1);
    h += 0.22 * ridgeNoise(x * 5.9 + 9.3);
    return 0.006 + (0.05 - 0.013 * row) * h * 0.6;
}

// The sunlight the air scatters towards the eye along the ray. `through`
// is the share of each color that crosses it unscattered.
float3 skylight(float3 eye, float3 rd, float reach, float3 sun,
                constant Params& p, thread float3& through,
                thread float& airPath) {
    float ds = reach / float(STEPS);
    float airDepth = 0.0, hazeDepth = 0.0, ozoneDepth = 0.0;
    float3 airLight = float3(0.0), hazeLight = float3(0.0);
    for (int i = 0; i < STEPS; i++) {
        float3 pos = eye + rd * (float(i) + 0.5) * ds;
        float h = length(pos) - GROUND;
        // How much air this step holds: it thins as it gets higher.
        float airHere = exp(-h / AIR_HEIGHT) * ds * p.air;
        airDepth += airHere;
        float hazeHere = exp(-h / HAZE_HEIGHT) * ds * p.haze;
        hazeDepth += hazeHere;
        ozoneDepth += ozoneLayer(h) * ds * p.air;
        // The same sum from here towards the sun: what its light crossed.
        float sunDs = leave(pos, sun, TOP) / float(SUN_STEPS);
        float sunAir = 0.0, sunHaze = 0.0, sunOzone = 0.0;
        for (int j = 0; j < SUN_STEPS; j++) {
            float3 q = pos + sun * (float(j) + 0.5) * sunDs;
            // Under the ground the air gets thick fast: the planet's shadow.
            float qh = max(length(q) - GROUND, -40.0);
            sunAir += exp(-qh / AIR_HEIGHT) * sunDs * p.air;
            sunHaze += exp(-qh / HAZE_HEIGHT) * sunDs * p.haze;
            sunOzone += ozoneLayer(qh) * sunDs * p.air;
        }
        // The light loses some of each color on both stretches.
        float3 lost = RAYLEIGH * (airDepth + sunAir)
                    + MIE * 1.1 * (hazeDepth + sunHaze)
                    + OZONE * (ozoneDepth + sunOzone);
        float3 left = exp(-lost);
        airLight += airHere * left;
        hazeLight += hazeHere * left;
    }
    through = exp(-(RAYLEIGH * airDepth + MIE * 1.1 * hazeDepth
                    + OZONE * ozoneDepth));
    airPath = airDepth;
    // Air sends as much light back as on, and half as much to the sides.
    float mu = dot(rd, sun);
    float airPhase = 3.0 / (16.0 * PI) * (1.0 + mu * mu);
    // Haze sends most of its light nearly straight on.
    float g = p.glare;
    float hazePhase = (1.0 - g * g)
        / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * mu, 1.5));
    return SUN_POWER * (airLight * RAYLEIGH * airPhase
                        + hazeLight * MIE * hazePhase);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 s = (uv - 0.5) * u.resolution * px;
    // The eye stands 300 m up a hill and looks a little above level.
    float3 eye = float3(0.0, GROUND + 0.3, 0.0);
    float3 rd = normalize(float3(s.x, s.y + 0.55, 1.6));
    float3 sun = sunAt(u.time, p);

    // How far the ray goes: to the top of the air, or to the ground.
    float reach = leave(eye, rd, TOP);
    float land = 0.0;
    float hit = meetGround(eye, rd);
    if (hit > 0.0) { reach = hit; land = 1.0; }
    // Or to one of three rows of hills, 3, 9 and 25 km away.
    float up = asin(rd.y);
    float around = atan2(rd.x, rd.z);
    // Within a pixel of an outline, `other` is how far the ray would go
    // on its other side.
    float edge = 1.0, other = reach;
    for (int row = 2; row >= 0; row--) {
        float over = up - hills(around, float(row));
        float away = row == 0 ? 3.0 : (row == 1 ? 9.0 : 25.0);
        float close = min(abs(over) / (px * 0.6), 1.0);
        if (over < 0.0) {
            other = reach;
            edge = close;
            reach = away;
            land = 1.0;
        } else if (close < edge) {
            other = away;
            edge = close;
        }
    }

    float3 through = float3(1.0);
    float airPath = 0.0;
    float3 light = skylight(eye, rd, reach, sun, p, through, airPath);
    // The sun's disc, over five times its real width, seen through the air.
    float disc = smoothstep(0.99955, 0.99975, dot(rd, sun));
    light += (1.0 - land) * disc * through * SUN_POWER * 4.0;

    // On an outline, mix in the other side's light, so the edge is smooth.
    if (edge < 1.0) {
        float3 through2 = float3(1.0);
        float path2 = 0.0;
        float3 light2 = skylight(eye, rd, other, sun, p, through2, path2);
        // Only open sky is more than 99 km deep: the disc shows there.
        light2 += step(99.0, other) * disc * through2 * SUN_POWER * 4.0;
        light = mix(light2, light, 0.5 + 0.5 * edge);
    }

    // The eye opens as the light goes: up to six times as the sun sets.
    float low = 1.0 - smoothstep(-0.1, 0.14, sunHeight(u.time, p));
    float open = p.exposure * (1.0 + 5.0 * low * low);
    // Bright light goes to white, then the screen's curve.
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// The same air, heard. A chord of whole-number partials over 72 Hz is the
// sunlight, and the air takes its high partials first, as it takes blue:
// each fades by its frequency to the fourth power times the air its light
// crosses, so the chord darkens as the sun sinks. The haze is wind: noise
// with the highs taken off. When the sun is nearly down, a cricket.

// Noise with nothing above about `rate` Hz in it, from hashes of the time.
float wind(float t, float rate) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    return mix(hash11(i), hash11(i + 1.0), f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // The air the sun's light crosses, 1 overhead and about 38 level.
    float mass = 1.0 / (max(sin(e), 0.0) + 0.026);
    float chordL = 0.0, chordR = 0.0;
    for (int k = 1; k <= 10; k++) {
        float f = 72.0 * float(k);
        float ratio = f / 720.0;
        float r4 = ratio * ratio * ratio * ratio;
        float kept = exp(-0.11 * p.air * mass * r4);
        float level = kept / float(k);
        // Each partial drifts slowly between the ears.
        float pan = 0.5 + 0.35 * sin(float(k) * 2.4 + TAU * t / 60.0);
        float tone = sin(TAU * f * t) * level;
        chordL += tone * (1.0 - pan);
        chordR += tone * pan;
    }
    float swell = 0.75 + 0.25 * sin(TAU * t / 12.0);
    float2 chord = float2(chordL, chordR) * 0.26 * swell;

    float gust = 0.6 + 0.4 * sin(TAU * t / 20.0 + 1.0);
    float hiss = 0.6 * wind(t, 900.0) + 0.4 * wind(t + 7.3, 2600.0);
    float2 air = float2(hiss, 0.6 * hiss + 0.4 * wind(t + 3.1, 1400.0));
    air *= min(p.haze, 3.0) * 0.045 * gust;

    // The cricket: three short chirps of a 4.3 kHz tone, twice a second.
    float dusk = 1.0 - smoothstep(-0.03, 0.09, e);
    float beat = fract(t * 2.0) / 2.0;
    float chirp = fract(beat * 28.0) / 28.0;
    float count = floor(beat * 28.0);
    float env = count < 3.0 ? sin(PI * chirp * 28.0) : 0.0;
    float cricket = sin(TAU * 4300.0 * chirp) * env * env * dusk * 0.05;

    float2 all = chord + air + float2(0.4, 1.0) * cricket;
    // Silence where the minute comes round, so it joins without a click.
    float turn = fract(t / 60.0);
    float fade = 1.0 - exp(-min(turn, 1.0 - turn) * 60.0 * 30.0);
    return tanh(all * 1.4) * p.volume * fade;
}
6 lines from stage 4 that are gone
    float airDepth = 0.0, hazeDepth = 0.0;
⋯
        float sunAir = 0.0, sunHaze = 0.0;
⋯
                    + MIE * 1.1 * (hazeDepth + sunHaze);
⋯
    through = exp(-(RAYLEIGH * airDepth + MIE * 1.1 * hazeDepth));
⋯
    float3 col = 1.0 - exp(-light);
⋯
    float2 all = chord + air;

The sound

The same air, heard. The sunlight is a chord: ten partials at whole multiples of 72 Hz, each as loud as 1 over its number, drifting slowly between the ears. The air takes the high partials first, as it takes blue. Each is multiplied by exp(−0.11 · air · mass · (f/720)⁴), where mass is how much air the sun's light crosses: 1 with the sun overhead, about 38 with it on the horizon. At the start, with the sun 18° up, the top partial keeps about 70% of its level. With the sun on the horizon it keeps under 2% and the fifth keeps 77%, so the chord is at its darkest when the picture is at its reddest.

The haze is wind: noise made by hashing the time and smoothing between the hashes, at 900, 1,400 and 2,600 values a second, louder with haze and rising and falling over 20 s. When the sun is within about 5° of the horizon a cricket comes in on the right: three chirps of a 4.3 kHz tone, twice a second. The sound falls to silence for a moment where the minute comes round, so the loop joins without a click.

At the defaults the peak is −11.3 dBFS and the average (RMS) −19.4 dBFS over the minute. With volume and haze at their highest it reaches a peak of −7.2 dBFS and an RMS of −17.0 dBFS.

New in Ray Kiln

Auto range for Show a value. Show a value turns a variable of shade into the picture: black at one end of a range, white at the other, 0 to 1 unless you type something else. That suits a color. It doesn't suit most of what a shader works with. Press Auto in the bar under the picture and the playground sets the range itself, to the smallest and largest value that line takes over the picture as it is at that moment.

It draws the value once more into a copy of the picture 256 × 144 pixels in size, as numbers and not as colors, reads the copy back, and takes the smallest and largest over the pixels that ran the line. The two are moved outwards to round numbers. A vector gets one range over all its components, since its color uses one. A value that isn't a number (NaN, infinity) is left out and counted, and the line under the sliders says what was found. The range belongs to that moment and those sliders: press Auto again after changing them. It works in a fragment shader whose picture is made from uv alone.

This episode is full of numbers nowhere near 0 to 1. Open the first stage in the playground, put the cursor on airPath in the line float airPath = airAlong(eye, rd, reach, p); and press Show a value. The picture is white all over: every ray crosses more than a kilometer of air, even the short ones that end on the ground. Press Auto. The line under the sliders says airPath runs from 1.103 to 328.2, the range becomes 1 to 329, and the picture is the sky's depth, dark overhead and brightest along the horizon. Do the same with reach in the finished shader: 3 to 990 kilometers, the hills black in front of a sky that grows to nearly a thousand kilometers deep at the horizon.

Try this

  • Set haze to 0: the glow round the sun goes and the sky is clean and deep. Set it to 6 and glare to 0.95 for a white sun in mist.
  • Set air to 4, four atmospheres: the sun is already orange well above the horizon. At 0.2 the sky is nearly black by day, as on a mountain far above most of the air.
  • Set swing to 0 and move height yourself, from 50° down to −4°, to stop the sun anywhere.
  • Show through with Show a value in the finished shader: it is what crosses each ray unscattered, white overhead and deep orange along the horizon. That orange is the color of the setting sun.
  • In the code, swap the red and blue numbers of RAYLEIGH. The sky is orange by day and the sunset is blue, as on Mars, where dust does what air does here.

Parameters

ParameterDefaultRangeWhat it does
height7-4 to 50The sun's middle height over the horizon, in degrees
swing110 to 25How far the sun rises and sinks from there, in degrees
air10.2 to 4How much air there is: Rayleigh scattering, the blue and the red
haze10 to 6How much haze there is: Mie scattering, the glow round the sun
glare0.760 to 0.95How much of the haze's light goes straight on
exposure10.25 to 4How bright the picture is
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.

sunset.metal
// Ray Kiln · Sunset
//
// @episode Sunset
// @length 60
// @variation 30
// @variations 1,2,3,4,7,8,10,11
// @sweeps height, air, haze
// @still 18
// @teaches Rayleigh and Mie scattering, a sky from the air it passes through
// @category Fragment
// @tags atmospheric scattering, Rayleigh scattering, Mie scattering, optical depth, raymarching, sky, procedural sound
// @final Sunset | Ozone turns the dusk violet, hills stand in the haze, and the eye opens as the light goes.
//
// A sky with no colors written into it. Every pixel looks along a ray
// through a round shell of air, 100 km deep on a planet 6,371 km in radius,
// and adds up the sunlight the air throws towards the eye. Air molecules
// scatter blue nearly six times as strongly as red (Rayleigh), so the sky
// is blue, and sunlight that crosses a lot of air has lost its
// blue, so a low sun is red. Haze scatters every color alike and mostly
// straight on (Mie), which makes the white glow round the sun. The sun
// sinks under the horizon and rises again once a minute.
// 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 height 7 -4 50 The sun's middle height over the horizon, in degrees
// @param swing 11 0 25 How far the sun rises and sinks from there, in degrees
// @param air 1 0.2 4 How much air there is: Rayleigh scattering, the blue and the red
// @param haze 1 0 6 How much haze there is: Mie scattering, the glow round the sun
// @param glare 0.76 0 0.95 How much of the haze's light goes straight on
// @param exposure 1 0.25 4 How bright the picture is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The sun goes down and comes back once in this many seconds.
constant float LOOP = 60.0;
// Lengths are in kilometers: the ground's radius and the top of the air.
constant float GROUND = 6371.0;
constant float TOP = 6471.0;
// Air thins with height: 8 km up there is 1/e of it left (about 37%).
constant float AIR_HEIGHT = 8.0;
// Haze stays low: 1.2 km up there is 1/e of it left.
constant float HAZE_HEIGHT = 1.2;
// What a kilometer of sea-level air scatters of red, green and blue.
constant float3 RAYLEIGH = float3(0.0058, 0.0135, 0.0331);
// What a kilometer of haze scatters, of every color alike.
constant float MIE = 0.004;
// What a kilometer of the ozone layer absorbs: mostly orange and green.
constant float3 OZONE = float3(0.00065, 0.00188, 0.000085);
constant float SUN_POWER = 18.0;
constant int STEPS = 24;
constant int SUN_STEPS = 8;

float hash11(float n) {
    return fract(sin(n * 12.9898) * 43758.5453);
}

// Smooth noise along a line: a random height at each whole number.
float ridgeNoise(float x) {
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    return mix(hash11(i), hash11(i + 1.0), f);
}

// How far along the ray it leaves a ball of this radius round the planet.
float leave(float3 from, float3 rd, float radius) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - radius) * (r + radius);
    return -b + sqrt(max(b * b - c, 0.0));
}

// Where it meets the ground, or -1 if it never does.
float meetGround(float3 from, float3 rd) {
    float r = length(from);
    float b = dot(from, rd);
    float c = (r - GROUND) * (r + GROUND);
    float h = b * b - c;
    if (b > 0.0 || h < 0.0) return -1.0;
    return -b - sqrt(h);
}

// The sun's height at time t, in radians: it swings once a loop.
float sunHeight(float t, constant Params& p) {
    return (p.height + p.swing * cos(TAU * t / LOOP)) * PI / 180.0;
}

float3 sunAt(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // It slides a little sideways as it sinks, as a real sunset does.
    float a = 0.35 * (e - p.height * PI / 180.0);
    return normalize(float3(sin(a) * cos(e), sin(e), cos(a) * cos(e)));
}

// Ozone at a height: most 25 km up, none 15 km from that.
float ozoneLayer(float h) {
    return max(1.0 - abs(h - 25.0) / 15.0, 0.0);
}

// A row of hills' outline: how high it stands, as an angle.
float hills(float around, float row) {
    float x = around * (9.0 + 5.0 * row) + row * 31.7;
    float h = ridgeNoise(x) + 0.5 * ridgeNoise(x * 2.3 + 4.1);
    h += 0.22 * ridgeNoise(x * 5.9 + 9.3);
    return 0.006 + (0.05 - 0.013 * row) * h * 0.6;
}

// The sunlight the air scatters towards the eye along the ray. `through`
// is the share of each color that crosses it unscattered.
float3 skylight(float3 eye, float3 rd, float reach, float3 sun,
                constant Params& p, thread float3& through,
                thread float& airPath) {
    float ds = reach / float(STEPS);
    float airDepth = 0.0, hazeDepth = 0.0, ozoneDepth = 0.0;
    float3 airLight = float3(0.0), hazeLight = float3(0.0);
    for (int i = 0; i < STEPS; i++) {
        float3 pos = eye + rd * (float(i) + 0.5) * ds;
        float h = length(pos) - GROUND;
        // How much air this step holds: it thins as it gets higher.
        float airHere = exp(-h / AIR_HEIGHT) * ds * p.air;
        airDepth += airHere;
        float hazeHere = exp(-h / HAZE_HEIGHT) * ds * p.haze;
        hazeDepth += hazeHere;
        ozoneDepth += ozoneLayer(h) * ds * p.air;
        // The same sum from here towards the sun: what its light crossed.
        float sunDs = leave(pos, sun, TOP) / float(SUN_STEPS);
        float sunAir = 0.0, sunHaze = 0.0, sunOzone = 0.0;
        for (int j = 0; j < SUN_STEPS; j++) {
            float3 q = pos + sun * (float(j) + 0.5) * sunDs;
            // Under the ground the air gets thick fast: the planet's shadow.
            float qh = max(length(q) - GROUND, -40.0);
            sunAir += exp(-qh / AIR_HEIGHT) * sunDs * p.air;
            sunHaze += exp(-qh / HAZE_HEIGHT) * sunDs * p.haze;
            sunOzone += ozoneLayer(qh) * sunDs * p.air;
        }
        // The light loses some of each color on both stretches.
        float3 lost = RAYLEIGH * (airDepth + sunAir)
                    + MIE * 1.1 * (hazeDepth + sunHaze)
                    + OZONE * (ozoneDepth + sunOzone);
        float3 left = exp(-lost);
        airLight += airHere * left;
        hazeLight += hazeHere * left;
    }
    through = exp(-(RAYLEIGH * airDepth + MIE * 1.1 * hazeDepth
                    + OZONE * ozoneDepth));
    airPath = airDepth;
    // Air sends as much light back as on, and half as much to the sides.
    float mu = dot(rd, sun);
    float airPhase = 3.0 / (16.0 * PI) * (1.0 + mu * mu);
    // Haze sends most of its light nearly straight on.
    float g = p.glare;
    float hazePhase = (1.0 - g * g)
        / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * mu, 1.5));
    return SUN_POWER * (airLight * RAYLEIGH * airPhase
                        + hazeLight * MIE * hazePhase);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 s = (uv - 0.5) * u.resolution * px;
    // The eye stands 300 m up a hill and looks a little above level.
    float3 eye = float3(0.0, GROUND + 0.3, 0.0);
    float3 rd = normalize(float3(s.x, s.y + 0.55, 1.6));
    float3 sun = sunAt(u.time, p);

    // How far the ray goes: to the top of the air, or to the ground.
    float reach = leave(eye, rd, TOP);
    float land = 0.0;
    float hit = meetGround(eye, rd);
    if (hit > 0.0) { reach = hit; land = 1.0; }
    // Or to one of three rows of hills, 3, 9 and 25 km away.
    float up = asin(rd.y);
    float around = atan2(rd.x, rd.z);
    // Within a pixel of an outline, `other` is how far the ray would go
    // on its other side.
    float edge = 1.0, other = reach;
    for (int row = 2; row >= 0; row--) {
        float over = up - hills(around, float(row));
        float away = row == 0 ? 3.0 : (row == 1 ? 9.0 : 25.0);
        float close = min(abs(over) / (px * 0.6), 1.0);
        if (over < 0.0) {
            other = reach;
            edge = close;
            reach = away;
            land = 1.0;
        } else if (close < edge) {
            other = away;
            edge = close;
        }
    }

    float3 through = float3(1.0);
    float airPath = 0.0;
    float3 light = skylight(eye, rd, reach, sun, p, through, airPath);
    // The sun's disc, over five times its real width, seen through the air.
    float disc = smoothstep(0.99955, 0.99975, dot(rd, sun));
    light += (1.0 - land) * disc * through * SUN_POWER * 4.0;

    // On an outline, mix in the other side's light, so the edge is smooth.
    if (edge < 1.0) {
        float3 through2 = float3(1.0);
        float path2 = 0.0;
        float3 light2 = skylight(eye, rd, other, sun, p, through2, path2);
        // Only open sky is more than 99 km deep: the disc shows there.
        light2 += step(99.0, other) * disc * through2 * SUN_POWER * 4.0;
        light = mix(light2, light, 0.5 + 0.5 * edge);
    }

    // The eye opens as the light goes: up to six times as the sun sets.
    float low = 1.0 - smoothstep(-0.1, 0.14, sunHeight(u.time, p));
    float open = p.exposure * (1.0 + 5.0 * low * low);
    // Bright light goes to white, then the screen's curve.
    float3 col = 1.0 - exp(-light * open);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// The same air, heard. A chord of whole-number partials over 72 Hz is the
// sunlight, and the air takes its high partials first, as it takes blue:
// each fades by its frequency to the fourth power times the air its light
// crosses, so the chord darkens as the sun sinks. The haze is wind: noise
// with the highs taken off. When the sun is nearly down, a cricket.

// Noise with nothing above about `rate` Hz in it, from hashes of the time.
float wind(float t, float rate) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    return mix(hash11(i), hash11(i + 1.0), f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    float e = sunHeight(t, p);
    // The air the sun's light crosses, 1 overhead and about 38 level.
    float mass = 1.0 / (max(sin(e), 0.0) + 0.026);
    float chordL = 0.0, chordR = 0.0;
    for (int k = 1; k <= 10; k++) {
        float f = 72.0 * float(k);
        float ratio = f / 720.0;
        float r4 = ratio * ratio * ratio * ratio;
        float kept = exp(-0.11 * p.air * mass * r4);
        float level = kept / float(k);
        // Each partial drifts slowly between the ears.
        float pan = 0.5 + 0.35 * sin(float(k) * 2.4 + TAU * t / 60.0);
        float tone = sin(TAU * f * t) * level;
        chordL += tone * (1.0 - pan);
        chordR += tone * pan;
    }
    float swell = 0.75 + 0.25 * sin(TAU * t / 12.0);
    float2 chord = float2(chordL, chordR) * 0.26 * swell;

    float gust = 0.6 + 0.4 * sin(TAU * t / 20.0 + 1.0);
    float hiss = 0.6 * wind(t, 900.0) + 0.4 * wind(t + 7.3, 2600.0);
    float2 air = float2(hiss, 0.6 * hiss + 0.4 * wind(t + 3.1, 1400.0));
    air *= min(p.haze, 3.0) * 0.045 * gust;

    // The cricket: three short chirps of a 4.3 kHz tone, twice a second.
    float dusk = 1.0 - smoothstep(-0.03, 0.09, e);
    float beat = fract(t * 2.0) / 2.0;
    float chirp = fract(beat * 28.0) / 28.0;
    float count = floor(beat * 28.0);
    float env = count < 3.0 ? sin(PI * chirp * 28.0) : 0.0;
    float cricket = sin(TAU * 4300.0 * chirp) * env * env * dusk * 0.05;

    float2 all = chord + air + float2(0.4, 1.0) * cricket;
    // Silence where the minute comes round, so it joins without a click.
    float turn = fract(t / 60.0);
    float fade = 1.0 - exp(-min(turn, 1.0 - turn) * 60.0 * 30.0);
    return tanh(all * 1.4) * 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] = [7, 11, 1, 1, 0.76, 1, 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.

More in Atmosphere