Shader

Clockwork

Six gears in front of the kiln, each a distance field in polar coordinates, a circle whose edge rises into a tooth and falls into a gap as the angle goes round. Each sits beside the gear that drives it and turns the other way, slower or faster by the ratio of their teeth, its teeth set so they fall into the other's gaps. The big gear ticks round six times a minute like an escapement, and every tooth count divides the 144 teeth that pass in that time, so after sixty seconds each gear has made whole turns and the minute loops.

· Shapes & Symmetry · Fragment shader

Teaches Gears from 2D distance fields, teeth that mesh, ratios that loop

Builds on Flowing Color Field (hash21, value noise, fractal noise), Morphing Shapes, Kaleidoscope

Watch

The idea

A gear is a circle whose edge goes up and down. Measured from its center, as an angle and a distance (the polar coordinates of Kaleidoscope), its edge is a radius plus a bump that comes round once per tooth. That makes a gear a distance field like the shapes in Morphing Shapes: every pixel asks how far it is from the edge, and below 0 it is metal.

Two gears mesh when they are as far apart as their radii added and a tooth of one always sits in a gap of the other. Then they turn opposite ways, and the speed changes by the ratio of their teeth: a 24-tooth gear driving a 36-tooth gear turns it 24/36 as fast. That ratio decides when the whole machine comes back to where it began, which is what makes a loop. It is built in five steps.

Stage 1 · One gear

gearEdge works in polar coordinates: a is the angle round the center, less the gear's own turn, spin. The edge is MODULE * (n * 0.5 + rise): the gear's radius, half its teeth in modules (0.04 each; the picture is 2 high), plus a tooth profile. cos(n * a) comes round n times a turn; scaled by 1.6 and clamped to −1 to 1, its tops and bottoms are cut flat, so each tooth has a flat tip one module out, a flat root 1.25 modules in, and steep flanks between. The distance is the radius less the edge, divided by how steeply the edge climbs (climb, the slope of the profile per unit of length round the circle), so the flanks come out as sharp as the round parts. Turning the gear is only taking spin off the angle. A hot mark near the rim shows it going round.

stage-1-one-gear.metal
// Stage 1 · One gear
// A gear is a circle whose edge goes up and down as the angle goes round.
// In polar coordinates (angle and radius, from Kaleidoscope) the edge is the
// radius plus cos(n * angle), clamped so each of the n teeth has a flat top
// and a flat root. Turning the gear is taking its angle off before the cos.

// @param turns 6 1 12 How many times the gear turns in a minute
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// The size of a tooth: a gear's radius is MODULE times half its teeth.
constant float MODULE = 0.04;

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));
}

// The tooth profile: tips one module above the radius, roots 1.25 below.
// Dividing by how steeply the edge climbs keeps it a true distance on the
// flanks, so they are as sharp as the round parts.
float gearEdge(float2 p, float n, float spin) {
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    a -= TAU * floor(a / TAU);
    float c = cos(n * a) * 1.6 - 0.05;
    float tooth = clamp(c, -1.0, 1.0);
    float rise = tooth > 0.0 ? tooth : tooth * 1.25;
    float edge = MODULE * (n * 0.5 + rise);
    float slope = MODULE * 1.6 * n * abs(sin(n * a)) / max(r, edge);
    float climb = abs(c) < 1.0 ? slope : 0.0;
    climb *= tooth > 0.0 ? 1.0 : 1.25;
    return (r - edge) / sqrt(1.0 + climb * climb);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float turns = max(floor(p.turns + 0.5), 1.0);
    // Clockwise, a whole number of turns a minute, as a fraction of a turn.
    float spin = -TAU * fract(u.time * turns / 60.0);
    float d = gearEdge(q, 24.0, spin);
    // A hot mark near the rim shows the turning.
    float2 mark = 0.36 * float2(cos(spin), sin(spin));
    float metal = 0.55;
    float hot = 1.0 - smoothstep(-px, px, length(q - mark) - 0.03);
    metal = mix(metal, 0.93, hot);
    float heat = mix(metal, 0.1, smoothstep(-px, px, d));
    return float4(kiln(heat), 1.0);
}

// The sound: a click each time a tooth passes the top, and a low hum.
float2 sound(float t, constant Params& p) {
    float turns = max(floor(p.turns + 0.5), 1.0);
    float x = t * turns * 24.0 / 60.0;
    float since = fract(x) * 60.0 / (turns * 24.0);
    float attack = 1.0 - exp(-since * 3000.0);
    float click = sin(TAU * 2100.0 * since) * exp(-since * 70.0) * attack;
    float hum = sin(TAU * 55.0 * t) + 0.35 * sin(TAU * 110.0 * t);
    float s = click * 0.4 + hum * 0.08;
    return float2(tanh(s * 1.5)) * p.volume;
}

Stage 2 · Two that mesh

The second gear has 36 teeth and sits in the direction dir from the first, MODULE * 0.5 * (n + np) away: the two radii added. Where they touch, each gear's tooth phase there (its teeth count times the angle, measured from its own turn) must add up to half a tooth, so a tooth meets a gap. Solving that for the second gear gives spin = dir + π − (π − np·(dir − spin_p)) / n. It holds at every moment because the second gear turns −24/36 as fast as the first, the other way: when the small gear has turned 6 times, the big one has turned 4. Their marks show it.

stage-2-two-that-mesh.metal22 new lines since stage 1
// Stage 2 · Two that mesh
// A second gear sits beside the first, as far away as their two radii
// added. Where they touch, a tooth of one must meet a gap of the other: the
// tooth phases of the two at that point add up to half a tooth. Keep that
// true and the second gear turns the other way, 24/36 as fast.

// @param turns 6 1 12 How many times the small gear turns in a minute
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
constant float MODULE = 0.04;

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 gearEdge(float2 p, float n, float spin) {
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    a -= TAU * floor(a / TAU);
    float c = cos(n * a) * 1.6 - 0.05;
    float tooth = clamp(c, -1.0, 1.0);
    float rise = tooth > 0.0 ? tooth : tooth * 1.25;
    float edge = MODULE * (n * 0.5 + rise);
    float slope = MODULE * 1.6 * n * abs(sin(n * a)) / max(r, edge);
    float climb = abs(c) < 1.0 ? slope : 0.0;
    climb *= tooth > 0.0 ? 1.0 : 1.25;
    return (r - edge) / sqrt(1.0 + climb * climb);
}

// A gear: its distance, and its hot mark, mixed into the heat.
float gear(float2 q, float2 c, float n, float spin, float px,
           thread float& heat) {
    float2 p = q - c;
    float d = gearEdge(p, n, spin);
    float2 mark = 0.6 * MODULE * n * 0.5 * float2(cos(spin), sin(spin));
    float hot = 1.0 - smoothstep(-px, px, length(p - mark) - 0.03);
    if (d < 0.0) heat = mix(0.55, 0.93, hot);
    return d;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float turns = max(floor(p.turns + 0.5), 1.0);
    float driven = -turns * u.time / 60.0;
    float spin = TAU * fract(driven);
    // The driver, and where the second sits: in direction dir, n + np
    // modules apart. Its angle puts a gap where the driver has a tooth.
    float2 c0 = float2(-0.5, 0.12);
    float n = 36.0, np = 24.0, dir = -0.2;
    float2 c1 = c0 + MODULE * 0.5 * (n + np) * float2(cos(dir), sin(dir));
    float rest = dir + PI - (PI - np * dir) / n;
    // It turns -np/n times as fast: 6 turns of the driver are 4 of its.
    float spin1 = rest + TAU * fract(-np / n * driven);
    float heat = 0.1;
    float d = min(gear(q, c0, np, spin, px, heat),
                  gear(q, c1, n, spin1, px, heat));
    heat = mix(heat, 0.1, smoothstep(-px, px, d));
    heat *= 0.55 + 0.45 * smoothstep(0.0, 1.5 * px, abs(d));
    return float4(kiln(heat), 1.0);
}

