Shader

Spirograph

A toothed wheel rolls round inside a fixed ring with a pen in one of its holes, and the pen draws nine long petals over 32 seconds. The curve is a hypotrochoid, a circle's motion added to a turn the other way, and when the wheel is 4/9 of the ring it closes after the wheel's center has gone round 4 times. A curve like this has no simple distance, so the shader cuts it into 240 straight segments and lights each pixel by its distance to the nearest one, walking along them with a complex multiply instead of a sine per step. Fresh ink is white-hot and cools to ember, gear teeth mesh as the wheel rolls, and the pen's voice swings left and right with it.

· Shapes & Symmetry · Fragment shader

Teaches Curves from wheels inside wheels, drawn as distance fields

Builds on Flowing Color Field, Morphing Shapes (circle distance), Fractal Glow (complex multiply), Murmuration (segment distance), Pulse Synth (line from a distance), Deep Zoom, Plucked Strings (time in the loop)

Watch

The idea

A Spirograph is a toothed plastic ring held down on the paper, a smaller toothed wheel that rolls round inside it, and a pen pushed through one of the holes in the wheel. The teeth keep the wheel from slipping, so where the pen goes depends only on the sizes and the hole.

Call the ring's radius R, the wheel's r, and the pen's distance from the wheel's center d. The wheel's center stays R − r from the middle, so it goes round a circle. As it goes round by an angle t, the wheel rolls along the ring without slipping, and it spins the other way by (R − r) / r times t. The pen adds the two motions:

x = (R − r) cos t + d cos((R − r) t / r), y = (R − r) sin t − d sin((R − r) t / r)

That curve is a hypotrochoid. When r / R is a fraction m / n in lowest terms, it closes after the wheel's center has gone round m times, with n petals, each tip 360 / n degrees from the next. Here the wheel is 4/9 of the ring: 9 petals in 4 turns.

To draw it, a shader needs each pixel's distance to the curve, and a curve like this has no simple formula for that. So the shader cuts it into 240 straight segments, a polyline, and takes each pixel's distance to the nearest one. All lengths are in picture heights, measured from the middle of the picture: the ring is 0.36, the wheel 0.16, its center 0.20 from the middle, and the pen 0.128 from the wheel's center. It is built in five steps.

Stage 1 · A ring and a wheel

The ring and the wheel are drawn from their distance fields: sdCircle is a pixel's distance from a circle's center minus its radius, so it is zero on the circle, and lineAt lights a pixel where its absolute value is within a pixel or two of zero. The wheel is R · 4 / 9, and its center is a = R − r from the middle. The pen sits on an arm from the wheel's center, d = pen · r out, and the arm is a segment: lit by the distance to the nearest point on it, as in Plucked Strings. With pen at 0 there is no arm.

The center goes round 4 times in 32 seconds at speed 1, once every 8 seconds, and the wheel spins the other way, a / r = 1.25 times as fast. Every color is a place on the kiln palette from Flowing Color Field: the ring at 0.38 and the wheel at 0.34, both dull red, and the pen at 1, white-hot.

The sound for now is two tones: the ring at 110 Hz and the wheel at 9/4 of that, 247.5 Hz, the smaller wheel higher, as its size is 4/9 of the ring's.

stage-1-a-ring-and-a-wheel.metal
// Stage 1 · A ring and a wheel
// A ring is fixed in the middle and a wheel 4 / 9 its size rolls round
// inside it. Each is drawn from its distance field: a pixel's distance to a
// circle is its distance to the center minus the radius, lit where that is
// within a pixel of zero.

// @param ring 0.36 0.2 0.45 The fixed ring's radius, in picture heights
// @param pen 0.8 0 1 How far out on the wheel the pen sits: 1 is the rim
// @param speed 1 0.25 2 How fast the wheel rolls
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;

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

// The distance from p to a circle of radius r round the origin: negative
// inside it.
float sdCircle(float2 p, float r) {
    return length(p) - r;
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float px = 1.0 / u.resolution.y;
    // Lengths are in picture heights, measured from the middle.
    float2 q = float2(uv.x * aspect, uv.y) - float2(0.5 * aspect, 0.5);
    float R = p.ring * min(aspect, 1.0);
    float r = R * 4.0 / 9.0;
    float a = R - r;
    float d = p.pen * r;

    // Rolling without slipping: as the center goes round by t, the wheel
    // spins the other way by (R - r) / r times t.
    float t = TAU * 4.0 * u.time * p.speed / 32.0;
    float2 c = a * float2(cos(t), sin(t));
    float spin = -(a / r) * t;
    float2 pen = c + d * float2(cos(spin), sin(spin));

    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.001, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(sdCircle(q - c, r)) - 0.001,
                                   1.5 * px));
    // The pen sits on an arm from the wheel's center: a segment, lit from
    // the distance to the nearest point on it. With the pen at the center
    // there is no arm.
    if (d > 0.0001) {
        float arm = segment(q, c, pen) - 0.0012;
        heat = max(heat, 0.5 * lineAt(arm, 1.5 * px));
    }
    heat = max(heat, lineAt(sdCircle(q - pen, 0.007), 1.5 * px));
    return float4(kiln(heat), 1.0);
}

// A sine at f hertz, its phase kept small.
float tone(float f, float t) {
    return sin(TAU * fract(f * t));
}

// The ring hums at 110 Hz and the wheel at 9 / 4 of that, a ninth up.
float2 sound(float t, constant Params& p) {
    float hum = 0.1 * tone(110.0, t) + 0.07 * tone(110.0 * 9.0 / 4.0, t);
    return float2(tanh(1.35 * hum * smoothstep(0.0, 1.5, t))) * p.volume;
}

Stage 2 · The pen's path

penAt is the formula above: the center a from the middle at angle t, plus the pen d from it, turned back by k · t, with k = a / r. The loop walks it in 240 straight segments over the 4 turns, so each step moves the center on by 6° and turns the pen's arm back by 7.5°.

Taking a cosine and a sine at every step would cost 480 of each per pixel. Instead each part of the pen's place is kept as a unit complex number, e1 and e2, and each step multiplies it by a fixed turn worked out once before the loop. cmul, which grew Fractal Glow's distance estimate and stepped Deep Zoom's dive, multiplies two complex numbers: the lengths multiply and the angles add, so multiplying by a turn of 6° moves a point 6° round its circle. The next corner is a · e1 + d · e2, and the pixel's distance to the curve is the smallest of its distances to the 240 segments. Here the whole path is drawn at once, and the machine rolls over it with the pen always on it.

stage-2-the-pens-path.metal25 new lines since stage 1
// Stage 2 · The pen's path
// The pen draws x = (R - r) cos t + d cos((R - r) t / r),
// y = (R - r) sin t - d sin((R - r) t / r). A curve has no simple distance,
// so it is cut into 240 straight segments, and a pixel's distance to it is
// its distance to the nearest one.

// @param ring 0.36 0.2 0.45 The fixed ring's radius, in picture heights
// @param pen 0.8 0 1 How far out on the wheel the pen sits: 1 is the rim
// @param speed 1 0.25 2 How fast the wheel rolls
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;

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

