#include <metal_stdlib>
using namespace metal;

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

struct Params {
    float rough;
    float brush;
    float lamp;
    float tarnish;
    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 · Copper Kettle
//
// @episode Copper Kettle
// @length 60
// @variation 30
// @variations 1,3,4,5,6,8,9,11
// @still 30
// @teaches Metals, microfacet highlights, brushed and anisotropic shine
// @category Fragment
// @tags raymarching, signed distance fields, solids of revolution, metals, fresnel, microfacets, anisotropic reflection, high dynamic range, procedural sound
// @final Copper Kettle | Old copper tarnishes: dark oxide low down, where hands never polish it, duller and rougher.
//
// A copper kettle on a dark table, lit by a lamp and by the kiln's
// glow. A metal has no diffuse color: everything it shows is a
// reflection, tinted by the metal, and stronger at a glance (Schlick's
// Fresnel with copper's own color head on). Its shine is a microfacet
// highlight: the surface is taken as countless tiny mirrors, and GGX
// says how many of them face halfway between the eye and the light. A
// brushed surface is rough across its grooves and smooth along them, so
// the highlight stretches into a streak across the brushing. The
// highlight is far brighter than white: nothing here clips 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 rough 0.3 0.12 0.7 How rough the copper is: mirror to satin
// @param brush 0.7 0 1 How strongly it is brushed: round spot to streak
// @param lamp 1 0.3 2.5 How bright the lamp is
// @param tarnish 0.45 0 1 How much dark oxide old copper has grown
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// Everything comes round in this many seconds.
constant float LOOP = 60.0;
// Copper's reflectance head on, in linear red, green and blue.
constant float3 COPPER = float3(0.955, 0.638, 0.538);
// The lamp's cream and the kiln's ember, in linear light.
constant float3 CREAM = float3(1.0, 0.90, 0.73);
constant float3 EMBER = float3(1.0, 0.30, 0.03);
// The kiln's mouth: low, to the right and behind the kettle.
constant float3 KILN_AT = float3(0.78, 0.12, -0.61);

// Turns a pair of coordinates round by the angle a.
float2 rot(float2 p, float a) {
    float c = cos(a), s = sin(a);
    return float2(c * p.x - s * p.y, s * p.x + c * p.y);
}

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

// A random number from 0 to 1 for a number.
float hash11(float n) {
    return fract(sin(n * 12.9898) * 43758.5453);
}

// A random number for each whole-numbered cube of space.
float hash31(float3 p) {
    uint3 v = uint3(int3(floor(p))) * 1664525u + 1013904223u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    v ^= v >> 16u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    return float(v.x) * (1.0 / 4294967295.0);
}

// Value noise in 3D: the cubes' numbers, blended smoothly.
float vnoise3(float3 p) {
    float3 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash31(i),                   b = hash31(i + float3(1, 0, 0));
    float c = hash31(i + float3(0, 1, 0)), d = hash31(i + float3(1, 1, 0));
    float e = hash31(i + float3(0, 0, 1)), g = hash31(i + float3(1, 0, 1));
    float h = hash31(i + float3(0, 1, 1)), k = hash31(i + float3(1, 1, 1));
    float lo = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
    float hi = mix(mix(e, g, f.x), mix(h, k, f.x), f.y);
    return mix(lo, hi, f.z);
}

// The smooth minimum: two shapes joined with a fillet.
float smin(float a, float b, float k) {
    float h = max(k - abs(a - b), 0.0) / k;
    return min(a, b) - h * h * k * 0.25;
}

// The kettle comes to the boil and cools once a minute: 0 to 1.
float boilAt(float t) {
    float s = sin(PI * t / LOOP);
    return s * s;
}

// Where the lamp shines from: high on the left, swaying slowly.
float3 lampDir(float t) {
    float a = -0.75 + 0.35 * sin(TAU * 2.0 * t / LOOP);
    return normalize(float3(sin(a), 0.9, cos(a)));
}

// The body's radius at height y: wide low down, a shoulder above.
float bodyRadius(float y) {
    float low = 1.0 - smoothstep(0.0, 0.3, y);
    return mix(0.78, 0.42, smoothstep(0.3, 0.9, y)) - 0.08 * low * low;
}

// A squashed sphere, its radii r.
float ellipsoid(float3 p, float3 r) {
    float k0 = length(p / r);
    float k1 = length(p / (r * r));
    return k0 * (k0 - 1.0) / k1;
}

// A tube from a to b whose radius tapers from ra to rb.
float taper(float3 p, float3 a, float3 b, float ra, float rb) {
    float3 pa = p - a, ba = b - a;
    float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
    return length(pa - ba * h) - mix(ra, rb, h);
}

// The kettle turned by a: distance, and 1 body, 2 spout, 3 wood.
float2 kettle(float3 p, float a) {
    p.xz = rot(p.xz, a);
    // A solid of revolution, cut below the lid, marched at 80%.
    float r = length(p.xz);
    float body = max(r - bodyRadius(p.y), max(-p.y, p.y - 0.88)) * 0.8;
    // The lid: a rim and a low dome, with a wooden knob.
    float2 rim = float2(r - 0.39, abs(p.y - 0.9) - 0.025);
    float lid = length(max(rim, 0.0)) + min(max(rim.x, rim.y), 0.0) - 0.01;
    lid = min(lid, ellipsoid(p - float3(0.0, 0.9, 0.0),
                             float3(0.36, 0.12, 0.36)));
    float knob = length(p - float3(0.0, 1.07, 0.0)) - 0.065;
    // The spout: a tapered tube, open at its tip.
    float3 tip = float3(1.12, 0.8, 0.0);
    float spout = taper(p, float3(0.5, 0.28, 0.0), tip, 0.13, 0.045);
    spout = max(spout, 0.03 - length(p - tip));
    // The handle: an arch on two lugs, a wooden grip on top.
    float2 q = float2(length(p.xy - float2(0.0, 0.78)) - 0.47, p.z);
    float arch = max(length(q) - 0.035, 0.85 - p.y);
    float3 lug = float3(abs(p.x) - 0.45, p.y - 0.86, p.z);
    arch = min(arch, length(lug) - 0.05);
    float grip = taper(p, float3(-0.2, 1.25, 0.0), float3(0.2, 1.25, 0.0),
                       0.07, 0.07);
    float copper = smin(body, lid, 0.02);
    float2 d = float2(copper, 1.0);
    float rest = smin(smin(spout, arch, 0.03), copper, 0.06);
    if (rest < d.x - 0.001) d = float2(rest, 2.0);
    float wood = min(knob, grip);
    if (wood < d.x) d = float2(wood, 3.0);
    return d;
}

// The way the surface faces: the slope of the distance.
float3 normalAt(float3 p, float a) {
    const float2 e = float2(0.0015, 0.0);
    return normalize(float3(
        kettle(p + e.xyy, a).x - kettle(p - e.xyy, a).x,
        kettle(p + e.yxy, a).x - kettle(p - e.yxy, a).x,
        kettle(p + e.yyx, a).x - kettle(p - e.yyx, a).x));
}

// Darker where a ray to the light passes near the kettle.
float softShadow(float3 ro, float3 rd, float w, float a) {
    float lit = 1.0;
    float s = 0.02;
    for (int i = 0; i < 40; i++) {
        float h = kettle(ro + rd * s, a).x;
        lit = min(lit, h / (w * s));
        if (lit < 0.001 || s > 4.0) break;
        s += clamp(h, 0.01, 0.25);
    }
    lit = clamp(lit, 0.0, 1.0);
    return lit * lit * (3.0 - 2.0 * lit);
}

// The room seen along rd; blur softens it as a rough mirror does.
float3 roomSeen(float3 rd, float blur, float t, constant Params& p) {
    float3 col = pow(kiln(0.1 + 0.12 * exp(-6.0 * abs(rd.y))), 2.2);
    // The table: near-black, past the horizon.
    float table = smoothstep(0.02 + blur, -0.02 - blur, rd.y);
    col = mix(col, float3(0.006, 0.004, 0.004), table * 0.85);
    // The lamp: a panel of four panes, out of sight behind us.
    float3 l = lampDir(t);
    float3 side = normalize(cross(float3(0.0, 1.0, 0.0), l));
    float3 up = cross(l, side);
    float2 f = float2(dot(rd, side), dot(rd, up)) / max(dot(rd, l), 0.05);
    float w = 0.01 + blur;
    float panel = smoothstep(0.28 + w, 0.28 - w, abs(f.x))
                * smoothstep(0.2 + w, 0.2 - w, abs(f.y));
    panel *= smoothstep(0.01, 0.01 + w, abs(f.x))
           * smoothstep(0.01, 0.01 + w, abs(f.y));
    panel *= step(0.0, dot(rd, l)) / (1.0 + 12.0 * blur);
    col += CREAM * 4.0 * p.lamp * panel;
    // The kiln's mouth glows hotter as the kettle nears the boil.
    float spread = 1.0 + 4.0 * blur;
    float glow = exp(-14.0 / spread * (1.0 - dot(rd, KILN_AT))) / spread;
    col += EMBER * glow * (0.4 + 2.0 * boilAt(t));
    return col;
}

// Schlick's Fresnel with a color: f0 head on, white at a glance.
float3 schlick(float3 f0, float c) {
    return f0 + (1.0 - f0) * pow(1.0 - clamp(c, 0.0, 1.0), 5.0);
}

// GGX stretched: roughness at along the brushing, ab across it.
float ggxAniso(float3 h, float3 n, float3 tg, float3 bt,
               float at, float ab) {
    float x = dot(h, tg) / at, y = dot(h, bt) / ab, z = dot(h, n);
    float k = x * x + y * y + z * z;
    return 1.0 / (PI * at * ab * k * k);
}

// Smith: mirrors that hide each other, over 4 (n.l)(n.v).
float smithV(float nl, float nv, float a) {
    float a2 = a * a;
    float gv = nl * sqrt(nv * nv * (1.0 - a2) + a2);
    float gl = nv * sqrt(nl * nl * (1.0 - a2) + a2);
    return 0.5 / max(gv + gl, 1e-5);
}

// One light's microfacet highlight: Fresnel times GGX times Smith.
float3 microfacet(float3 n, float3 v, float3 l, float3 f0,
                  float3 tg, float3 bt, float at, float ab) {
    float3 h = normalize(v + l);
    float nl = max(dot(n, l), 0.0), nv = max(dot(n, v), 1e-3);
    float d = ggxAniso(h, n, tg, bt, at, ab);
    float vis = smithV(nl, nv, sqrt(at * ab));
    return schlick(f0, dot(v, h)) * d * vis * nl;
}

// The brushing's grooves: a smooth random number for each ring.
float grooves(float s) {
    float i = floor(s), f = fract(s);
    f = f * f * (3.0 - 2.0 * f);
    return mix(hash11(i), hash11(i + 1.0), f) - 0.5;
}

// Oxide, 0 to 1: low down and in patches, where hands don't polish.
float tarnishAt(float3 p, float amount) {
    float n = 0.65 * vnoise3(p * 4.0) + 0.35 * vnoise3(p * 15.0 + 7.0);
    float low = 1.0 - smoothstep(0.0, 0.7, p.y);
    return smoothstep(0.25, 0.85, 0.6 * n + 0.7 * low) * amount;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float t = fmod(u.time, LOOP);
    // The kettle swings a little each way and back once a minute.
    float a = 0.35 + 0.45 * sin(TAU * t / LOOP);
    // The camera looks down at it; a tall picture moves it back.
    float fit = min(1.0, u.resolution.x / u.resolution.y * 1.1);
    float3 eye = float3(0.0, 1.6, 4.4);
    float3 fw = normalize(float3(0.25, 0.55, 0.0) - eye);
    float3 right = normalize(cross(fw, float3(0.0, 1.0, 0.0)));
    float3 up = cross(right, fw);
    float3 rd = normalize(fw * 3.8 * fit + right * s.x + up * s.y);

    // March to the kettle, starting where the ray enters a ball round it.
    float dist = 0.0, id = 0.0;
    float3 oc = eye - float3(0.2, 0.62, 0.0);
    float bb = dot(oc, rd), cc = dot(oc, oc) - 1.5 * 1.5;
    if (bb * bb - cc > 0.0) {
        dist = max(-bb - sqrt(bb * bb - cc), 0.0);
        for (int i = 0; i < 128; i++) {
            float2 k = kettle(eye + rd * dist, a);
            if (k.x < 0.0008) { id = k.y; break; }
            dist += k.x;
            if (dist > 7.0) break;
        }
    }
    float floorAt = rd.y < 0.0 ? -eye.y / rd.y : 100.0;
    // Two lights: the lamp, and the kiln, hotter at the boil.
    float3 l = lampDir(t);
    float3 lampLight = CREAM * 5.0 * p.lamp;
    float3 kilnLight = EMBER * (0.25 + 1.1 * boilAt(t));
    float3 col;
    if (id == 0.0 && floorAt < 100.0) {
        // The table: dark, lit by the lamp, the kettle's shadow on it.
        float3 q = eye + rd * floorAt;
        float lit = softShadow(q + float3(0.0, 0.002, 0.0), l, 0.08, a);
        float pool = exp(-0.3 * dot(q.xz, q.xz));
        float3 light = lampLight * l.y * lit * pool + kilnLight * KILN_AT.y;
        col = float3(0.01, 0.007, 0.006) * light;
    } else if (id == 0.0) {
        col = roomSeen(rd, 0.0, t, p);
    } else {
        float3 pos = eye + rd * dist;
        float3 n = normalAt(pos, a);
        float3 v = -rd;
        float lit = softShadow(pos + n * 0.004, l, 0.06, a);
        if (id == 3.0) {
            // Wood is no metal: a dark diffuse color of its own.
            float3 diffuse = float3(0.03, 0.012, 0.007)
                           * (lampLight * max(dot(n, l), 0.0) * lit
                              + roomSeen(n, 1.0, t, p));
            // And a faint highlight, white, 4% head on.
            float3 tg = normalize(cross(n, float3(0.0, 0.0, 1.0)));
            float3 bt = cross(n, tg);
            col = diffuse + microfacet(n, v, l, float3(0.04), tg, bt,
                                       0.3, 0.3) * lampLight * lit;
        } else {
            // Copper's roughness: GGX takes its square.
            float alpha = p.rough * p.rough;
            // Brushed round the axis, as a lathe spins it.
            float3 local = pos;
            local.xz = rot(local.xz, a);
            float3 tg = float3(pos.z, 0.0, -pos.x);
            tg = normalize(tg - n * dot(n, tg) + float3(1e-4, 0.0, 0.0));
            float3 bt = cross(n, tg);
            float brushed = p.brush * smoothstep(0.03, 0.12, length(pos.xz))
                          * (id == 1.0 ? 1.0 : 0.0);
            // Each ring of grooves is brushed a little finer or coarser.
            float ring = (local.y + length(local.xz)) * 70.0;
            float g = grooves(ring) + 0.7 * grooves(ring * 0.23 + 4.0);
            // Oxide: darker, rougher and no longer brushed.
            float ox = tarnishAt(local, p.tarnish);
            float3 f0 = mix(COPPER, float3(0.2, 0.07, 0.05), ox);
            alpha = mix(alpha, max(alpha, 0.3), ox);
            brushed *= 1.0 - ox;
            // Smooth along the grooves, rough across them.
            float at = alpha * (1.0 - 0.75 * brushed) * exp(1.4 * g * brushed);
            at = max(at, 0.004);
            float ab = min(alpha * (1.0 + 2.5 * brushed), 0.9);
            // No diffuse: the room, mirrored, tinted by Fresnel.
            float3 r = reflect(rd, n);
            float nv = max(dot(n, v), 0.0);
            col = schlick(f0, nv) * roomSeen(r, sqrt(at * ab), t, p);
            // Two microfacet highlights: the lamp and the kiln.
            col += microfacet(n, v, l, f0, tg, bt, at, ab) * lampLight * lit;
            col += microfacet(n, v, KILN_AT, f0, tg, bt, at, ab) * kilnLight;
        }
    }
    // The screen's curve, no clamp: highlights stay over white.
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}

// ---- The sound ---------------------------------------------------------
// The kettle, heard. It simmers, low noise that rises as it heats,
// with bubbles that come quicker; the copper ticks as it swells and
// shrinks, duller the rougher it is; and at the boil it whistles, a
// tone that climbs with the heat and falls away as it cools.

// Integer hash, so noise stays exact for minutes of sound.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// Cracked Clay's sound noise: random values joined `rate` times a second.
float noise1(float t, float rate, uint seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    uint k = uint(i) + seed * 7919u;
    return mix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}

// A tick of thin copper `since` seconds ago: three partials out of tune
// with each other, as a metal sheet's are, dying faster when rough.
float tink(float since, float hz, float rough) {
    if (since < 0.0) return 0.0;
    float die = 25.0 + 90.0 * rough;
    float rise = 1.0 - exp(-since * 2000.0);
    return rise * (sin(TAU * hz * since) * exp(-since * die)
         + 0.5 * sin(TAU * hz * 2.31 * since) * exp(-since * die * 1.7)
         + 0.25 * sin(TAU * hz * 3.92 * since) * exp(-since * die * 2.6));
}

float2 sound(float t, constant Params& p) {
    float heat = boilAt(t);

    // The simmer: two bands of noise, louder as the water heats.
    float2 simmer = float2(noise1(t, 260.0, 1u) + 0.4 * noise1(t, 900.0, 2u),
                           noise1(t, 280.0, 3u) + 0.4 * noise1(t, 950.0, 4u));
    simmer *= 0.05 + 0.2 * heat;

    // Bubbles: forty chances a second, more of them taken when hot.
    // This slot's and the last's, so none is cut off as the next begins.
    float2 pops = float2(0.0);
    for (int j = 0; j < 2; j++) {
        float slot = floor(t * 40.0) - float(j);
        uint id = uint(max(slot, 0.0));
        // Each bubble takes the heat of its own moment, so none is
        // switched on or off halfway.
        float hot = boilAt(slot / 40.0);
        if (hashU(id * 3u + 11u) < 0.05 + 0.6 * hot * hot) {
            float since = t - slot / 40.0;
            float hz = 220.0 + 500.0 * hashU(id * 3u + 12u) + 300.0 * hot;
            float env = since * 150.0 * exp(1.0 - since * 150.0);
            float pan = hashU(id * 3u + 13u);
            pops += float2(1.0 - pan, pan) * env
                  * sin(TAU * hz * since * (1.0 + 4.0 * since));
        }
    }

    // Ticks: the copper swells as it heats and shrinks as it cools,
    // ticking most while the heat changes fastest.
    float2 ticks = float2(0.0);
    for (int j = 0; j < 2; j++) {
        float slot = floor(t * 3.0) - float(j);
        uint id = uint(max(slot, 0.0));
        float change = abs(sin(TAU * slot / 3.0 / LOOP));
        if (hashU(id + 500u) < 0.7 * change) {
            float hz = 1900.0 + 1400.0 * hashU(id + 600u);
            float at = slot / 3.0 + 0.3 * hashU(id + 700u);
            float pan = hashU(id + 800u);
            ticks += float2(1.0 - pan, pan) * tink(t - at, hz, p.rough);
        }
    }

    // The whistle: its pitch follows the heat, 900 Hz cold to 1400
    // at the boil. The phase is that pitch added up over time.
    float cycles = 1150.0 * t - 250.0 * LOOP / TAU * sin(TAU * t / LOOP);
    float phase = TAU * fract(cycles) + 1.6 * sin(TAU * 5.0 * t);
    float blow = smoothstep(0.55, 0.95, heat);
    float whistle = sin(phase) + 0.3 * sin(2.0 * phase + 0.4);
    whistle = whistle * (0.8 + 0.2 * noise1(t, 40.0, 5u))
            + 0.3 * noise1(t, 3000.0, 6u);
    whistle *= 0.22 * blow * blow;

    float2 all = simmer + pops * 0.12 + ticks * 0.3
               + float2(0.4, 0.6) * whistle;
    // Silence where the minute comes round, so it loops without a click.
    float round = fract(t / LOOP);
    float fade = 1.0 - exp(-min(round, 1.0 - round) * LOOP * 30.0);
    return tanh(all * 1.8) * 0.8 * 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);
}