// The sound: a click as each tooth meets the other gear, a low hum.
float2 sound(float t, constant Params& p) {
    float turns = max(floor(p.turns + 0.5), 1.0);
    float x = t * turns * 24.0 / 60.0;
    float since = fract(x) * 60.0 / (turns * 24.0);
    float attack = 1.0 - exp(-since * 3000.0);
    float click = sin(TAU * 2100.0 * since) * exp(-since * 70.0) * attack;
    float hum = sin(TAU * 55.0 * t) + 0.35 * sin(TAU * 110.0 * t);
    float s = click * 0.4 + hum * 0.08;
    return float2(tanh(s * 1.5)) * p.volume;
}
7 lines from stage 1 that are gone
    float spin = -TAU * fract(u.time * turns / 60.0);
    float d = gearEdge(q, 24.0, spin);
⋯
    float2 mark = 0.36 * float2(cos(spin), sin(spin));
    float metal = 0.55;
    float hot = 1.0 - smoothstep(-px, px, length(q - mark) - 0.03);
    metal = mix(metal, 0.93, hot);
    float heat = mix(metal, 0.1, smoothstep(-px, px, d));

Stage 3 · A train

Six gears, kept in tables: TEETH (24, 36, 12, 16, 48, 18), PARENT (the gear that drives each one) and DIR (which way from its parent it sits). train places each one from its parent and works out its rest angle (where it stands when the driver is at 0) and its ratio (its parent's ratio times −np/n). The driver turns turns times a minute, 6 by default. The ratios make the others turn 4, 12, 9, 3 and 8 times: every tooth count divides 6 × 24 = 144 teeth, so each gear makes a whole number of turns in the minute and its mark ends where it began. At 7 turns the 36-tooth gear would make 4⅔ turns, and the minute wouldn't loop.

The angles are kept small on purpose: each gear's turn is TAU * fract(ratio * driven), the fraction of a turn it has made, rather than the whole angle. A minute in, the driver alone has turned 37 radians, and cos(48 * a) of an angle that large rounds differently from the same angle near 0. That moved a tooth's edge by a pixel at 60 s and broke the loop, until the turns were kept as fractions. trainDistance takes the nearest gear for each pixel and remembers which one it is.

stage-3-a-train.metal84 new lines since stage 2
// Stage 3 · A train
// Six gears, each placed beside the gear that drives it and turned from it
// by the ratio of their teeth. The driver turns six times a minute; every
// tooth count here divides 6 x 24 = 144, so each gear makes whole turns in
// a minute and its mark is back where it began: the minute loops.

// @param turns 6 1 12 How many times the big gear turns in a minute, in whole turns
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The loop: sixty seconds, two ticks a second (for the sound).
constant float LOOP = 60.0;
constant float TICKS = 120.0;
constant float MODULE = 0.04;
// The train: each gear's teeth, the gear that drives it, and the direction
// from that gear's center to its own. The first is the driver.
constant int GEARS = 6;
constant float TEETH[6] = {24.0, 36.0, 12.0, 16.0, 48.0, 18.0};
constant int PARENT[6] = {-1, 0, 0, 1, 0, 1};
constant float DIR[6] = {0.0, -0.2, 2.3, 1.6, -1.9, -0.9};
constant float2 DRIVER = float2(-0.35, 0.05);

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

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 gearEdge(float2 p, float n, float spin) {
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    a -= TAU * floor(a / TAU);
    float c = cos(n * a) * 1.6 - 0.05;
    float tooth = clamp(c, -1.0, 1.0);
    // The tip rises one module above the radius, the root 1.25 below.
    float rise = tooth > 0.0 ? tooth : tooth * 1.25;
    float edge = MODULE * (n * 0.5 + rise);
    // How fast the edge moves per unit of length round the circle, out at
    // the teeth (nearer the axle the flanks are far away anyway).
    float slope = MODULE * 1.6 * n * abs(sin(n * a)) / max(r, edge);
    float climb = abs(c) < 1.0 ? slope : 0.0;
    climb *= tooth > 0.0 ? 1.0 : 1.25;
    return (r - edge) / sqrt(1.0 + climb * climb);
}

// The driver turns; each other gear turns from its parent. Where they touch,
// in direction dir from the parent, the parent's tooth phase n_p(dir - spin_p)
// and the child's n(dir + pi - spin) always add up to half a tooth, so a tooth
// meets a gap: spin = dir + pi - (pi - n_p(dir - spin_p)) / n. That makes the
// child turn -n_p/n times as fast as its parent: its ratio.
// The angles are kept small: each gear's turns so far as a fraction of a
// turn. A minute in, the driver alone is 37 radians round, and cos(48 * a)
// of that rounds differently from cos of the same angle near 0, enough to
// move a tooth's edge by a pixel and break the loop.

struct Train {
    float2 centre[6];
    float spin[6];
};

Train train(float driven, float zoom) {
    Train g;
    float rest[6];
    float ratio[6];
    g.centre[0] = DRIVER * zoom;
    rest[0] = 0.0;
    ratio[0] = 1.0;
    for (int i = 1; i < GEARS; i++) {
        int j = PARENT[i];
        float n = TEETH[i], np = TEETH[j];
        float dir = DIR[i];
        float reach = MODULE * 0.5 * (n + np) * zoom;
        g.centre[i] = g.centre[j] + reach * float2(cos(dir), sin(dir));
        rest[i] = dir + PI - (PI - np * (dir - rest[j])) / n;
        ratio[i] = -ratio[j] * np / n;
    }
    for (int i = 0; i < GEARS; i++) {
        g.spin[i] = rest[i] + TAU * fract(ratio[i] * driven);
    }
    return g;
}

// The whole train's distance: its nearest gear, and which one it is.
float trainDistance(float2 q, Train g, thread int& id) {
    float d = 1e3;
    for (int i = 0; i < GEARS; i++) {
        float2 p = q - g.centre[i];
        float gd = gearEdge(p, TEETH[i], g.spin[i]);
        if (gd < d) { d = gd; id = i; }
    }
    return d;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float turns = max(floor(p.turns + 0.5), 1.0);
    Train g = train(-turns * u.time / LOOP, 1.0);
    int id = 0;
    float d = trainDistance(q, g, id);
    // Each gear's mark, its turns made visible.
    float2 local = q - g.centre[id];
    float R = MODULE * TEETH[id] * 0.5;
    float2 mark = 0.6 * R * float2(cos(g.spin[id]), sin(g.spin[id]));
    float hot = 1.0 - smoothstep(-px, px, length(local - mark) - 0.022);
    float heat = mix(mix(0.5, 0.93, hot), 0.1, smoothstep(-px, px, d));
    heat *= 0.55 + 0.45 * smoothstep(0.0, 1.5 * px, abs(d));
    return float4(kiln(heat), 1.0);
}

// ---- Sound ----------------------------------------------------------------
// The same clock in time. Two ticks a second, a tick and a tock a little
// lower, each a burst of noise ringing a small metal ping; every time the big
// gear comes round, a bell; under them the low hum of the train turning. Each
// starts from silence at its own moment, and the hum's 55 Hz makes a whole
// number of cycles in a minute, so the sound loops with the picture.

float tickSound(float since, float parity) {
    float attack = 1.0 - exp(-since * 4000.0);
    float sample = floor(since * 48000.0);
    float noise = hash21(float2(sample, parity * 7.1)) * 2.0 - 1.0;
    float click = noise * exp(-since * 700.0);
    float f = parity > 0.5 ? 1850.0 : 2400.0;
    float ping = sin(TAU * f * since) * exp(-since * 55.0);
    return (0.6 * click + ping) * attack;
}

float gearBell(float since) {
    float attack = 1.0 - exp(-since * 900.0);
    float b = sin(TAU * 392.0 * since) * exp(-since * 0.9);
    b += 0.5 * sin(TAU * 392.0 * 2.76 * since) * exp(-since * 2.2);
    b += 0.25 * sin(TAU * 392.0 * 5.40 * since) * exp(-since * 4.0);
    return b * attack;
}

float2 sound(float t, constant Params& p) {
    float turns = max(floor(p.turns + 0.5), 1.0);
    float x = t * TICKS / LOOP;
    float k = floor(x);
    float since = fract(x) * LOOP / TICKS;
    float parity = k - 2.0 * floor(k * 0.5);
    float tk = tickSound(since, parity);
    // The tick sits a little left, the tock a little right.
    float2 side = parity > 0.5 ? float2(0.75, 1.0) : float2(1.0, 0.75);
    float2 ticks = tk * side * 0.4;

    // A bell each turn of the driver: the turn's count, and the one before
    // still ringing under it.
    float turn = t * turns / LOOP;
    float ring = 0.0;
    for (int back = 0; back < 2; back++) {
        float since2 = (fract(turn) + float(back)) * LOOP / turns;
        if (floor(turn) - float(back) >= 0.0) ring += gearBell(since2);
    }
    float2 bells = float2(ring, ring) * 0.2;

    float hum = sin(TAU * 55.0 * t) + 0.35 * sin(TAU * 110.0 * t);
    float2 drone = float2(hum, hum) * 0.075;

    return tanh((ticks + bells + drone) * 1.5) * p.volume;
}
24 lines from stage 2 that are gone
float gear(float2 q, float2 c, float n, float spin, float px,
           thread float& heat) {
    float2 p = q - c;
    float d = gearEdge(p, n, spin);
    float2 mark = 0.6 * MODULE * n * 0.5 * float2(cos(spin), sin(spin));
    float hot = 1.0 - smoothstep(-px, px, length(p - mark) - 0.03);
    if (d < 0.0) heat = mix(0.55, 0.93, hot);
⋯
    float driven = -turns * u.time / 60.0;
    float spin = TAU * fract(driven);
⋯
    float2 c0 = float2(-0.5, 0.12);
    float n = 36.0, np = 24.0, dir = -0.2;
    float2 c1 = c0 + MODULE * 0.5 * (n + np) * float2(cos(dir), sin(dir));
    float rest = dir + PI - (PI - np * dir) / n;
⋯
    float spin1 = rest + TAU * fract(-np / n * driven);
    float heat = 0.1;
    float d = min(gear(q, c0, np, spin, px, heat),
                  gear(q, c1, n, spin1, px, heat));
    heat = mix(heat, 0.1, smoothstep(-px, px, d));
⋯
    float x = t * turns * 24.0 / 60.0;
    float since = fract(x) * 60.0 / (turns * 24.0);
    float attack = 1.0 - exp(-since * 3000.0);
    float click = sin(TAU * 2100.0 * since) * exp(-since * 70.0) * attack;
⋯
    float s = click * 0.4 + hum * 0.08;
    return float2(tanh(s * 1.5)) * p.volume;

Stage 4 · Spokes and axles

gearWindows cuts the windows: a ring from the hub (a fifth of the radius, at least 0.07) to 2.8 modules inside the rim, with SPOKES spokes left standing across it. The spokes are the angle repeated round the circle, as Kaleidoscope's slices are: aa is the angle from the nearest spoke, and r * sin(aa) is the distance from its middle line. A gear's distance is now the larger of its edge and minus its windows. The smallest gear stays solid. Each gear gets an axle cap with a dark pin, and its mark moves halfway along its first spoke. size scales the whole train.

stage-4-spokes-and-axles.metal36 new lines since stage 3
// Stage 4 · Spokes and axles
// Cut windows out of each gear: a ring between the hub and the rim, with
// spokes left standing across it, as an angle repeated round the circle.
// An axle cap in the middle, and the mark moves onto a spoke. A gear's
// distance is now the larger of its edge and minus its windows.

// @param turns 6 1 12 How many times the big gear turns in a minute, in whole turns
// @param size 1 0.6 1.6 How big the gears are on screen
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The loop: sixty seconds, two ticks a second (for the sound).
constant float LOOP = 60.0;
constant float TICKS = 120.0;
constant float MODULE = 0.04;
// The train: each gear's teeth, the gear that drives it, and the direction
// from that gear's center to its own. The first is the driver.
constant int GEARS = 6;
constant float TEETH[6] = {24.0, 36.0, 12.0, 16.0, 48.0, 18.0};
constant int PARENT[6] = {-1, 0, 0, 1, 0, 1};
constant float DIR[6] = {0.0, -0.2, 2.3, 1.6, -1.9, -0.9};
// How many spokes each gear has (none for the smallest).
constant float SPOKES[6] = {6.0, 6.0, 0.0, 4.0, 8.0, 3.0};
constant float2 DRIVER = float2(-0.35, 0.05);

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

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 gearEdge(float2 p, float n, float spin) {
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    a -= TAU * floor(a / TAU);
    float c = cos(n * a) * 1.6 - 0.05;
    float tooth = clamp(c, -1.0, 1.0);
    // The tip rises one module above the radius, the root 1.25 below.
    float rise = tooth > 0.0 ? tooth : tooth * 1.25;
    float edge = MODULE * (n * 0.5 + rise);
    // How fast the edge moves per unit of length round the circle, out at
    // the teeth (nearer the axle the flanks are far away anyway).
    float slope = MODULE * 1.6 * n * abs(sin(n * a)) / max(r, edge);
    float climb = abs(c) < 1.0 ? slope : 0.0;
    climb *= tooth > 0.0 ? 1.0 : 1.25;
    return (r - edge) / sqrt(1.0 + climb * climb);
}

// The windows between the spokes: a ring between the hub and the rim, with s
// spokes left standing across it. Positive outside a window.
float gearWindows(float2 p, float n, float s, float spin) {
    if (s < 1.0) return 1.0;
    float R = MODULE * n * 0.5;
    float hub = max(0.07, 0.2 * R), rim = R - 2.8 * MODULE;
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    float ring = abs(r - 0.5 * (hub + rim)) - 0.5 * (rim - hub);
    float slice = TAU / s;
    float aa = a - slice * floor(a / slice + 0.5);
    float spoke = abs(r * sin(aa)) - (0.022 + 0.03 * R);
    return max(ring, -spoke);
}

// The driver turns; each other gear turns from its parent. Where they touch,
// in direction dir from the parent, the parent's tooth phase n_p(dir - spin_p)
// and the child's n(dir + pi - spin) always add up to half a tooth, so a tooth
// meets a gap: spin = dir + pi - (pi - n_p(dir - spin_p)) / n. That makes the
// child turn -n_p/n times as fast as its parent: its ratio.
// The angles are kept small: each gear's turns so far as a fraction of a
// turn. A minute in, the driver alone is 37 radians round, and cos(48 * a)
// of that rounds differently from cos of the same angle near 0, enough to
// move a tooth's edge by a pixel and break the loop.

struct Train {
    float2 centre[6];
    float spin[6];
};

Train train(float driven, float zoom) {
    Train g;
    float rest[6];
    float ratio[6];
    g.centre[0] = DRIVER * zoom;
    rest[0] = 0.0;
    ratio[0] = 1.0;
    for (int i = 1; i < GEARS; i++) {
        int j = PARENT[i];
        float n = TEETH[i], np = TEETH[j];
        float dir = DIR[i];
        float reach = MODULE * 0.5 * (n + np) * zoom;
        g.centre[i] = g.centre[j] + reach * float2(cos(dir), sin(dir));
        rest[i] = dir + PI - (PI - np * (dir - rest[j])) / n;
        ratio[i] = -ratio[j] * np / n;
    }
    for (int i = 0; i < GEARS; i++) {
        g.spin[i] = rest[i] + TAU * fract(ratio[i] * driven);
    }
    return g;
}

// The whole train's distance: its nearest gear, and which one it is.
float trainDistance(float2 q, Train g, float zoom, thread int& id) {
    float d = 1e3;
    for (int i = 0; i < GEARS; i++) {
        float2 p = (q - g.centre[i]) / zoom;
        float n = TEETH[i];
        float gd = length(p) - MODULE * (n * 0.5 + 1.0);
        // Only near a gear is its tooth profile worth working out.
        if (gd < 0.05) {
            float s = g.spin[i];
            gd = max(gearEdge(p, n, s), -gearWindows(p, n, SPOKES[i], s));
        }
        gd *= zoom;
        if (gd < d) { d = gd; id = i; }
    }
    return d;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float turns = max(floor(p.turns + 0.5), 1.0);
    float zoom = p.size;
    Train g = train(-turns * u.time / LOOP, zoom);
    int id = 0;
    float d = trainDistance(q, g, zoom, id);
    float2 local = (q - g.centre[id]) / zoom;
    float r = length(local);
    float R = MODULE * TEETH[id] * 0.5;
    float metal = 0.5;
    // The axle: a bright cap with a dark pin.
    metal = mix(metal, 0.72, 1.0 - smoothstep(-px, px, (r - 0.035) * zoom));
    metal = mix(metal, 0.08, 1.0 - smoothstep(-px, px, (r - 0.012) * zoom));
    // The mark, halfway along the first spoke.
    float onSpoke = 0.5 * (max(0.07, 0.2 * R) + R - 2.8 * MODULE);
    float reach = SPOKES[id] > 0.0 ? onSpoke : 0.6 * R;
    float2 mark = reach * float2(cos(g.spin[id]), sin(g.spin[id]));
    float rivet = length(local - mark) - 0.022;
    metal = mix(metal, 0.93, 1.0 - smoothstep(-px, px, rivet * zoom));
    float heat = mix(metal, 0.1, smoothstep(-px, px, d));
    heat *= 0.55 + 0.45 * smoothstep(0.0, 1.5 * px, abs(d));
    return float4(kiln(heat), 1.0);
}

// ---- Sound ----------------------------------------------------------------
// The same clock in time. Two ticks a second, a tick and a tock a little
// lower, each a burst of noise ringing a small metal ping; every time the big
// gear comes round, a bell; under them the low hum of the train turning. Each
// starts from silence at its own moment, and the hum's 55 Hz makes a whole
// number of cycles in a minute, so the sound loops with the picture.

float tickSound(float since, float parity) {
    float attack = 1.0 - exp(-since * 4000.0);
    float sample = floor(since * 48000.0);
    float noise = hash21(float2(sample, parity * 7.1)) * 2.0 - 1.0;
    float click = noise * exp(-since * 700.0);
    float f = parity > 0.5 ? 1850.0 : 2400.0;
    float ping = sin(TAU * f * since) * exp(-since * 55.0);
    return (0.6 * click + ping) * attack;
}

float gearBell(float since) {
    float attack = 1.0 - exp(-since * 900.0);
    float b = sin(TAU * 392.0 * since) * exp(-since * 0.9);
    b += 0.5 * sin(TAU * 392.0 * 2.76 * since) * exp(-since * 2.2);
    b += 0.25 * sin(TAU * 392.0 * 5.40 * since) * exp(-since * 4.0);
    return b * attack;
}

float2 sound(float t, constant Params& p) {
    float turns = max(floor(p.turns + 0.5), 1.0);
    float x = t * TICKS / LOOP;
    float k = floor(x);
    float since = fract(x) * LOOP / TICKS;
    float parity = k - 2.0 * floor(k * 0.5);
    float tk = tickSound(since, parity);
    // The tick sits a little left, the tock a little right.
    float2 side = parity > 0.5 ? float2(0.75, 1.0) : float2(1.0, 0.75);
    float2 ticks = tk * side * 0.4;

    // A bell each turn of the driver: the turn's count, and the one before
    // still ringing under it.
    float turn = t * turns / LOOP;
    float ring = 0.0;
    for (int back = 0; back < 2; back++) {
        float since2 = (fract(turn) + float(back)) * LOOP / turns;
        if (floor(turn) - float(back) >= 0.0) ring += gearBell(since2);
    }
    float2 bells = float2(ring, ring) * 0.2;

    float hum = sin(TAU * 55.0 * t) + 0.35 * sin(TAU * 110.0 * t);
    float2 drone = float2(hum, hum) * 0.075;

    return tanh((ticks + bells + drone) * 1.5) * p.volume;
}
9 lines from stage 3 that are gone
float trainDistance(float2 q, Train g, thread int& id) {
⋯
        float2 p = q - g.centre[i];
        float gd = gearEdge(p, TEETH[i], g.spin[i]);
⋯
    Train g = train(-turns * u.time / LOOP, 1.0);
⋯
    float d = trainDistance(q, g, id);
⋯
    float2 local = q - g.centre[id];
⋯
    float2 mark = 0.6 * R * float2(cos(g.spin[id]), sin(g.spin[id]));
    float hot = 1.0 - smoothstep(-px, px, length(local - mark) - 0.022);
    float heat = mix(mix(0.5, 0.93, hot), 0.1, smoothstep(-px, px, d));

Stage 5 · Clockwork

driverTurns makes it tick. Time is counted in ticks, two a second, 120 a minute; within each tick the driver steps on with 1 − e^(−22f) cos(34f), a step that overshoots by about an eighth and settles, as an escapement lets a train jump one beat at a time. tick mixes from smooth turning (0) to that step (1). At 60 s the count is exactly 120, so the loop still closes.

The light comes from the kiln below the picture. The wall is fractal noise (from Flowing Color Field) drifting round a circle once a minute, so it loops too, with the kiln's glow rising from below, and a shadow: the train's distance worked out again 0.035 to the right and 0.05 lower, darkening the wall by up to 55%. The metal is brushed in rings round each axle (value noise along the radius) and catches the light in a streak through the axle that stays still as the gear turns, as brushed metal does. A bevel 0.018 wide round every edge is lit where it faces down towards the kiln, as strongly as glow says, and a thin dark line keeps two gears that touch apart. heat slides all the metal from cool iron to white-hot brass.

the kiln palette and shade(), from the finished shader
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) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float t = u.time;
    float turns = max(floor(p.turns + 0.5), 1.0);
    float zoom = p.size;

    Train g = train(driverTurns(t, turns, p.tick), zoom);

    int id = 0;
    float d = trainDistance(q, g, zoom, id);
    int shadowId = 0;
    float shadow = trainDistance(q - float2(0.035, -0.05), g, zoom, shadowId);

    // The wall: dark smoke drifting round a circle once a minute, so it loops
    // too, and the kiln's glow rising from below the picture.
    float2 drift = 0.35 * float2(cos(TAU * t / LOOP), sin(TAU * t / LOOP));
    float wall = 0.05 + 0.12 * fbm(q * 1.6 + drift);
    float kilnGlow = exp(-length(q - float2(0.0, -1.5)) * 1.1);
    wall += 0.2 * kilnGlow;
    wall *= 1.0 - 0.55 * (1.0 - smoothstep(-0.02, 0.06, shadow));

    // The metal, brushed in rings round its axle, warmer lower down.
    float2 local = (q - g.centre[id]) / zoom;
    float r = length(local);
    float n = TEETH[id];
    float R = MODULE * n * 0.5;
    float2 radial = local / max(r, 1e-4);
    float brush = vnoise(float2(r * 420.0, float(id) * 13.0));
    // A streak of light through the axle that stays put as it turns.
    float sheen = pow(abs(radial.y), 12.0) * (radial.y < 0.0 ? 0.16 : 0.07);
    float metal = 0.27 + 0.035 * brush + sheen + 0.14 * kilnGlow;
    metal -= 0.05 * local.y / max(R, 0.1);
    metal += (p.heat - 0.5) * 0.4;
    // A bevel round each edge, lit where it faces down to the kiln.
    float outer = gearEdge(local, n, g.spin[id]) * zoom;
    float window = gearWindows(local, n, SPOKES[id], g.spin[id]) * zoom;
    float2 facing = outer > -window ? radial : -radial;
    float bevel = 1.0 - smoothstep(0.0, 0.018, -d);
    float lit = 0.5 + 0.5 * dot(facing, float2(0.0, -1.0));
    metal += bevel * (0.12 + 0.36 * lit * p.glow);
    // The axle cap, and the hot mark that shows each gear's turn.
    float axle = r - 0.035;
    metal = mix(metal, 0.72, 1.0 - smoothstep(-px, px, axle * zoom));
    metal = mix(metal, 0.08, 1.0 - smoothstep(-px, px, (r - 0.012) * zoom));
    float onSpoke = 0.5 * (max(0.07, 0.2 * R) + R - 2.8 * MODULE);
    float reach = SPOKES[id] > 0.0 ? onSpoke : 0.6 * R;
    float2 mark = reach * float2(cos(g.spin[id]), sin(g.spin[id]));
    float rivet = length(local - mark) - 0.022;
    metal = mix(metal, 0.93, 1.0 - smoothstep(-px, px, rivet * zoom));

    float heat = mix(metal, wall, smoothstep(-px, px, d));
    // A thin dark line round every gear, so two that touch still read as two.
    heat *= 0.55 + 0.45 * smoothstep(0.0, 1.5 * px, abs(d));
    return float4(kiln(heat), 1.0);
}
clockwork.metal, the whole file49 new lines since stage 4
// Ray Kiln · Clockwork
//
// @episode Clockwork
// @length 60
// @variation 30
// @variations 1,2,4,5,6,9,11,12
// @sweeps size, heat, glow
// @still 21.3
// @teaches Gears from 2D distance fields, teeth that mesh, ratios that loop
// @category Fragment
// @tags gears, signed distance fields, polar coordinates, gear ratios, seamless loop, procedural sound
// @final Clockwork | The train ticks like an escapement, lit from the kiln below, and a minute later every gear is back where it began.
//
// Six gears in front of the kiln, each one a distance field in polar
// coordinates: a circle whose edge rises into a tooth and falls into a gap as
// the angle goes round. A gear sits beside the gear that drives it, as far
// from it as their two radii added, and turns the other way, slower by the
// ratio of their teeth, with its teeth set half a tooth over so they fall into
// the other's gaps. The big gear turns six times a minute. Each gear's tooth
// count divides six times its 24 teeth, so in sixty seconds every gear turns
// a whole number of times, and the minute loops: the frame at 60 s is the
// first frame again.
// 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 turns 6 1 12 How many times the big gear turns in a minute, in whole turns
// @param tick 0.8 0 1 From smooth turning (0) to the step and settle of an escapement (1)
// @param size 1 0.6 1.6 How big the gears are on screen
// @param heat 0.5 0 1 The metal from cool iron (0) to white-hot brass (1)
// @param glow 0.6 0 1 How brightly the kiln below lights the edges
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The loop: sixty seconds, two ticks a second.
constant float LOOP = 60.0;
constant float TICKS = 120.0;
// The size of a tooth: a gear's radius is MODULE times half its teeth, so any
// two gears with the same module mesh.
constant float MODULE = 0.04;
// The train: each gear's teeth, the gear that drives it, the direction from
// that gear's center to its own, and its spokes. The first is the driver.
constant int GEARS = 6;
constant float TEETH[6] = {24.0, 36.0, 12.0, 16.0, 48.0, 18.0};
constant int PARENT[6] = {-1, 0, 0, 1, 0, 1};
constant float DIR[6] = {0.0, -0.2, 2.3, 1.6, -1.9, -0.9};
constant float SPOKES[6] = {6.0, 6.0, 0.0, 4.0, 8.0, 3.0};
constant float2 DRIVER = float2(-0.35, 0.05);

// ---- Noise (Flowing Color Field) ------------------------------------------

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 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 fbm(float2 p) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < 4; i++) {
        v += a * vnoise(p);
        p = p * 2.03 + float2(17.1, 9.2);
        a *= 0.5;
    }
    return v;
}

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));
}