// The distance from p to a circle of radius r round the origin: negative
// inside it.
float sdCircle(float2 p, float r) {
    return length(p) - r;
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Two complex numbers multiplied: lengths multiply, angles add.
float2 cmul(float2 a, float2 b) {
    return float2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}

// Where the pen is once the wheel's center has gone round by angle t: the
// center a from the middle, the pen d from it, turned back by k t.
float2 penAt(float t, float a, float d, float k) {
    return a * float2(cos(t), sin(t)) + d * float2(cos(k * t), -sin(k * t));
}

// The pen's path is drawn as 240 straight segments.
constant float SEGMENTS = 240.0;

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float px = 1.0 / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y) - float2(0.5 * aspect, 0.5);
    float R = p.ring * min(aspect, 1.0);
    float r = R * 4.0 / 9.0;
    float a = R - r;
    float d = p.pen * r;
    float k = a / r;

    // With r / R = 4 / 9, the path closes after the center goes round 4
    // times. The segments split those 4 turns evenly. Each step turns the
    // pen's two parts by a fixed angle, a complex multiply, so the loop
    // needs no sines.
    float h = TAU * 4.0 / SEGMENTS;
    float2 turn1 = float2(cos(h), sin(h));
    float2 turn2 = float2(cos(k * h), -sin(k * h));
    float2 e1 = float2(1.0, 0.0);
    float2 e2 = float2(1.0, 0.0);
    float2 prev = float2(a + d, 0.0);
    float near = 1e9;
    for (int i = 0; i < 240; i++) {
        e1 = cmul(e1, turn1);
        e2 = cmul(e2, turn2);
        float2 next = a * e1 + d * e2;
        near = min(near, segment(q, prev, next));
        prev = next;
    }

    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));
    heat = max(heat, 0.5 * lineAt(near - 0.0012, 1.5 * px));

    // The machine rolls over the finished path, the pen always on it.
    float t = TAU * 4.0 * u.time * p.speed / 32.0;
    float2 c = a * float2(cos(t), sin(t));
    float2 pen = penAt(t, a, d, k);
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.001, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(sdCircle(q - c, r)) - 0.001,
                                   1.5 * px));
    if (d > 0.0001) {
        float arm = segment(q, c, pen) - 0.0012;
        heat = max(heat, 0.5 * lineAt(arm, 1.5 * px));
    }
    heat = max(heat, lineAt(sdCircle(q - pen, 0.007), 1.5 * px));
    return float4(kiln(heat), 1.0);
}

// A sine at f hertz, its phase kept small.
float tone(float f, float t) {
    return sin(TAU * fract(f * t));
}

// The ring hums at 110 Hz and the wheel at 9 / 4 of that.
float2 sound(float t, constant Params& p) {
    float hum = 0.1 * tone(110.0, t) + 0.07 * tone(110.0 * 9.0 / 4.0, t);
    return float2(tanh(1.35 * hum * smoothstep(0.0, 1.5, t))) * p.volume;
}
3 lines from stage 1 that are gone
    float spin = -(a / r) * t;
    float2 pen = c + d * float2(cos(spin), sin(spin));
⋯
    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));

Stage 3 · Petals and turns

Now the sizes come from two whole numbers. petals, n, is rounded and held between 3 and 12; turns, m, is rounded and held below n. The wheel is R · m / n. If m and n share a factor, the curve would close sooner and have fewer petals, so turnsOf moves m to the nearest number that shares none: one less, one more, two less, two more. sharedFactor finds the largest number dividing both by Euclid's rule, taking the remainder of one by the other until nothing is left.

Each petal gets the same number of segments, floor(240 / n): 20 for this stage's 12 petals, all 240 used; 26 for 9 petals, 234 in all. The tips come where the pen's arm points straight out from the middle, every m / n of a turn of the center, and that is a whole number of segments, so a corner falls on every tip and the points stay sharp. This stage shows 12 petals in 5 turns. The wheel's tone is n / m times 110 Hz, here 264 Hz.

stage-3-petals-and-turns.metal33 new lines since stage 2
// Stage 3 · Petals and turns
// When the wheel's radius is m / n of the ring's, in lowest terms, the
// curve closes after the center goes round m times, with n petals 360 / n
// degrees apart. Each petal gets the same number of segments, so a corner
// falls on every tip.

// @param ring 0.36 0.2 0.45 The fixed ring's radius, in picture heights
// @param petals 12 3 12 How many petals the curve has
// @param turns 5 1 5 Times the wheel goes round before the curve closes
// @param pen 0.8 0 1 How far out on the wheel the pen sits: 1 is the rim
// @param speed 1 0.25 2 How fast the wheel rolls
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;

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

// The distance from p to a circle of radius r round the origin: negative
// inside it.
float sdCircle(float2 p, float r) {
    return length(p) - r;
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Two complex numbers multiplied: lengths multiply, angles add.
float2 cmul(float2 a, float2 b) {
    return float2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}

// Where the pen is once the wheel's center has gone round by angle t: the
// center a from the middle, the pen d from it, turned back by k t.
float2 penAt(float t, float a, float d, float k) {
    return a * float2(cos(t), sin(t)) + d * float2(cos(k * t), -sin(k * t));
}

// The pen's path is drawn as 240 straight segments.
constant float SEGMENTS = 240.0;

// The petals as a whole number, 3 to 12.
float petalsOf(constant Params& p) {
    return clamp(floor(p.petals + 0.5), 3.0, 12.0);
}

// The largest whole number that divides both a and b, by Euclid's rule.
float sharedFactor(float a, float b) {
    for (int i = 0; i < 16; i++) {
        if (b < 0.5) break;
        float rest = a - b * floor(a / b + 0.0001);
        a = b;
        b = rest;
    }
    return a;
}

// The turns as a whole number below the petals. If it shares a factor
// with them, the curve would close sooner with fewer petals, so it moves
// to the nearest number that doesn't: one less, one more, two less...
float turnsOf(constant Params& p) {
    float n = petalsOf(p);
    float m = clamp(floor(p.turns + 0.5), 1.0, n - 1.0);
    for (int i = 0; i < 12; i++) {
        float side = fmod(float(i), 2.0) > 0.5 ? -1.0 : 1.0;
        float c = m + side * floor(float(i + 1) / 2.0);
        if (c < 0.5 || c > n - 0.5) continue;
        if (sharedFactor(n, c) < 1.5) return c;
    }
    return 1.0;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float px = 1.0 / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y) - float2(0.5 * aspect, 0.5);
    float R = p.ring * min(aspect, 1.0);
    float n = petalsOf(p);
    float m = turnsOf(p);
    float r = R * m / n;
    float a = R - r;
    float d = p.pen * r;
    float k = a / r;

    // The m turns are split into n petals of 240 / n segments each.
    float per = floor(SEGMENTS / n);
    float total = per * n;
    float h = TAU * m / total;
    float2 turn1 = float2(cos(h), sin(h));
    float2 turn2 = float2(cos(k * h), -sin(k * h));
    float2 e1 = float2(1.0, 0.0);
    float2 e2 = float2(1.0, 0.0);
    float2 prev = float2(a + d, 0.0);
    float near = 1e9;
    for (int i = 0; i < 240; i++) {
        if (float(i) >= total) break;
        e1 = cmul(e1, turn1);
        e2 = cmul(e2, turn2);
        float2 next = a * e1 + d * e2;
        near = min(near, segment(q, prev, next));
        prev = next;
    }

    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));
    heat = max(heat, 0.5 * lineAt(near - 0.0012, 1.5 * px));

    // The machine rolls over the finished path, the pen always on it.
    float t = TAU * m * u.time * p.speed / 32.0;
    float2 c = a * float2(cos(t), sin(t));
    float2 pen = penAt(t, a, d, k);
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.001, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(sdCircle(q - c, r)) - 0.001,
                                   1.5 * px));
    if (d > 0.0001) {
        float arm = segment(q, c, pen) - 0.0012;
        heat = max(heat, 0.5 * lineAt(arm, 1.5 * px));
    }
    heat = max(heat, lineAt(sdCircle(q - pen, 0.007), 1.5 * px));
    return float4(kiln(heat), 1.0);
}

