#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 heat;
    float cooling;
    float scale;
    float width;
    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 · Lava Flow
//
// @episode Lava Flow
// @length 60
// @variation 30
// @variations 1,2,4,5,6,8,9,12
// @still 14
// @teaches Flow noise, a cooling crust, color from temperature
// @category Fragment
// @tags flow noise, fractal noise, domain warping, cosine palette, procedural sound
// @final Lava Flow | The crust breaks into plates, the cracks glow, and the banks catch the light.
//
// A river of lava running down a slope. The noise doesn't scroll: it is
// carried along a flow field, two copies half a cycle apart, each faded
// out as it stretches too far, so it moves with the river and never tears.
// Every pixel gets a temperature: hottest in the middle of the channel and
// at the top, cooler downstream and towards the banks, and lower where the
// noise says the crust is thick. That one number is the color: a cosine
// palette, four float3s, from dull red to white-hot. Where it falls low
// enough the lava is crust, dark rock that cracks into plates, and the
// cracks between them stay hot.
// 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 lava runs
// @param heat 1 0.4 1.6 How hot it comes out at the top
// @param cooling 1 0 2 How quickly it cools and grows a crust
// @param scale 3 1 8 How big the crust's plates are: higher means smaller
// @param width 0.75 0.3 1.2 How wide the channel is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// The loop: everything comes back to where it started in this many seconds.
constant float LOOP = 60.0;
// Each copy of the noise is carried this many seconds before it fades.
constant float CYCLE = 3.0;

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 hash11(float n) {
    return fract(sin(n * 12.9898) * 43758.5453);
}

// Value noise: random values on a grid, blended smoothly between them.
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);
}

// Fractal noise: five octaves, each finer and fainter than the last.
float fbm(float2 p) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < 5; i++) {
        v += a * vnoise(p);
        p = p * 2.03 + float2(17.1, 9.2);
        a *= 0.5;
    }
    return v;
}

// Where the channel's middle is at height y: it bends gently down the slope.
float channelMid(float y) {
    return 0.22 * sin(y * 1.6 + 0.7) + 0.08 * sin(y * 3.7 + 2.0);
}

// How far across the channel a point is: 0 in the middle, 1 at a bank.
float across(float2 q, constant Params& p) {
    return abs(q.x - channelMid(q.y)) / p.width;
}

// The flow: down the slope along the bend, slow at the banks.
float2 flowAt(float2 q, constant Params& p) {
    float a = clamp(across(q, p), 0.0, 1.0);
    float pace = 0.12 * (0.25 + 0.75 * (1.0 - a * a));
    float bend = (channelMid(q.y + 0.01) - channelMid(q.y - 0.01)) / 0.02;
    return normalize(float2(-bend, -1.0)) * pace;
}

// One copy of the noise, carried back up the flow. Each cycle starts
// from a new place in the noise.
float carried(float2 q, float t, float shift, constant Params& p) {
    float k = (t + shift) / CYCLE;
    float phase = fract(k);
    float jump = fmod(floor(k), LOOP / CYCLE);
    float2 start = float2(jump * 3.17, jump * 5.71);
    float2 from = q - flowAt(q, p) * phase * CYCLE * p.speed;
    float2 s = from * p.scale + start;
    // Domain warping: a second noise bends the first.
    float2 bendBy = float2(fbm(s * 0.7 + 3.1), fbm(s * 0.7 + 8.4));
    return fbm(s + 1.6 * bendBy);
}

// Flow noise: two copies half a cycle apart, each unseen as it jumps.
float flowNoise(float2 q, float t, constant Params& p) {
    float w = abs(1.0 - 2.0 * fract(t / CYCLE));
    float a = carried(q, t, 0.0, p);
    float b = carried(q, t, 0.5 * CYCLE, p);
    float n = mix(a, b, w);
    // Mixing flattens them: put the contrast back.
    return 0.5 + (n - 0.5) / sqrt(w * w + (1.0 - w) * (1.0 - w));
}

// Temperature to color: a cosine palette, a + b * cos(2π(c * t + d)).
// Four float3s give a ramp close to the kiln palette: dull red, orange,
// gold, nearly white.
float3 heatColor(float t) {
    float3 a = float3(0.527, 0.645, 1.500);
    float3 b = float3(0.518, 0.631, 1.496);
    float3 c = float3(0.564, 0.378, 0.199);
    float3 d = float3(0.551, 0.465, 0.458);
    return max(a + b * cos(6.28318 * (c * t + d)), 0.0);
}

