#include <metal_stdlib>
using namespace metal;

struct Uniforms {
    float2 resolution;
    float  time;
    float  timeDelta;
    float2 mouse;
    uint   frame;
    uint   pad;
};

struct Params {
    float speed;
    float tiles;
    float slide;
    float grout;
    float rings;
    float glow;
    float bevel;
    float volume;
};

struct RKVertexOut {
    float4 position [[position]];
    float2 uv;
};

vertex RKVertexOut rk_vertex(uint vid [[vertex_id]]) {
    float2 p = float2((vid << 1) & 2, vid & 2);
    RKVertexOut o;
    o.position = float4(p * 2.0 - 1.0, 0.0, 1.0);
    o.uv = p;
    return o;
}

#line 1 "shader.metal"
// Ray Kiln · Penrose Tiles
//
// @episode Penrose Tiles
// @length 60
// @variation 30
// @variations 1,2,4,5,6,7,10,11
// @still 30.0
// @teaches An aperiodic tiling from five grids, symmetry that never repeats
// @category Fragment
// @tags penrose tiling, aperiodic tiling, pentagrid, quasicrystal, symmetry, procedural sound
// @final Penrose Tiles | Glaze pools in each tile and thins at its edges, the floor breathes, and bells follow the long and short gaps.
//
// Two tiles, a thick rhomb and a thin one, cover the plane without the
// pattern ever repeating. De Bruijn's way to lay them: five grids of
// parallel lines, a fifth of a turn apart. Every crossing of two lines
// is one tile, thick where the lines cross at 72 degrees, thin at 36,
// and the lines a point lies beyond in the other three grids say where
// the tile goes. With the grids in their symmetric places the whole
// floor has five-fold symmetry about its middle. Slide them and tiles
// flip in threes: the five-fold symmetry goes at once, a mirror stays,
// and at half the loop everything is back.
// 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 speed 1 0 3 How fast the grids slide and the heat runs outwards
// @param tiles 13 6 30 How many tile edges fit the picture's height
// @param slide 0.3 0 1 How far the grids slide from their symmetric places (0 keeps the five-fold symmetry)
// @param grout 0.05 0.015 0.15 How wide the dark lines between the tiles are, in tile edges
// @param rings 5 2 12 How many tile edges from one ring of heat to the next
// @param glow 0.6 0 1 How much the rings of heat change a tile
// @param bevel 0.5 0 1 How far the shade at a tile's edge reaches in
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PHI = 1.6180340;

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

// Grid j's direction: five, a fifth of a turn apart, the first pointing up.
float2 gridDir(int j) {
    const float2 dirs[5] = {
        float2(0.0, 1.0), float2(-0.9510565, 0.3090170),
        float2(-0.5877853, -0.8090170), float2(0.5877853, -0.8090170),
        float2(0.9510565, 0.3090170)};
    return dirs[j];
}

// How far grid j is slid. At 0.2 each the grids are alike: five-fold
// symmetry. The shares add up to nothing.
float gridShift(int j, float slide) {
    const float share[5] = {
        1.0, -0.8090170, 0.3090170, 0.3090170, -0.8090170};
    return 0.2 + slide * share[j];
}

// The slide over the loop: out, back, out the other way and back.
float slideAt(float t, constant Params& p) {
    return 0.5 * p.slide * sin(TAU * t * p.speed / 60.0);
}

struct Tile {
    float2 at;      // where the point is in its tile, 0...1 along each edge
    float thin;     // 0 for a thick rhomb, 1 for a thin one
    float sine;     // the sine of the tile's corner angle
    float2 middle;  // the tile's middle, in tile edges from the floor's
    float2 along;   // its long diagonal, a unit vector
};