// A sine at f hertz, its phase kept small.
float tone(float f, float t) {
    return sin(TAU * fract(f * t));
}

// The ring hums at 110 Hz and the wheel at n / m of that: the smaller
// wheel, the higher.
float2 sound(float t, constant Params& p) {
    float high = 110.0 * petalsOf(p) / turnsOf(p);
    float hum = 0.1 * tone(110.0, t) + 0.07 * tone(high, t);
    return float2(tanh(1.35 * hum * smoothstep(0.0, 1.5, t))) * p.volume;
}
4 lines from stage 2 that are gone
    float r = R * 4.0 / 9.0;
⋯
    float h = TAU * 4.0 / SEGMENTS;
⋯
    float t = TAU * 4.0 * u.time * p.speed / 32.0;
⋯
    float hum = 0.1 * tone(110.0, t) + 0.07 * tone(110.0 * 9.0 / 4.0, t);

Stage 4 · Drawing it in time

Now the pen draws as the wheel rolls. The piece is 40 seconds at speed 1: loopTime wraps the time into it, the center goes round m times over the first 32 seconds, and inkLeft fades the ink out between 36 and 39.5 seconds, so at 40 it starts again from the first frame. The defaults are back to 9 petals in 4 turns.

The loop stops at the segment the pen has reached, and that last one ends exactly under the pen, so the line grows smoothly rather than a segment at a time. Each segment knows when it was drawn, from its angle over the rate the center turns, and warmth takes its age: 1, white-hot, when fresh, cooling toward 0.46, ember, with a time constant of 3 seconds. Where the curve crosses itself, the hotter strand shows.

The pen reaches a tip every 32 / 9 seconds, about 3.6, and each time a soft tick sounds: 1,760 Hz, rising in 3 ms and dying away over 40 ms. The tips come 160° apart, four of the 40° between neighbors, since the center goes 4/9 of a turn from one tip to the next.

stage-4-drawing-it-in-time.metal45 new lines since stage 3
// Stage 4 · Drawing it in time
// Now the wheel draws as it rolls, m turns in 32 seconds, and only the
// segments the pen has passed are drawn. Each knows when it was drawn, so
// it starts white-hot and cools along the kiln palette to ember.

// @param ring 0.36 0.2 0.45 The fixed ring's radius, in picture heights
// @param petals 9 3 12 How many petals the curve has
// @param turns 4 1 5 Times the wheel goes round before the curve closes
// @param pen 0.8 0 1 How far out on the wheel the pen sits: 1 is the rim
// @param speed 1 0.25 2 How fast the wheel rolls: 1 draws the curve in 32 seconds
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;

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

// The distance from p to a circle of radius r round the origin: negative
// inside it.
float sdCircle(float2 p, float r) {
    return length(p) - r;
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Two complex numbers multiplied: lengths multiply, angles add.
float2 cmul(float2 a, float2 b) {
    return float2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}

// Where the pen is once the wheel's center has gone round by angle t: the
// center a from the middle, the pen d from it, turned back by k t.
float2 penAt(float t, float a, float d, float k) {
    return a * float2(cos(t), sin(t)) + d * float2(cos(k * t), -sin(k * t));
}

// The pen's path is drawn as 240 straight segments.
constant float SEGMENTS = 240.0;

// The petals as a whole number, 3 to 12.
float petalsOf(constant Params& p) {
    return clamp(floor(p.petals + 0.5), 3.0, 12.0);
}

// The largest whole number that divides both a and b, by Euclid's rule.
float sharedFactor(float a, float b) {
    for (int i = 0; i < 16; i++) {
        if (b < 0.5) break;
        float rest = a - b * floor(a / b + 0.0001);
        a = b;
        b = rest;
    }
    return a;
}

// The turns as a whole number below the petals. If it shares a factor
// with them, the curve would close sooner with fewer petals, so it moves
// to the nearest number that doesn't: one less, one more, two less...
float turnsOf(constant Params& p) {
    float n = petalsOf(p);
    float m = clamp(floor(p.turns + 0.5), 1.0, n - 1.0);
    for (int i = 0; i < 12; i++) {
        float side = fmod(float(i), 2.0) > 0.5 ? -1.0 : 1.0;
        float c = m + side * floor(float(i + 1) / 2.0);
        if (c < 0.5 || c > n - 0.5) continue;
        if (sharedFactor(n, c) < 1.5) return c;
    }
    return 1.0;
}

// 40 seconds at speed 1: the curve is drawn over the first 32, then the
// ink cools and fades out from 36 s.
constant float LOOP = 40.0;
constant float DRAW = 32.0;

// Time within the piece.
float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// How much ink is left as the piece ends.
float inkLeft(float t) {
    return 1.0 - smoothstep(36.0, 39.5, t);
}

// Fresh ink is white-hot and cools to ember over a few seconds.
float warmth(float age) {
    return 0.46 + 0.54 * exp(-max(age, 0.0) / 3.0);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float px = 1.0 / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y) - float2(0.5 * aspect, 0.5);
    float R = p.ring * min(aspect, 1.0);
    float n = petalsOf(p);
    float m = turnsOf(p);
    float r = R * m / n;
    float a = R - r;
    float d = p.pen * r;
    float k = a / r;

    // The center goes round m times in 32 seconds.
    float t = loopTime(u.time * p.speed);
    float turned = TAU * m * min(t / DRAW, 1.0);
    float rate = TAU * m / DRAW;

    // The m turns are split into n petals of 240 / n segments each.
    float per = floor(SEGMENTS / n);
    float total = per * n;
    float h = TAU * m / total;
    float2 turn1 = float2(cos(h), sin(h));
    float2 turn2 = float2(cos(k * h), -sin(k * h));
    float2 e1 = float2(1.0, 0.0);
    float2 e2 = float2(1.0, 0.0);
    float2 tip = penAt(turned, a, d, k);
    float2 prev = float2(a + d, 0.0);
    float ink = 0.0;
    for (int i = 0; i < 240; i++) {
        if (float(i) >= total) break;
        float t0 = float(i) * h;
        if (t0 >= turned - 0.00001) break;
        e1 = cmul(e1, turn1);
        e2 = cmul(e2, turn2);
        float2 next = a * e1 + d * e2;
        float t1 = t0 + h;
        // The newest segment ends exactly under the pen.
        if (t1 > turned) {
            next = tip;
            t1 = turned;
        }
        float s = segment(q, prev, next);
        // Each segment keeps its own age, so where the curve crosses
        // itself the hotter strand shows.
        float age = t - t1 / rate;
        ink = max(ink, lineAt(s - 0.0012, 1.5 * px) * warmth(age));
        prev = next;
    }

    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));
    heat = max(heat, ink * inkLeft(t));

    // The machine on top, the pen at the end of the ink.
    float2 c = a * float2(cos(turned), sin(turned));
    float2 pen = tip;
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.001, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(sdCircle(q - c, r)) - 0.001,
                                   1.5 * px));
    if (d > 0.0001) {
        float arm = segment(q, c, pen) - 0.0012;
        heat = max(heat, 0.5 * lineAt(arm, 1.5 * px));
    }
    heat = max(heat, lineAt(sdCircle(q - pen, 0.007), 1.5 * px));
    return float4(kiln(heat), 1.0);
}