// The temperature at a point, from 0 (cold) to 1 (white-hot).
float temperature(float2 q, float n, constant Params& p) {
    float a = clamp(across(q, p), 0.0, 1.0);
    // How far it has run: q.y goes from 1 at the top to -1 at the bottom.
    float down = 0.5 - 0.5 * q.y;
    float hot = p.heat * (1.0 - 0.45 * a * a);
    // It cools as it runs and towards the banks.
    float cool = p.cooling * (0.12 + 0.42 * down + 0.22 * a);
    // The noise makes some of it hotter, some cooler.
    return hot - cool + 0.45 * (n - 0.5) - 0.1;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 q = (uv - 0.5) * 2.0 * float2(u.resolution.x / u.resolution.y, 1.0);
    // The lava enters at the top, q.y = 1.
    float t = fmod(u.time, LOOP);
    float a = across(q, p);

    float n = flowNoise(q, t, p);
    float temp = temperature(q, n, p);
    // Past 0.9 the fitted palette turns green.
    float3 lava = heatColor(clamp(temp, 0.0, 0.9));

    // Under about 0.45 the lava sets into crust.
    float crust = 1.0 - smoothstep(0.38, 0.52, temp);
    // Cracks where the noise crosses 1/8, 3/8, 5/8, 7/8.
    float d = abs(fract(n * 4.0) - 0.5) / 4.0;
    float crack = 1.0 - smoothstep(0.004, 0.016, d);
    // Cold all through: no glow left.
    crack *= smoothstep(0.05, 0.25, temp + 0.2);
    // Rock: two grays.
    float rough = fbm(q * p.scale * 6.0 + float2(n * 3.0, 0.0));
    float3 rock = mix(float3(0.030, 0.026, 0.026),
                      float3(0.150, 0.125, 0.115), rough * rough);
    float rim = 1.0 - smoothstep(0.0, 0.05, d);
    float3 plate = rock + lava * 0.5 * rim;
    // In a crack, the hotter lava underneath.
    float3 seam = heatColor(clamp(temp + 0.2, 0.0, 0.9));
    float3 col = mix(lava, mix(plate, seam, crack), crust);

    // The banks: cold rock past the channel's edge, warmed by its glow.
    float bank = smoothstep(0.95, 1.05, a);
    float near = exp(-max(a - 1.0, 0.0) * 6.0);
    float3 stone = mix(float3(0.030, 0.026, 0.026),
                       float3(0.150, 0.125, 0.115),
                       fbm(q * 7.0) * fbm(q * 2.5 + 4.0));
    stone += heatColor(0.45) * 0.35 * near * near * p.heat;
    col = mix(col, stone, bank);

    // A dark edge where the lava meets the bank: it is coolest there.
    col *= 1.0 - 0.5 * exp(-abs(a - 1.0) * 30.0);
    return float4(col, 1.0);
}

// The lava, heard. A low rumble is the flow: noise with nothing above
// about 90 Hz, louder with speed. Under it a drone on 55 Hz brightens
// with the heat. Crackles are the crust breaking: short bursts of noise,
// each a few milliseconds, more of them the more crust there is.

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

// One crackle channel: in each 1/60 s slot, maybe a burst.
float crackle(float t, float chance, float seed) {
    float slot = floor(t * 60.0);
    float h = hash11(slot * 1.37 + seed);
    if (h > chance) return 0.0;
    // Where in the slot it starts, in seconds after that; it dies in ~4 ms.
    float at = (t * 60.0 - slot - hash11(slot + seed * 3.1) * 0.5) / 60.0;
    if (at < 0.0) return 0.0;
    float env = (1.0 - exp(-at * 4000.0)) * exp(-at * 250.0);
    float grain = hash11(floor(t * 24000.0) + seed) * 2.0 - 1.0;
    return grain * env * (0.5 + 0.5 * h / chance);
}

float2 sound(float t, constant Params& p) {
    float flow = min(p.speed, 2.0);
    float lowL = 0.6 * rumble(t, 40.0) + 0.4 * rumble(t + 9.1, 90.0);
    float lowR = 0.6 * rumble(t + 3.3, 40.0) + 0.4 * rumble(t + 5.7, 90.0);
    float2 low = float2(lowL, lowR) * 0.35 * (0.3 + 0.7 * flow / 2.0);

    // The drone: 55 Hz and its partials, the high ones only when hot.
    float drone = 0.0;
    for (int k = 1; k <= 6; k++) {
        float level = exp(-float(k - 1) / (0.6 + 2.0 * p.heat)) / float(k);
        drone += sin(TAU * 55.0 * float(k) * t + float(k)) * level;
    }
    float breath = 0.75 + 0.25 * sin(TAU * t / 12.0);
    float2 hum = float2(drone) * 0.12 * breath;

    // Crust breaks more when it cools faster.
    float chance = 0.04 + 0.14 * min(p.cooling, 2.0) / 2.0;
    float2 crack = float2(crackle(t, chance, 1.0),
                          crackle(t + 0.013, chance, 7.0)) * 0.4;

    float2 all = low + hum + crack;
    // Silence where the minute comes round, so it joins without a click.
    float turn = fract(t / LOOP);
    float fade = 1.0 - exp(-min(turn, 1.0 - turn) * LOOP * 30.0);
    return tanh(all * 1.3) * p.volume * fade;
}

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