// ---- A gear ---------------------------------------------------------------
// In polar coordinates round its center, a gear's edge is its radius plus a
// tooth profile: cos(n * a) clamped, so each tooth has a flat top, a flat
// root and straight flanks, one tooth every 1/n of a turn. Its distance is
// the radius minus the edge, divided by how steeply the edge climbs, so the
// flanks are as sharp as the round parts.

float gearEdge(float2 p, float n, float spin) {
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    a -= TAU * floor(a / TAU);
    float c = cos(n * a) * 1.6 - 0.05;
    float tooth = clamp(c, -1.0, 1.0);
    // The tip rises one module above the radius, the root 1.25 below.
    float rise = tooth > 0.0 ? tooth : tooth * 1.25;
    float edge = MODULE * (n * 0.5 + rise);
    // How fast the edge moves per unit of length round the circle, out at
    // the teeth (nearer the axle the flanks are far away anyway).
    float slope = MODULE * 1.6 * n * abs(sin(n * a)) / max(r, edge);
    float climb = abs(c) < 1.0 ? slope : 0.0;
    climb *= tooth > 0.0 ? 1.0 : 1.25;
    return (r - edge) / sqrt(1.0 + climb * climb);
}

// The windows between the spokes: a ring between the hub and the rim, with s
// spokes left standing across it. Positive outside a window.
float gearWindows(float2 p, float n, float s, float spin) {
    if (s < 1.0) return 1.0;
    float R = MODULE * n * 0.5;
    float hub = max(0.07, 0.2 * R), rim = R - 2.8 * MODULE;
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    float ring = abs(r - 0.5 * (hub + rim)) - 0.5 * (rim - hub);
    float slice = TAU / s;
    float aa = a - slice * floor(a / slice + 0.5);
    float spoke = abs(r * sin(aa)) - (0.022 + 0.03 * R);
    return max(ring, -spoke);
}