// A sine at f hertz, its phase kept small.
float tone(float f, float t) {
    return sin(TAU * fract(f * t));
}

// A soft tick, 3 ms up and 40 ms down.
float tick(float since) {
    if (since < 0.0) return 0.0;
    float env = smoothstep(0.0, 0.003, since) * exp(-since / 0.04);
    return env * tone(1760.0, since);
}

// The ring hums at 110 Hz and the wheel at n / m of that, the smaller
// wheel higher. The pen reaches a tip every 32 / n seconds, and ticks.
float2 sound(float t, constant Params& p) {
    float n = petalsOf(p);
    float tl = loopTime(t * p.speed);
    float tr = tl / p.speed;
    float env = smoothstep(0.0, 1.5, tl) * inkLeft(tl);
    float high = 110.0 * n / turnsOf(p);
    float hum = 0.1 * tone(110.0, tr) + 0.07 * tone(high, tr);
    float petal = floor(tl * n / DRAW);
    if (petal >= 1.0 && petal <= n) {
        hum += 0.18 * tick((tl - petal * DRAW / n) / p.speed);
    }
    return float2(tanh(1.35 * hum * env)) * p.volume;
}
9 lines from stage 3 that are gone
    float near = 1e9;
⋯
        near = min(near, segment(q, prev, next));
⋯
    heat = max(heat, 0.5 * lineAt(near - 0.0012, 1.5 * px));
⋯
    float t = TAU * m * u.time * p.speed / 32.0;
    float2 c = a * float2(cos(t), sin(t));
    float2 pen = penAt(t, a, d, k);
⋯
    float high = 110.0 * petalsOf(p) / turnsOf(p);
    float hum = 0.1 * tone(110.0, t) + 0.07 * tone(high, t);
    return float2(tanh(1.35 * hum * smoothstep(0.0, 1.5, t))) * p.volume;

Stage 5 · Spirograph

The finished shader makes the machine look like the toy:

  • Teeth. toothEdge makes a circle wavy, its radius tooth · cos(teeth · angle) in and out. The ring has 12 teeth for each petal, 108, pointing in, and the wheel 12 for each turn, 48, turned with its spin. As R / n = r / m, their teeth are one size, so where they meet, a tip of one sits in a gap of the other. The ring is a band from its toothed inner edge out to 0.03 past R, with a thin brighter line along its pitch circle at R, the circle it rolls on. The wheel is a darker disc with a toothed rim and nine pen holes along one spoke, at tenths of its radius, so at the default pen of 0.8 the pen sits on the 8th.
  • Glowing ink. Fresh ink gets a glow as well, exp(−s / 0.012) around it, fading with a time constant of 1.5 seconds. The curve stays between |a − d| and a + d from the middle, so pixels more than 0.05 outside that skip the loop.
  • Any shape of picture. In a picture taller than wide, fit shrinks everything to the width, so the ring stays whole on a phone.
the kiln palette and shade(), from the finished shader
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float px = 1.0 / u.resolution.y;
    // Lengths are in picture heights, from the middle of the picture. In a
    // picture taller than wide, everything shrinks to fit its width.
    float2 q = float2(uv.x * aspect, uv.y) - float2(0.5 * aspect, 0.5);
    float fit = min(aspect, 1.0);

    // The ring, the wheel, the pen. r / R = m / n.
    float n = petalsOf(p);
    float m = turnsOf(p);
    float R = p.ring * fit;
    float r = R * m / n;
    float a = R - r;
    float d = p.pen * r;
    float k = a / r;

    // The center goes round m times in 32 seconds.
    float t = loopTime(u.time * p.speed);
    float turned = TAU * m * min(t / DRAW, 1.0);
    float rate = TAU * m / DRAW;
    float fade = inkLeft(t);

    // A dark ground, a little warmer toward the middle.
    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));

    // The curve: the pen's path as a polyline of 240 segments, n petals
    // of 240 / n each, so a corner falls on every petal's tip. Each step
    // turns the two parts of the pen's place by a fixed angle, a complex
    // multiply, so no sine is needed inside the loop.
    float per = floor(SEGMENTS / n);
    float total = per * n;
    float h = TAU * m / total;
    float2 turn1 = float2(cos(h), sin(h));
    float2 turn2 = float2(cos(k * h), -sin(k * h));
    float2 e1 = float2(1.0, 0.0);
    float2 e2 = float2(1.0, 0.0);
    float2 tip = penAt(turned, a, d, k);
    float2 prev = float2(a + d, 0.0);
    float ink = 0.0, glow = 0.0;
    // The curve stays between |a - d| and a + d from the middle: pixels
    // farther than a glow's reach skip the loop.
    float dist = length(q);
    bool near = dist > abs(a - d) - 0.05 && dist < a + d + 0.05;
    for (int i = 0; i < 240; i++) {
        if (!near || float(i) >= total) break;
        float t0 = float(i) * h;
        if (t0 >= turned - 0.00001) break;
        e1 = cmul(e1, turn1);
        e2 = cmul(e2, turn2);
        float2 next = a * e1 + d * e2;
        float t1 = t0 + h;
        // The newest segment ends exactly under the pen.
        if (t1 > turned) {
            next = tip;
            t1 = turned;
        }
        float s = segment(q, prev, next);
        // Each segment keeps its own age, so where the curve crosses
        // itself the hotter strand shows.
        float age = t - t1 / rate;
        ink = max(ink, lineAt(s - 0.0012, 1.5 * px) * warmth(age));
        glow = max(glow, exp(-max(age, 0.0) / 1.5) * exp(-s / 0.012));
        prev = next;
    }
    heat = max(heat, ink * fade);
    heat += 0.35 * glow * fade;

    // The ring: a band from its toothed inner edge out 0.03 past R, and a
    // thin line along its pitch circle at R, the radius it rolls on.
    float teeth = 12.0 * n;
    float tooth = 0.24 * TAU * R / teeth;
    float angle = atan2(q.y, q.x);
    float rho = length(q);
    float band = max(toothEdge(angle, R, teeth, tooth) - rho,
                     rho - (R + 0.03 * fit));
    heat = mix(heat, 0.12, lineAt(band, 1.5 * px));
    heat = max(heat, 0.27 * lineAt(abs(band) - 0.0008, 1.5 * px));
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.0006, px));

    // The wheel: its center, how far it has spun, a clear disc with a
    // toothed rim, and a row of pen holes along one spoke.
    float2 c = a * float2(cos(turned), sin(turned));
    float spin = -k * turned;
    float2 w = q - c;
    float2 local = float2(cos(spin) * w.x + sin(spin) * w.y,
                          -sin(spin) * w.x + cos(spin) * w.y);
    float rim = length(w) - toothEdge(atan2(local.y, local.x), r,
                                     12.0 * m, tooth);
    heat = mix(heat, 0.09, 0.45 * lineAt(rim, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(rim) - 0.0008, 1.5 * px));
    float gap = 0.1 * r;
    float j = clamp(floor(local.x / gap + 0.5), 1.0, 9.0);
    float hole = length(local - float2(j * gap, 0.0)) - 0.0035;
    heat = max(heat, 0.22 * lineAt(abs(hole) - 0.0006, 1.5 * px));

    // The arm from the hub to the pen, then the pen, white-hot.
    if (d > 0.0001) {
        float arm = segment(q, c, tip) - 0.0012;
        heat = max(heat, 0.5 * lineAt(arm, 1.5 * px));
    }
    heat = max(heat, 0.5 * lineAt(sdCircle(w, 0.006 * fit), 1.5 * px));
    float penDot = sdCircle(q - tip, 0.007 * fit);
    heat += 0.3 * exp(-max(penDot, 0.0) / 0.01);
    heat = max(heat, lineAt(penDot, 1.5 * px));
    return float4(kiln(heat), 1.0);
}
spirograph.metal, the whole file58 new lines since stage 4
// Ray Kiln · Spirograph
//
// @episode Spirograph
// @length 40
// @variation 30
// @variations 1,7,8,9,10,11,12
// @sweeps pen, petals, turns
// @still 27
// @teaches Curves from wheels inside wheels, drawn as distance fields
// @category Fragment
// @tags spirograph, hypotrochoid, distance field, polyline, gear ratio, rotational symmetry, procedural sound
// @final Spirograph | Gear teeth make the ring and the wheel a machine, the fresh ink glows, and the pen's own voice follows it left and right.
//
// A wheel rolls inside a fixed ring with a pen in one of its holes. The
// wheel's center goes round at R - r from the middle, and the wheel spins
// the other way, (R - r) / r times as fast, so the pen draws
// x = (R - r) cos t + d cos((R - r) t / r),
// y = (R - r) sin t - d sin((R - r) t / r).
// When r / R is a fraction m / n in lowest terms, the curve closes after
// the wheel's center has gone round m times, with n petals.
// The curve is drawn as a distance field: each pixel finds how far it is
// from a polyline of 240 short segments along the pen's path, and lights
// up within a pixel or two of it.
// 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 ring 0.36 0.2 0.45 The fixed ring's radius, in picture heights
// @param petals 9 3 12 How many petals the curve has; the ring has 12 teeth for each
// @param turns 4 1 5 Times the wheel goes round before the curve closes, moved to the nearest number sharing no factor with petals; the wheel has 12 teeth for each
// @param pen 0.8 0 1 How far out on the wheel the pen sits: 1 is the rim, where the petals come to points
// @param speed 1 0.25 2 How fast the wheel rolls: 1 draws the curve in 32 seconds
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;

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