// The tile that holds y. Every crossing of two grids' lines is one tile;
// the four crossings nearest y are tried for each of the ten pairs of
// grids, and one of those tiles holds y.
Tile tileAt(float2 y, float slide) {
    Tile t;
    t.at = float2(0.5);
    t.thin = 0.0;
    t.sine = 1.0;
    t.middle = y;
    t.along = float2(0.0, 1.0);
    // The tiles are the grids' plane stretched by 5/2, so y lies near
    // 2/5 of it.
    float2 moved = float2(0.0);
    for (int m = 0; m < 5; m++) {
        moved += gridShift(m, slide) * gridDir(m);
    }
    float2 x = 0.4 * (y - moved);
    for (int i = 0; i < 4; i++) {
        float2 ei = gridDir(i);
        float gi = gridShift(i, slide);
        float ni = floor(dot(x, ei) + gi);
        for (int j = i + 1; j < 5; j++) {
            float2 ej = gridDir(j);
            float gj = gridShift(j, slide);
            float nj = floor(dot(x, ej) + gj);
            float cross = ei.x * ej.y - ei.y * ej.x;
            for (int a = 0; a < 2; a++) {
                for (int b = 0; b < 2; b++) {
                    // Lines ki and kj cross at q.
                    float ki = ni + float(a);
                    float kj = nj + float(b);
                    float si = ki - gi;
                    float sj = kj - gj;
                    float2 q = float2(si * ej.y - sj * ei.y,
                                      sj * ei.x - si * ej.x) / cross;
                    // The tile's corner: a step along a grid's direction
                    // for each line passed, the next line beyond q in the
                    // other three grids.
                    float2 corner = ki * ei + kj * ej;
                    for (int m = 0; m < 5; m++) {
                        if (m == i || m == j) { continue; }
                        float2 em = gridDir(m);
                        float km = ceil(dot(q, em) + gridShift(m, slide));
                        corner += km * em;
                    }
                    // y from that corner, along the tile's two edges.
                    float2 d = y - corner;
                    float2 at = float2(d.x * ej.y - d.y * ej.x,
                                       ei.x * d.y - ei.y * d.x) / cross;
                    bool inside = at.x >= 0.0 && at.x < 1.0
                               && at.y >= 0.0 && at.y < 1.0;
                    if (inside) {
                        // Neighboring grids cross at 72 degrees: thick.
                        // Grids two apart, at 36: thin.
                        bool thick = (j - i == 1) || (j - i == 4);
                        t.at = at;
                        t.thin = thick ? 0.0 : 1.0;
                        t.sine = abs(cross);
                        t.middle = corner + 0.5 * (ei + ej);
                        t.along = normalize(thick ? ei + ej : ei - ej);
                    }
                }
            }
        }
    }
    return t;
}

// How far the point is from its tile's nearest edge, in tile edges.
float edgeDistance(Tile t) {
    float2 d = min(t.at, 1.0 - t.at);
    return min(d.x, d.y) * t.sine;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float aspect = u.resolution.x / u.resolution.y;
    float t = u.time * p.speed;
    // The floor breathes in and out a little, twice a loop.
    float across = p.tiles * (1.0 + 0.06 * sin(TAU * t / 30.0));
    float2 y = (uv - 0.5) * float2(aspect, 1.0) * across;
    float pixel = across / u.resolution.y;
    Tile tile = tileAt(y, slideAt(u.time, p));
    // Heat runs outwards in rings, and each tile takes the heat at its
    // own middle, so it is one flat color.
    float r = length(tile.middle);
    float ring = 0.5 + 0.5 * sin(TAU * (r / p.rings - t / 6.0));
    // A tile whose long diagonal points at the floor's middle burns
    // brighter than one that lies across. Both are the same after a
    // fifth of a turn, so the color keeps the symmetry the tiles have.
    float2 out = tile.middle / max(r, 0.001);
    float points = abs(dot(tile.along, out));
    float fire = mix(0.42, 0.66, tile.thin) + 0.22 * (points - 0.5);
    fire += p.glow * 0.36 * (ring - 0.5);
    // The floor is cooler towards its rim.
    fire -= 0.10 * smoothstep(0.0, 1.2, r / across);
    float3 color = kiln(fire);
    float d = edgeDistance(tile);
    // Glaze pools in the middle of a tile and thins towards its edges,
    // and the pool catches the heat as a ring passes.
    float pool = smoothstep(0.0, 0.02 + 0.3 * p.bevel, d);
    color *= mix(1.0, 0.55 + 0.45 * pool, step(0.001, p.bevel));
    color += 0.10 * kiln(0.9) * pool * pool * ring * p.glow;
    // Dark grout where two tiles meet, softened over a pixel.
    float line = smoothstep(0.5 * p.grout - pixel,
                            0.5 * p.grout + pixel, d);
    color = mix(kiln(0.06), color, line);
    return float4(color, 1.0);
}