// ---- The train ------------------------------------------------------------
// The driver turns; each other gear turns from its parent. Where they touch,
// in direction dir from the parent, the parent's tooth phase n_p(dir - spin_p)
// and the child's n(dir + pi - spin) always add up to half a tooth, so a tooth
// meets a gap: spin = dir + pi - (pi - n_p(dir - spin_p)) / n. That makes the
// child turn -n_p/n times as fast as its parent: its ratio.
// The angles are kept small: each gear's turns so far as a fraction of a
// turn. A minute in, the driver alone is 37 radians round, and cos(48 * a)
// of that rounds differently from cos of the same angle near 0, enough to
// move a tooth's edge by a pixel and break the loop.

struct Train {
    float2 centre[6];
    float spin[6];
};

Train train(float driven, float zoom) {
    Train g;
    float rest[6];
    float ratio[6];
    g.centre[0] = DRIVER * zoom;
    rest[0] = 0.0;
    ratio[0] = 1.0;
    for (int i = 1; i < GEARS; i++) {
        int j = PARENT[i];
        float n = TEETH[i], np = TEETH[j];
        float dir = DIR[i];
        float reach = MODULE * 0.5 * (n + np) * zoom;
        g.centre[i] = g.centre[j] + reach * float2(cos(dir), sin(dir));
        rest[i] = dir + PI - (PI - np * (dir - rest[j])) / n;
        ratio[i] = -ratio[j] * np / n;
    }
    for (int i = 0; i < GEARS; i++) {
        g.spin[i] = rest[i] + TAU * fract(ratio[i] * driven);
    }
    return g;
}