// The distance from p to a circle of radius r round the origin: negative
// inside it.
float sdCircle(float2 p, float r) {
    return length(p) - r;
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Two complex numbers multiplied: lengths multiply, angles add.
float2 cmul(float2 a, float2 b) {
    return float2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}

// Where the pen is once the wheel's center has gone round by angle t: the
// center a from the middle, the pen d from it, turned back by k t.
float2 penAt(float t, float a, float d, float k) {
    return a * float2(cos(t), sin(t)) + d * float2(cos(k * t), -sin(k * t));
}

// The pen's path is drawn as 240 straight segments.
constant float SEGMENTS = 240.0;

// The petals as a whole number, 3 to 12.
float petalsOf(constant Params& p) {
    return clamp(floor(p.petals + 0.5), 3.0, 12.0);
}

// The largest whole number that divides both a and b, by Euclid's rule.
float sharedFactor(float a, float b) {
    for (int i = 0; i < 16; i++) {
        if (b < 0.5) break;
        float rest = a - b * floor(a / b + 0.0001);
        a = b;
        b = rest;
    }
    return a;
}

// The turns as a whole number below the petals. If it shares a factor
// with them, the curve would close sooner with fewer petals, so it moves
// to the nearest number that doesn't: one less, one more, two less...
float turnsOf(constant Params& p) {
    float n = petalsOf(p);
    float m = clamp(floor(p.turns + 0.5), 1.0, n - 1.0);
    for (int i = 0; i < 12; i++) {
        float side = fmod(float(i), 2.0) > 0.5 ? -1.0 : 1.0;
        float c = m + side * floor(float(i + 1) / 2.0);
        if (c < 0.5 || c > n - 0.5) continue;
        if (sharedFactor(n, c) < 1.5) return c;
    }
    return 1.0;
}

// 40 seconds at speed 1: the curve is drawn over the first 32, then the
// ink cools and fades out from 36 s.
constant float LOOP = 40.0;
constant float DRAW = 32.0;

// Time within the piece.
float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// How much ink is left as the piece ends.
float inkLeft(float t) {
    return 1.0 - smoothstep(36.0, 39.5, t);
}

// Fresh ink is white-hot and cools to ember over a few seconds.
float warmth(float age) {
    return 0.46 + 0.54 * exp(-max(age, 0.0) / 3.0);
}

// A toothed edge: how far out it is at this angle. The ring has 12 n teeth
// pointing in, the wheel 12 m. As R / n = r / m they are one size, and
// where they touch, a tip meets a gap.
float toothEdge(float angle, float radius, float teeth, float tooth) {
    return radius - tooth * cos(teeth * angle);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float px = 1.0 / u.resolution.y;
    // Lengths are in picture heights, from the middle of the picture. In a
    // picture taller than wide, everything shrinks to fit its width.
    float2 q = float2(uv.x * aspect, uv.y) - float2(0.5 * aspect, 0.5);
    float fit = min(aspect, 1.0);

    // The ring, the wheel, the pen. r / R = m / n.
    float n = petalsOf(p);
    float m = turnsOf(p);
    float R = p.ring * fit;
    float r = R * m / n;
    float a = R - r;
    float d = p.pen * r;
    float k = a / r;

    // The center goes round m times in 32 seconds.
    float t = loopTime(u.time * p.speed);
    float turned = TAU * m * min(t / DRAW, 1.0);
    float rate = TAU * m / DRAW;
    float fade = inkLeft(t);

    // A dark ground, a little warmer toward the middle.
    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));

    // The curve: the pen's path as a polyline of 240 segments, n petals
    // of 240 / n each, so a corner falls on every petal's tip. Each step
    // turns the two parts of the pen's place by a fixed angle, a complex
    // multiply, so no sine is needed inside the loop.
    float per = floor(SEGMENTS / n);
    float total = per * n;
    float h = TAU * m / total;
    float2 turn1 = float2(cos(h), sin(h));
    float2 turn2 = float2(cos(k * h), -sin(k * h));
    float2 e1 = float2(1.0, 0.0);
    float2 e2 = float2(1.0, 0.0);
    float2 tip = penAt(turned, a, d, k);
    float2 prev = float2(a + d, 0.0);
    float ink = 0.0, glow = 0.0;
    // The curve stays between |a - d| and a + d from the middle: pixels
    // farther than a glow's reach skip the loop.
    float dist = length(q);
    bool near = dist > abs(a - d) - 0.05 && dist < a + d + 0.05;
    for (int i = 0; i < 240; i++) {
        if (!near || float(i) >= total) break;
        float t0 = float(i) * h;
        if (t0 >= turned - 0.00001) break;
        e1 = cmul(e1, turn1);
        e2 = cmul(e2, turn2);
        float2 next = a * e1 + d * e2;
        float t1 = t0 + h;
        // The newest segment ends exactly under the pen.
        if (t1 > turned) {
            next = tip;
            t1 = turned;
        }
        float s = segment(q, prev, next);
        // Each segment keeps its own age, so where the curve crosses
        // itself the hotter strand shows.
        float age = t - t1 / rate;
        ink = max(ink, lineAt(s - 0.0012, 1.5 * px) * warmth(age));
        glow = max(glow, exp(-max(age, 0.0) / 1.5) * exp(-s / 0.012));
        prev = next;
    }
    heat = max(heat, ink * fade);
    heat += 0.35 * glow * fade;

    // The ring: a band from its toothed inner edge out 0.03 past R, and a
    // thin line along its pitch circle at R, the radius it rolls on.
    float teeth = 12.0 * n;
    float tooth = 0.24 * TAU * R / teeth;
    float angle = atan2(q.y, q.x);
    float rho = length(q);
    float band = max(toothEdge(angle, R, teeth, tooth) - rho,
                     rho - (R + 0.03 * fit));
    heat = mix(heat, 0.12, lineAt(band, 1.5 * px));
    heat = max(heat, 0.27 * lineAt(abs(band) - 0.0008, 1.5 * px));
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.0006, px));

    // The wheel: its center, how far it has spun, a clear disc with a
    // toothed rim, and a row of pen holes along one spoke.
    float2 c = a * float2(cos(turned), sin(turned));
    float spin = -k * turned;
    float2 w = q - c;
    float2 local = float2(cos(spin) * w.x + sin(spin) * w.y,
                          -sin(spin) * w.x + cos(spin) * w.y);
    float rim = length(w) - toothEdge(atan2(local.y, local.x), r,
                                     12.0 * m, tooth);
    heat = mix(heat, 0.09, 0.45 * lineAt(rim, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(rim) - 0.0008, 1.5 * px));
    float gap = 0.1 * r;
    float j = clamp(floor(local.x / gap + 0.5), 1.0, 9.0);
    float hole = length(local - float2(j * gap, 0.0)) - 0.0035;
    heat = max(heat, 0.22 * lineAt(abs(hole) - 0.0006, 1.5 * px));

    // The arm from the hub to the pen, then the pen, white-hot.
    if (d > 0.0001) {
        float arm = segment(q, c, tip) - 0.0012;
        heat = max(heat, 0.5 * lineAt(arm, 1.5 * px));
    }
    heat = max(heat, 0.5 * lineAt(sdCircle(w, 0.006 * fit), 1.5 * px));
    float penDot = sdCircle(q - tip, 0.007 * fit);
    heat += 0.3 * exp(-max(penDot, 0.0) / 0.01);
    heat = max(heat, lineAt(penDot, 1.5 * px));
    return float4(kiln(heat), 1.0);
}