// ---- The sound ---------------------------------------------------------------

// A bell: a tone and two partials that are not whole multiples of it, each
// dying away at its own rate. since is the time since it was struck.
float bell(float f, float since) {
    if (since < 0.0) { return 0.0; }
    float attack = smoothstep(0.0, 0.004, since);
    float tone = sin(TAU * f * since) * exp(-since * 3.0);
    tone += 0.45 * sin(TAU * f * 2.76 * since) * exp(-since * 6.0);
    tone += 0.25 * sin(TAU * f * 5.40 * since) * exp(-since * 11.0);
    return tone * attack;
}

// When beat n falls. Penrose's tiles hide rows of parallel lines (Ammann's
// bars) whose gaps come in two lengths, PHI to 1, in the order of the
// Fibonacci word, which never repeats. Beat n comes after n gaps,
// floor(n / PHI) of them long.
float beatTime(float n, float gap) {
    return gap * (n + (PHI - 1.0) * floor(n / PHI));
}

// One rhythm of bells: the last beats before t ring on. The notes are a
// pentatonic scale on D, five like the grids, and which one a beat plays
// comes from the same count of long gaps, so the tune never repeats.
float rhythm(float t, float gap, float base, float shift) {
    // The mean gap is gap * (2 - 1 / PHI), so the beat at t is near this.
    float near = floor(t / (gap * (2.0 - 1.0 / PHI)));
    float sum = 0.0;
    for (int k = -4; k <= 1; k++) {
        float n = near + float(k);
        if (n < 0.0) { continue; }
        float longs = floor(n / PHI);
        const float scale[5] = {1.0, 1.125, 1.25, 1.5, 1.6666667};
        int note = int(fmod(n + 2.0 * longs + shift, 5.0));
        // A beat before a long gap is struck harder.
        float hard = (floor((n + 1.0) / PHI) - longs) > 0.5 ? 1.0 : 0.6;
        sum += hard * bell(base * scale[note], t - beatTime(n, gap));
    }
    return sum;
}

float2 sound(float t, constant Params& p) {
    float ts = t * max(p.speed, 0.05);
    // Two rhythms, one PHI times slower than the other and an octave
    // below, one to each side.
    float high = rhythm(ts, 0.42, 293.66, 0.0);
    float low = rhythm(ts, 0.42 * PHI, 146.83, 2.0);
    // A hum on D2 and its fifth; the fifth leans out of tune as the grids
    // slide from their symmetric places, and comes back with them.
    float lean = slideAt(t, p);
    float hum = 0.5 * sin(TAU * 73.42 * t);
    hum += 0.3 * sin(TAU * 110.0 * (1.0 + 0.03 * lean) * t);
    // The hum swells as each ring of heat leaves the middle.
    hum *= 0.5 + 0.5 * p.glow * sin(TAU * ts / 6.0);
    float left = 0.35 * high + 0.12 * low + 0.17 * hum;
    float right = 0.12 * high + 0.35 * low + 0.17 * hum;
    // No click at the start or at the loop's end.
    float ends = smoothstep(0.0, 0.05, t) * smoothstep(60.0, 59.9, t);
    return float2(left, right) * p.volume * ends;
}

#line 1 "rk_host"
fragment float4 rk_fragment(RKVertexOut in [[stage_in]],
                                constant Uniforms& u [[buffer(0)]],
                                constant Params& p [[buffer(1)]]) {
    return shade(in.uv, u, p);
}

struct SoundUniforms { float start; float rate; uint count; uint pad; };
kernel void rk_sound(device float2* out [[buffer(0)]],
                         constant SoundUniforms& su [[buffer(1)]],
                         constant Params& p [[buffer(2)]],
                         uint i [[thread_position_in_grid]]) {
    if (i >= su.count) return;
    out[i] = clamp(sound(su.start + float(i) / su.rate, p), -1.0, 1.0);
}