// How many turns the driver has made at time t (clockwise, so negative): two
// ticks a second, each a step that springs and settles (an escapement), or
// smooth turning with tick 0. At t = 60 the count is 120 ticks exactly, and
// the driver has made `turns` whole turns.
float driverTurns(float t, float turns, float tick) {
    float x = t * TICKS / LOOP;
    float f = fract(x);
    float settle = 1.0 - exp(-f * 22.0) * cos(f * 34.0);
    float ticked = floor(x) + settle;
    return -turns * mix(x, ticked, tick) / TICKS;
}

// The whole train's distance: its nearest gear, and which one it is.
float trainDistance(float2 q, Train g, float zoom, thread int& id) {
    float d = 1e3;
    for (int i = 0; i < GEARS; i++) {
        float2 p = (q - g.centre[i]) / zoom;
        float n = TEETH[i];
        float gd = length(p) - MODULE * (n * 0.5 + 1.0);
        // Only near a gear is its tooth profile worth working out.
        if (gd < 0.05) {
            float s = g.spin[i];
            gd = max(gearEdge(p, n, s), -gearWindows(p, n, SPOKES[i], s));
        }
        gd *= zoom;
        if (gd < d) { d = gd; id = i; }
    }
    return d;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float t = u.time;
    float turns = max(floor(p.turns + 0.5), 1.0);
    float zoom = p.size;

    Train g = train(driverTurns(t, turns, p.tick), zoom);

    int id = 0;
    float d = trainDistance(q, g, zoom, id);
    int shadowId = 0;
    float shadow = trainDistance(q - float2(0.035, -0.05), g, zoom, shadowId);

    // The wall: dark smoke drifting round a circle once a minute, so it loops
    // too, and the kiln's glow rising from below the picture.
    float2 drift = 0.35 * float2(cos(TAU * t / LOOP), sin(TAU * t / LOOP));
    float wall = 0.05 + 0.12 * fbm(q * 1.6 + drift);
    float kilnGlow = exp(-length(q - float2(0.0, -1.5)) * 1.1);
    wall += 0.2 * kilnGlow;
    wall *= 1.0 - 0.55 * (1.0 - smoothstep(-0.02, 0.06, shadow));

    // The metal, brushed in rings round its axle, warmer lower down.
    float2 local = (q - g.centre[id]) / zoom;
    float r = length(local);
    float n = TEETH[id];
    float R = MODULE * n * 0.5;
    float2 radial = local / max(r, 1e-4);
    float brush = vnoise(float2(r * 420.0, float(id) * 13.0));
    // A streak of light through the axle that stays put as it turns.
    float sheen = pow(abs(radial.y), 12.0) * (radial.y < 0.0 ? 0.16 : 0.07);
    float metal = 0.27 + 0.035 * brush + sheen + 0.14 * kilnGlow;
    metal -= 0.05 * local.y / max(R, 0.1);
    metal += (p.heat - 0.5) * 0.4;
    // A bevel round each edge, lit where it faces down to the kiln.
    float outer = gearEdge(local, n, g.spin[id]) * zoom;
    float window = gearWindows(local, n, SPOKES[id], g.spin[id]) * zoom;
    float2 facing = outer > -window ? radial : -radial;
    float bevel = 1.0 - smoothstep(0.0, 0.018, -d);
    float lit = 0.5 + 0.5 * dot(facing, float2(0.0, -1.0));
    metal += bevel * (0.12 + 0.36 * lit * p.glow);
    // The axle cap, and the hot mark that shows each gear's turn.
    float axle = r - 0.035;
    metal = mix(metal, 0.72, 1.0 - smoothstep(-px, px, axle * zoom));
    metal = mix(metal, 0.08, 1.0 - smoothstep(-px, px, (r - 0.012) * zoom));
    float onSpoke = 0.5 * (max(0.07, 0.2 * R) + R - 2.8 * MODULE);
    float reach = SPOKES[id] > 0.0 ? onSpoke : 0.6 * R;
    float2 mark = reach * float2(cos(g.spin[id]), sin(g.spin[id]));
    float rivet = length(local - mark) - 0.022;
    metal = mix(metal, 0.93, 1.0 - smoothstep(-px, px, rivet * zoom));

    float heat = mix(metal, wall, smoothstep(-px, px, d));
    // A thin dark line round every gear, so two that touch still read as two.
    heat *= 0.55 + 0.45 * smoothstep(0.0, 1.5 * px, abs(d));
    return float4(kiln(heat), 1.0);
}