// A sine at f hertz, its phase kept small.
float tone(float f, float t) {
    return sin(TAU * fract(f * t));
}

// A soft tick, 3 ms up and 40 ms down.
float tick(float since) {
    if (since < 0.0) return 0.0;
    float env = smoothstep(0.0, 0.003, since) * exp(-since / 0.04);
    return env * tone(1760.0, since);
}

// What you hear: the ring and the wheel as two tones in the ratio n : m,
// the bigger one lower; the pen as a third, an octave over the wheel,
// louder as it swings out to a petal's tip and panned with it left and
// right; and a tick each time the pen reaches a tip.
float2 sound(float t, constant Params& p) {
    float n = petalsOf(p);
    float m = turnsOf(p);
    float tl = loopTime(t * p.speed);
    float tr = tl / p.speed;
    float env = smoothstep(0.0, 1.5, tl) * inkLeft(tl);

    float low = 110.0;
    float high = low * n / m;
    float hum = 0.1 * tone(low, tr) + 0.025 * tone(2.0 * low, tr);
    hum += 0.07 * tone(high, tr);

    float r = m / n;
    float a = 1.0 - r;
    float d = p.pen * r;
    float turned = TAU * m * min(tl / DRAW, 1.0);
    float2 at = penAt(turned, a, d, a / r) / max(a + d, 0.001);
    float reach = dot(at, at);
    float voice = 0.07 * reach * tone(2.0 * high, tr);
    float pan = 0.5 + 0.4 * at.x;
    float2 sides = float2(cos(pan * 1.5707963), sin(pan * 1.5707963));

    float petal = floor(tl * n / DRAW);
    float clicks = 0.0;
    if (petal >= 1.0 && petal <= n) {
        clicks = 0.18 * tick((tl - petal * DRAW / n) / p.speed);
    }
    float2 mixed = float2(hum + clicks) + voice * sides * 1.41;
    return tanh(1.35 * mixed * env) * p.volume;
}
15 lines from stage 4 that are gone
    float R = p.ring * min(aspect, 1.0);
⋯
    float ink = 0.0;
⋯
        if (float(i) >= total) break;
⋯
    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));
    heat = max(heat, ink * inkLeft(t));
⋯
    float2 pen = tip;
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.001, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(sdCircle(q - c, r)) - 0.001,
                                   1.5 * px));
⋯
        float arm = segment(q, c, pen) - 0.0012;
⋯
    heat = max(heat, lineAt(sdCircle(q - pen, 0.007), 1.5 * px));
⋯
    float high = 110.0 * n / turnsOf(p);
    float hum = 0.1 * tone(110.0, tr) + 0.07 * tone(high, tr);
⋯
        hum += 0.18 * tick((tl - petal * DRAW / n) / p.speed);
⋯
    return float2(tanh(1.35 * hum * env)) * p.volume;

The sound

The sound is the machine. The ring hums at 110 Hz, with a little of its octave at 220 Hz, and the wheel at n / m times that, 247.5 Hz at the defaults. Over them the pen has a voice an octave above the wheel, 495 Hz, as loud as the pen is far out: its distance from the middle over the farthest it gets, squared, so it swells at each tip and nearly vanishes as the pen sweeps past the middle. The voice is panned with the pen, from 0.1 to 0.9 of the way from left to right as the pen goes from its farthest left to its farthest right, with an equal-power pan. A tick sounds each time the pen reaches a tip, 9 times in the 32 seconds of drawing.

Everything follows the same time within the piece as the picture, loopTime(t · speed), and goes through tanh(1.35 · …) before volume. It fades in over the first 1.5 seconds and out with the ink, so the first and last samples are 0 and it loops at 40 seconds with the picture. Over the 40 seconds at the defaults the peak is −7.9 dBFS and the RMS −20.3 dBFS.

New in Ray Kiln