// ---- Sound ----------------------------------------------------------------
// The same clock in time. Two ticks a second, a tick and a tock a little
// lower, each a burst of noise ringing a small metal ping; every time the big
// gear comes round, a bell; under them the low hum of the train turning. Each
// starts from silence at its own moment, and the hum's 55 Hz makes a whole
// number of cycles in a minute, so the sound loops with the picture.

float tickSound(float since, float parity) {
    float attack = 1.0 - exp(-since * 4000.0);
    float sample = floor(since * 48000.0);
    float noise = hash21(float2(sample, parity * 7.1)) * 2.0 - 1.0;
    float click = noise * exp(-since * 700.0);
    float f = parity > 0.5 ? 1850.0 : 2400.0;
    float ping = sin(TAU * f * since) * exp(-since * 55.0);
    return (0.6 * click + ping) * attack;
}

float gearBell(float since) {
    float attack = 1.0 - exp(-since * 900.0);
    float b = sin(TAU * 392.0 * since) * exp(-since * 0.9);
    b += 0.5 * sin(TAU * 392.0 * 2.76 * since) * exp(-since * 2.2);
    b += 0.25 * sin(TAU * 392.0 * 5.40 * since) * exp(-since * 4.0);
    return b * attack;
}

float2 sound(float t, constant Params& p) {
    float turns = max(floor(p.turns + 0.5), 1.0);
    float x = t * TICKS / LOOP;
    float k = floor(x);
    float since = fract(x) * LOOP / TICKS;
    float parity = k - 2.0 * floor(k * 0.5);
    float tk = tickSound(since, parity);
    // The tick sits a little left, the tock a little right.
    float2 side = parity > 0.5 ? float2(0.75, 1.0) : float2(1.0, 0.75);
    float2 ticks = tk * side * 0.4;

    // A bell each turn of the driver: the turn's count, and the one before
    // still ringing under it.
    float turn = t * turns / LOOP;
    float ring = 0.0;
    for (int back = 0; back < 2; back++) {
        float since2 = (fract(turn) + float(back)) * LOOP / turns;
        if (floor(turn) - float(back) >= 0.0) ring += gearBell(since2);
    }
    float2 bells = float2(ring, ring) * 0.2;

    float hum = sin(TAU * 55.0 * t) + 0.35 * sin(TAU * 110.0 * t);
    float2 drone = float2(hum, hum) * 0.075;

    return tanh((ticks + bells + drone) * 1.5) * p.volume;
}
5 lines from stage 4 that are gone
    Train g = train(-turns * u.time / LOOP, zoom);
⋯
    float R = MODULE * TEETH[id] * 0.5;
    float metal = 0.5;
⋯
    metal = mix(metal, 0.72, 1.0 - smoothstep(-px, px, (r - 0.035) * zoom));
⋯
    float heat = mix(metal, 0.1, smoothstep(-px, px, d));

The sound

The same clock, heard. Two ticks a second, on the same 120 counts as the picture's escapement: a tick, then a tock. Each is a burst of noise dying away in about a millisecond and a half (e^(−700 s)) that strikes a small metal ping, 2,400 Hz for the tick and 1,850 Hz for the tock, ringing out over about a tenth of a second; the tick sits a little left and the tock a little right. Each time the big gear comes round (every 10 s at 6 turns), a bell: G4 (392 Hz) with partials at 2.76 and 5.4 times it, dying away over a few seconds. Under all of it a hum at 55 and 110 Hz, the train turning. tanh rounds off the loudest moments.

Every sound starts from silence at its own moment and the hum makes a whole number of cycles in a minute, so the sound comes round with the picture: each tick, tock and bell falls at the same moment of every minute. Sample for sample it isn't quite identical, since the click's noise is hashed from the time and at 60 s the time rounds by part of a sample. At the defaults the peak is about −3.8 dBFS and the average (RMS) about −21.2 dBFS over the minute; with volume at its highest and turns at 12, −1.9 dBFS and −18.4 dBFS.