Measure in the playground. Press Measure, after Guides under the picture (or M outside the code), and drag over the picture from one point to another. A line is drawn with a ring at each end and an arc for its angle, and the bar under the picture reads it: both ends in the shader's uv, dx and dy, the distance in uv, in pixels and in picture heights, and the angle on screen, from the right and counterclockwise, 0° to 360°. Heights are the unit of coordinates corrected for the aspect, so a circle drawn as length(p) − r in them reads r heights from its middle to its edge. Hold Shift to snap the angle to steps of 15°; Esc or Clear removes the line. It follows Zoom, so a zoomed line reads the zoomed uv. It is on screen only (stills, exports and grading never see it), free, and in the playground only, not in Run it live on these pages.

Open Spirograph in the playground, paused at 33 seconds with the curve finished and the wheel back at the start. On a picture at least as wide as tall:

  • From the middle, uv (0.5, 0.5), to the thin bright pitch circle straight to the right reads 0.360 heights at 0°: the ring param. In uv it is 0.36 over the picture's width over its height, 0.2025 on a 16:9 picture, since uv runs 0 to 1 both ways whatever the shape.
  • From the middle to the wheel's hub reads 0.200 heights, R − r, and from the hub to the pen 0.128, pen · r, both at 0°.
  • From the middle to the tip of the petal on the right reads 0.328 heights, a + d, at 0°. Every tip is that far out, and the next tip counterclockwise reads 40°: nine tips, 360 / 9 apart.
  • No part of the curve comes nearer the middle than 0.072 heights, a − d: the small clear hole in the middle.

Change pen and measure again: at 1 the tips reach the pitch circle at 0.360 and the hole shrinks to 0.040.

Try this

  • Set pen to 1, the rim: the petals come to sharp points that touch the ring's pitch circle, and the curve passes 0.04 heights from the middle.
  • Set pen to 0: the pen sits at the wheel's center, which only goes round, so the curve is a plain circle 0.2 heights from the middle, drawn 4 times over.
  • Set petals to 5 and turns to 2: a five-pointed star.
  • Set turns to 3: 3 divides 9, so the wheel would be a third of the ring and the curve would close after one turn with 3 petals; turnsOf moves it to 2, and the picture is exactly the one at 2.
  • Set turns to 1: the wheel is a ninth of the ring, and the pen draws nine arches bowed in toward the middle, their points almost at the ring.
  • Set speed to 2: the curve is drawn in 16 seconds, and the piece starts again at 20.

Parameters

ParameterDefaultRangeWhat it does
ring0.360.2 to 0.45The fixed ring's radius, in picture heights
petals93 to 12How many petals the curve has; the ring has 12 teeth for each
turns41 to 5Times the wheel goes round before the curve closes, moved to the nearest number sharing no factor with petals; the wheel has 12 teeth for each
pen0.80 to 1How far out on the wheel the pen sits: 1 is the rim, where the petals come to points
speed10.25 to 2How fast the wheel rolls: 1 draws the curve in 32 seconds
volume0.80 to 1Loudness of the sound

More from this shader

The same shader 7 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.

spirograph.metal
// Ray Kiln · Spirograph
//
// @episode Spirograph
// @length 40
// @variation 30
// @variations 1,7,8,9,10,11,12
// @sweeps pen, petals, turns
// @still 27
// @teaches Curves from wheels inside wheels, drawn as distance fields
// @category Fragment
// @tags spirograph, hypotrochoid, distance field, polyline, gear ratio, rotational symmetry, procedural sound
// @final Spirograph | Gear teeth make the ring and the wheel a machine, the fresh ink glows, and the pen's own voice follows it left and right.
//
// A wheel rolls inside a fixed ring with a pen in one of its holes. The
// wheel's center goes round at R - r from the middle, and the wheel spins
// the other way, (R - r) / r times as fast, so the pen draws
// x = (R - r) cos t + d cos((R - r) t / r),
// y = (R - r) sin t - d sin((R - r) t / r).
// When r / R is a fraction m / n in lowest terms, the curve closes after
// the wheel's center has gone round m times, with n petals.
// The curve is drawn as a distance field: each pixel finds how far it is
// from a polyline of 240 short segments along the pen's path, and lights
// up within a pixel or two of it.
// 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 ring 0.36 0.2 0.45 The fixed ring's radius, in picture heights
// @param petals 9 3 12 How many petals the curve has; the ring has 12 teeth for each
// @param turns 4 1 5 Times the wheel goes round before the curve closes, moved to the nearest number sharing no factor with petals; the wheel has 12 teeth for each
// @param pen 0.8 0 1 How far out on the wheel the pen sits: 1 is the rim, where the petals come to points
// @param speed 1 0.25 2 How fast the wheel rolls: 1 draws the curve in 32 seconds
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;

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