New in Ray Kiln

The loop check in the playground. Press Loop check under the picture (or L) and the playground draws two stills off screen, as an export draws them: the first frame and the frame at the shader's // @length. It shows them side by side with their difference, made eight times brighter, in ember where a pixel differs by more than 2/255. Under them it says whether the shader loops seamlessly. A recording of a shader that does loop can play round and round without a jump.

Rounding is allowed for. A difference of up to 2/255 counts as the same picture. So do a few lone pixels (at most 1 in 10,000, none touching another), which happen where two shapes meet and rounding tips a pixel from one to the other. A seam a viewer would see is a patch of pixels, so a patch never passes. The check looks at shaders without state: fragment, grid and mesh shaders that don't read a camera, a microphone or their last frame. It redraws a moment after the code or a slider changes, and it uses the sliders as they are.

Open Clockwork in the playground and press Loop check: it says Clockwork loops seamlessly (in Safari, the frame at 60 s is the first frame to within 1/255). Now set turns to 7. The verdict says it doesn't loop, and the difference goes dark except for a few small dots: each mark that moved, where it was and where it is now. In 7 turns the driver passes 168 teeth, and every other gear turns by the same 168 of its own teeth, so teeth always land on teeth, and here the spokes do too. What gives it away is the hot marks. The 36-tooth gear has made 4⅔ turns, the 16 and 48-tooth gears 10½ and 3½, and the 18-tooth gear 9⅓, so their marks are somewhere else. The driver and the 12-tooth gear make 7 and 14 whole turns, and theirs stay put. Only 6 and 12 turns loop. Then try it on any other shader with a // @length, or on your own.

Try this

  • Set tick to 0 for smooth turning, or to 1 for the full jump and settle of each beat.
  • Set turns to 12 and the loop check still passes: every gear makes twice as many whole turns. Any other value fails it.
  • Set size to 0.6 to see the whole train at once, and to 1.6 to look closely at two gears meshing.
  • Set heat to 0 for dark iron, or to 1 for brass glowing almost white, and glow to 0 to put the kiln out.
  • In the code, change a gear's teeth in TEETH (say 16 to 20) and press Loop check: the gear still meshes, because train places it from its teeth, but 20 doesn't divide 144, and the loop breaks.

Parameters

ParameterDefaultRangeWhat it does
turns61 to 12How many times the big gear turns in a minute, in whole turns
tick0.80 to 1From smooth turning (0) to the step and settle of an escapement (1)
size10.6 to 1.6How big the gears are on screen
heat0.50 to 1The metal from cool iron (0) to white-hot brass (1)
glow0.60 to 1How brightly the kiln below lights the edges
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.

clockwork.metal
// Ray Kiln · Clockwork
//
// @episode Clockwork
// @length 60
// @variation 30
// @variations 1,2,4,5,6,9,11,12
// @sweeps size, heat, glow
// @still 21.3
// @teaches Gears from 2D distance fields, teeth that mesh, ratios that loop
// @category Fragment
// @tags gears, signed distance fields, polar coordinates, gear ratios, seamless loop, procedural sound
// @final Clockwork | The train ticks like an escapement, lit from the kiln below, and a minute later every gear is back where it began.
//
// Six gears in front of the kiln, each one a distance field in polar
// coordinates: a circle whose edge rises into a tooth and falls into a gap as
// the angle goes round. A gear sits beside the gear that drives it, as far
// from it as their two radii added, and turns the other way, slower by the
// ratio of their teeth, with its teeth set half a tooth over so they fall into
// the other's gaps. The big gear turns six times a minute. Each gear's tooth
// count divides six times its 24 teeth, so in sixty seconds every gear turns
// a whole number of times, and the minute loops: the frame at 60 s is the
// first frame again.
// 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 turns 6 1 12 How many times the big gear turns in a minute, in whole turns
// @param tick 0.8 0 1 From smooth turning (0) to the step and settle of an escapement (1)
// @param size 1 0.6 1.6 How big the gears are on screen
// @param heat 0.5 0 1 The metal from cool iron (0) to white-hot brass (1)
// @param glow 0.6 0 1 How brightly the kiln below lights the edges
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The loop: sixty seconds, two ticks a second.
constant float LOOP = 60.0;
constant float TICKS = 120.0;
// The size of a tooth: a gear's radius is MODULE times half its teeth, so any
// two gears with the same module mesh.
constant float MODULE = 0.04;
// The train: each gear's teeth, the gear that drives it, the direction from
// that gear's center to its own, and its spokes. The first is the driver.
constant int GEARS = 6;
constant float TEETH[6] = {24.0, 36.0, 12.0, 16.0, 48.0, 18.0};
constant int PARENT[6] = {-1, 0, 0, 1, 0, 1};
constant float DIR[6] = {0.0, -0.2, 2.3, 1.6, -1.9, -0.9};
constant float SPOKES[6] = {6.0, 6.0, 0.0, 4.0, 8.0, 3.0};
constant float2 DRIVER = float2(-0.35, 0.05);

// ---- Noise (Flowing Color Field) ------------------------------------------

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 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 fbm(float2 p) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < 4; i++) {
        v += a * vnoise(p);
        p = p * 2.03 + float2(17.1, 9.2);
        a *= 0.5;
    }
    return v;
}

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));
}

// ---- A gear ---------------------------------------------------------------
// In polar coordinates round its center, a gear's edge is its radius plus a
// tooth profile: cos(n * a) clamped, so each tooth has a flat top, a flat
// root and straight flanks, one tooth every 1/n of a turn. Its distance is
// the radius minus the edge, divided by how steeply the edge climbs, so the
// flanks are as sharp as the round parts.

float gearEdge(float2 p, float n, float spin) {
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    a -= TAU * floor(a / TAU);
    float c = cos(n * a) * 1.6 - 0.05;
    float tooth = clamp(c, -1.0, 1.0);
    // The tip rises one module above the radius, the root 1.25 below.
    float rise = tooth > 0.0 ? tooth : tooth * 1.25;
    float edge = MODULE * (n * 0.5 + rise);
    // How fast the edge moves per unit of length round the circle, out at
    // the teeth (nearer the axle the flanks are far away anyway).
    float slope = MODULE * 1.6 * n * abs(sin(n * a)) / max(r, edge);
    float climb = abs(c) < 1.0 ? slope : 0.0;
    climb *= tooth > 0.0 ? 1.0 : 1.25;
    return (r - edge) / sqrt(1.0 + climb * climb);
}

// The windows between the spokes: a ring between the hub and the rim, with s
// spokes left standing across it. Positive outside a window.
float gearWindows(float2 p, float n, float s, float spin) {
    if (s < 1.0) return 1.0;
    float R = MODULE * n * 0.5;
    float hub = max(0.07, 0.2 * R), rim = R - 2.8 * MODULE;
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    float ring = abs(r - 0.5 * (hub + rim)) - 0.5 * (rim - hub);
    float slice = TAU / s;
    float aa = a - slice * floor(a / slice + 0.5);
    float spoke = abs(r * sin(aa)) - (0.022 + 0.03 * R);
    return max(ring, -spoke);
}

// ---- The train ------------------------------------------------------------
// The driver turns; each other gear turns from its parent. Where they touch,
// in direction dir from the parent, the parent's tooth phase n_p(dir - spin_p)
// and the child's n(dir + pi - spin) always add up to half a tooth, so a tooth
// meets a gap: spin = dir + pi - (pi - n_p(dir - spin_p)) / n. That makes the
// child turn -n_p/n times as fast as its parent: its ratio.
// The angles are kept small: each gear's turns so far as a fraction of a
// turn. A minute in, the driver alone is 37 radians round, and cos(48 * a)
// of that rounds differently from cos of the same angle near 0, enough to
// move a tooth's edge by a pixel and break the loop.