// The distance from p to a circle of radius r round the origin: negative
// inside it.
float sdCircle(float2 p, float r) {
    return length(p) - r;
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Two complex numbers multiplied: lengths multiply, angles add.
float2 cmul(float2 a, float2 b) {
    return float2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}

// Where the pen is once the wheel's center has gone round by angle t: the
// center a from the middle, the pen d from it, turned back by k t.
float2 penAt(float t, float a, float d, float k) {
    return a * float2(cos(t), sin(t)) + d * float2(cos(k * t), -sin(k * t));
}

// The pen's path is drawn as 240 straight segments.
constant float SEGMENTS = 240.0;

// The petals as a whole number, 3 to 12.
float petalsOf(constant Params& p) {
    return clamp(floor(p.petals + 0.5), 3.0, 12.0);
}

// The largest whole number that divides both a and b, by Euclid's rule.
float sharedFactor(float a, float b) {
    for (int i = 0; i < 16; i++) {
        if (b < 0.5) break;
        float rest = a - b * floor(a / b + 0.0001);
        a = b;
        b = rest;
    }
    return a;
}

// The turns as a whole number below the petals. If it shares a factor
// with them, the curve would close sooner with fewer petals, so it moves
// to the nearest number that doesn't: one less, one more, two less...
float turnsOf(constant Params& p) {
    float n = petalsOf(p);
    float m = clamp(floor(p.turns + 0.5), 1.0, n - 1.0);
    for (int i = 0; i < 12; i++) {
        float side = fmod(float(i), 2.0) > 0.5 ? -1.0 : 1.0;
        float c = m + side * floor(float(i + 1) / 2.0);
        if (c < 0.5 || c > n - 0.5) continue;
        if (sharedFactor(n, c) < 1.5) return c;
    }
    return 1.0;
}

// 40 seconds at speed 1: the curve is drawn over the first 32, then the
// ink cools and fades out from 36 s.
constant float LOOP = 40.0;
constant float DRAW = 32.0;

// Time within the piece.
float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// How much ink is left as the piece ends.
float inkLeft(float t) {
    return 1.0 - smoothstep(36.0, 39.5, t);
}

// Fresh ink is white-hot and cools to ember over a few seconds.
float warmth(float age) {
    return 0.46 + 0.54 * exp(-max(age, 0.0) / 3.0);
}

// A toothed edge: how far out it is at this angle. The ring has 12 n teeth
// pointing in, the wheel 12 m. As R / n = r / m they are one size, and
// where they touch, a tip meets a gap.
float toothEdge(float angle, float radius, float teeth, float tooth) {
    return radius - tooth * cos(teeth * angle);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float px = 1.0 / u.resolution.y;
    // Lengths are in picture heights, from the middle of the picture. In a
    // picture taller than wide, everything shrinks to fit its width.
    float2 q = float2(uv.x * aspect, uv.y) - float2(0.5 * aspect, 0.5);
    float fit = min(aspect, 1.0);

    // The ring, the wheel, the pen. r / R = m / n.
    float n = petalsOf(p);
    float m = turnsOf(p);
    float R = p.ring * fit;
    float r = R * m / n;
    float a = R - r;
    float d = p.pen * r;
    float k = a / r;

    // The center goes round m times in 32 seconds.
    float t = loopTime(u.time * p.speed);
    float turned = TAU * m * min(t / DRAW, 1.0);
    float rate = TAU * m / DRAW;
    float fade = inkLeft(t);

    // A dark ground, a little warmer toward the middle.
    float heat = 0.04 + 0.03 * exp(-3.0 * length(q));

    // The curve: the pen's path as a polyline of 240 segments, n petals
    // of 240 / n each, so a corner falls on every petal's tip. Each step
    // turns the two parts of the pen's place by a fixed angle, a complex
    // multiply, so no sine is needed inside the loop.
    float per = floor(SEGMENTS / n);
    float total = per * n;
    float h = TAU * m / total;
    float2 turn1 = float2(cos(h), sin(h));
    float2 turn2 = float2(cos(k * h), -sin(k * h));
    float2 e1 = float2(1.0, 0.0);
    float2 e2 = float2(1.0, 0.0);
    float2 tip = penAt(turned, a, d, k);
    float2 prev = float2(a + d, 0.0);
    float ink = 0.0, glow = 0.0;
    // The curve stays between |a - d| and a + d from the middle: pixels
    // farther than a glow's reach skip the loop.
    float dist = length(q);
    bool near = dist > abs(a - d) - 0.05 && dist < a + d + 0.05;
    for (int i = 0; i < 240; i++) {
        if (!near || float(i) >= total) break;
        float t0 = float(i) * h;
        if (t0 >= turned - 0.00001) break;
        e1 = cmul(e1, turn1);
        e2 = cmul(e2, turn2);
        float2 next = a * e1 + d * e2;
        float t1 = t0 + h;
        // The newest segment ends exactly under the pen.
        if (t1 > turned) {
            next = tip;
            t1 = turned;
        }
        float s = segment(q, prev, next);
        // Each segment keeps its own age, so where the curve crosses
        // itself the hotter strand shows.
        float age = t - t1 / rate;
        ink = max(ink, lineAt(s - 0.0012, 1.5 * px) * warmth(age));
        glow = max(glow, exp(-max(age, 0.0) / 1.5) * exp(-s / 0.012));
        prev = next;
    }
    heat = max(heat, ink * fade);
    heat += 0.35 * glow * fade;

    // The ring: a band from its toothed inner edge out 0.03 past R, and a
    // thin line along its pitch circle at R, the radius it rolls on.
    float teeth = 12.0 * n;
    float tooth = 0.24 * TAU * R / teeth;
    float angle = atan2(q.y, q.x);
    float rho = length(q);
    float band = max(toothEdge(angle, R, teeth, tooth) - rho,
                     rho - (R + 0.03 * fit));
    heat = mix(heat, 0.12, lineAt(band, 1.5 * px));
    heat = max(heat, 0.27 * lineAt(abs(band) - 0.0008, 1.5 * px));
    heat = max(heat, 0.38 * lineAt(abs(sdCircle(q, R)) - 0.0006, px));

    // The wheel: its center, how far it has spun, a clear disc with a
    // toothed rim, and a row of pen holes along one spoke.
    float2 c = a * float2(cos(turned), sin(turned));
    float spin = -k * turned;
    float2 w = q - c;
    float2 local = float2(cos(spin) * w.x + sin(spin) * w.y,
                          -sin(spin) * w.x + cos(spin) * w.y);
    float rim = length(w) - toothEdge(atan2(local.y, local.x), r,
                                     12.0 * m, tooth);
    heat = mix(heat, 0.09, 0.45 * lineAt(rim, 1.5 * px));
    heat = max(heat, 0.34 * lineAt(abs(rim) - 0.0008, 1.5 * px));
    float gap = 0.1 * r;
    float j = clamp(floor(local.x / gap + 0.5), 1.0, 9.0);
    float hole = length(local - float2(j * gap, 0.0)) - 0.0035;
    heat = max(heat, 0.22 * lineAt(abs(hole) - 0.0006, 1.5 * px));

    // The arm from the hub to the pen, then the pen, white-hot.
    if (d > 0.0001) {
        float arm = segment(q, c, tip) - 0.0012;
        heat = max(heat, 0.5 * lineAt(arm, 1.5 * px));
    }
    heat = max(heat, 0.5 * lineAt(sdCircle(w, 0.006 * fit), 1.5 * px));
    float penDot = sdCircle(q - tip, 0.007 * fit);
    heat += 0.3 * exp(-max(penDot, 0.0) / 0.01);
    heat = max(heat, lineAt(penDot, 1.5 * px));
    return float4(kiln(heat), 1.0);
}

// A sine at f hertz, its phase kept small.
float tone(float f, float t) {
    return sin(TAU * fract(f * t));
}

// A soft tick, 3 ms up and 40 ms down.
float tick(float since) {
    if (since < 0.0) return 0.0;
    float env = smoothstep(0.0, 0.003, since) * exp(-since / 0.04);
    return env * tone(1760.0, since);
}

// What you hear: the ring and the wheel as two tones in the ratio n : m,
// the bigger one lower; the pen as a third, an octave over the wheel,
// louder as it swings out to a petal's tip and panned with it left and
// right; and a tick each time the pen reaches a tip.
float2 sound(float t, constant Params& p) {
    float n = petalsOf(p);
    float m = turnsOf(p);
    float tl = loopTime(t * p.speed);
    float tr = tl / p.speed;
    float env = smoothstep(0.0, 1.5, tl) * inkLeft(tl);

    float low = 110.0;
    float high = low * n / m;
    float hum = 0.1 * tone(low, tr) + 0.025 * tone(2.0 * low, tr);
    hum += 0.07 * tone(high, tr);

    float r = m / n;
    float a = 1.0 - r;
    float d = p.pen * r;
    float turned = TAU * m * min(tl / DRAW, 1.0);
    float2 at = penAt(turned, a, d, a / r) / max(a + d, 0.001);
    float reach = dot(at, at);
    float voice = 0.07 * reach * tone(2.0 * high, tr);
    float pan = 0.5 + 0.4 * at.x;
    float2 sides = float2(cos(pan * 1.5707963), sin(pan * 1.5707963));

    float petal = floor(tl * n / DRAW);
    float clicks = 0.0;
    if (petal >= 1.0 && petal <= n) {
        clicks = 0.18 * tick((tl - petal * DRAW / n) / p.speed);
    }
    float2 mixed = float2(hum + clicks) + voice * sides * 1.41;
    return tanh(1.35 * mixed * env) * 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] = [0.36, 9, 4, 0.8, 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 Shapes & Symmetry