struct Train {
    float2 centre[6];
    float spin[6];
};

Train train(float driven, float zoom) {
    Train g;
    float rest[6];
    float ratio[6];
    g.centre[0] = DRIVER * zoom;
    rest[0] = 0.0;
    ratio[0] = 1.0;
    for (int i = 1; i < GEARS; i++) {
        int j = PARENT[i];
        float n = TEETH[i], np = TEETH[j];
        float dir = DIR[i];
        float reach = MODULE * 0.5 * (n + np) * zoom;
        g.centre[i] = g.centre[j] + reach * float2(cos(dir), sin(dir));
        rest[i] = dir + PI - (PI - np * (dir - rest[j])) / n;
        ratio[i] = -ratio[j] * np / n;
    }
    for (int i = 0; i < GEARS; i++) {
        g.spin[i] = rest[i] + TAU * fract(ratio[i] * driven);
    }
    return g;
}

// How many turns the driver has made at time t (clockwise, so negative): two
// ticks a second, each a step that springs and settles (an escapement), or
// smooth turning with tick 0. At t = 60 the count is 120 ticks exactly, and
// the driver has made `turns` whole turns.
float driverTurns(float t, float turns, float tick) {
    float x = t * TICKS / LOOP;
    float f = fract(x);
    float settle = 1.0 - exp(-f * 22.0) * cos(f * 34.0);
    float ticked = floor(x) + settle;
    return -turns * mix(x, ticked, tick) / TICKS;
}

// The whole train's distance: its nearest gear, and which one it is.
float trainDistance(float2 q, Train g, float zoom, thread int& id) {
    float d = 1e3;
    for (int i = 0; i < GEARS; i++) {
        float2 p = (q - g.centre[i]) / zoom;
        float n = TEETH[i];
        float gd = length(p) - MODULE * (n * 0.5 + 1.0);
        // Only near a gear is its tooth profile worth working out.
        if (gd < 0.05) {
            float s = g.spin[i];
            gd = max(gearEdge(p, n, s), -gearWindows(p, n, SPOKES[i], s));
        }
        gd *= zoom;
        if (gd < d) { d = gd; id = i; }
    }
    return d;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float t = u.time;
    float turns = max(floor(p.turns + 0.5), 1.0);
    float zoom = p.size;

    Train g = train(driverTurns(t, turns, p.tick), zoom);

    int id = 0;
    float d = trainDistance(q, g, zoom, id);
    int shadowId = 0;
    float shadow = trainDistance(q - float2(0.035, -0.05), g, zoom, shadowId);

    // The wall: dark smoke drifting round a circle once a minute, so it loops
    // too, and the kiln's glow rising from below the picture.
    float2 drift = 0.35 * float2(cos(TAU * t / LOOP), sin(TAU * t / LOOP));
    float wall = 0.05 + 0.12 * fbm(q * 1.6 + drift);
    float kilnGlow = exp(-length(q - float2(0.0, -1.5)) * 1.1);
    wall += 0.2 * kilnGlow;
    wall *= 1.0 - 0.55 * (1.0 - smoothstep(-0.02, 0.06, shadow));

    // The metal, brushed in rings round its axle, warmer lower down.
    float2 local = (q - g.centre[id]) / zoom;
    float r = length(local);
    float n = TEETH[id];
    float R = MODULE * n * 0.5;
    float2 radial = local / max(r, 1e-4);
    float brush = vnoise(float2(r * 420.0, float(id) * 13.0));
    // A streak of light through the axle that stays put as it turns.
    float sheen = pow(abs(radial.y), 12.0) * (radial.y < 0.0 ? 0.16 : 0.07);
    float metal = 0.27 + 0.035 * brush + sheen + 0.14 * kilnGlow;
    metal -= 0.05 * local.y / max(R, 0.1);
    metal += (p.heat - 0.5) * 0.4;
    // A bevel round each edge, lit where it faces down to the kiln.
    float outer = gearEdge(local, n, g.spin[id]) * zoom;
    float window = gearWindows(local, n, SPOKES[id], g.spin[id]) * zoom;
    float2 facing = outer > -window ? radial : -radial;
    float bevel = 1.0 - smoothstep(0.0, 0.018, -d);
    float lit = 0.5 + 0.5 * dot(facing, float2(0.0, -1.0));
    metal += bevel * (0.12 + 0.36 * lit * p.glow);
    // The axle cap, and the hot mark that shows each gear's turn.
    float axle = r - 0.035;
    metal = mix(metal, 0.72, 1.0 - smoothstep(-px, px, axle * zoom));
    metal = mix(metal, 0.08, 1.0 - smoothstep(-px, px, (r - 0.012) * zoom));
    float onSpoke = 0.5 * (max(0.07, 0.2 * R) + R - 2.8 * MODULE);
    float reach = SPOKES[id] > 0.0 ? onSpoke : 0.6 * R;
    float2 mark = reach * float2(cos(g.spin[id]), sin(g.spin[id]));
    float rivet = length(local - mark) - 0.022;
    metal = mix(metal, 0.93, 1.0 - smoothstep(-px, px, rivet * zoom));

    float heat = mix(metal, wall, smoothstep(-px, px, d));
    // A thin dark line round every gear, so two that touch still read as two.
    heat *= 0.55 + 0.45 * smoothstep(0.0, 1.5 * px, abs(d));
    return float4(kiln(heat), 1.0);
}

// ---- Sound ----------------------------------------------------------------
// The same clock in time. Two ticks a second, a tick and a tock a little
// lower, each a burst of noise ringing a small metal ping; every time the big
// gear comes round, a bell; under them the low hum of the train turning. Each
// starts from silence at its own moment, and the hum's 55 Hz makes a whole
// number of cycles in a minute, so the sound loops with the picture.

float tickSound(float since, float parity) {
    float attack = 1.0 - exp(-since * 4000.0);
    float sample = floor(since * 48000.0);
    float noise = hash21(float2(sample, parity * 7.1)) * 2.0 - 1.0;
    float click = noise * exp(-since * 700.0);
    float f = parity > 0.5 ? 1850.0 : 2400.0;
    float ping = sin(TAU * f * since) * exp(-since * 55.0);
    return (0.6 * click + ping) * attack;
}

float gearBell(float since) {
    float attack = 1.0 - exp(-since * 900.0);
    float b = sin(TAU * 392.0 * since) * exp(-since * 0.9);
    b += 0.5 * sin(TAU * 392.0 * 2.76 * since) * exp(-since * 2.2);
    b += 0.25 * sin(TAU * 392.0 * 5.40 * since) * exp(-since * 4.0);
    return b * attack;
}

float2 sound(float t, constant Params& p) {
    float turns = max(floor(p.turns + 0.5), 1.0);
    float x = t * TICKS / LOOP;
    float k = floor(x);
    float since = fract(x) * LOOP / TICKS;
    float parity = k - 2.0 * floor(k * 0.5);
    float tk = tickSound(since, parity);
    // The tick sits a little left, the tock a little right.
    float2 side = parity > 0.5 ? float2(0.75, 1.0) : float2(1.0, 0.75);
    float2 ticks = tk * side * 0.4;

    // A bell each turn of the driver: the turn's count, and the one before
    // still ringing under it.
    float turn = t * turns / LOOP;
    float ring = 0.0;
    for (int back = 0; back < 2; back++) {
        float since2 = (fract(turn) + float(back)) * LOOP / turns;
        if (floor(turn) - float(back) >= 0.0) ring += gearBell(since2);
    }
    float2 bells = float2(ring, ring) * 0.2;

    float hum = sin(TAU * 55.0 * t) + 0.35 * sin(TAU * 110.0 * t);
    float2 drone = float2(hum, hum) * 0.075;

    return tanh((ticks + bells + drone) * 1.5) * p.volume;
}

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] = [6, 0.8, 1, 0.5, 0.6, 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 Shapes & Symmetry