// Ray Kiln · Soap Bubble
//
// @episode Soap Bubble
// @length 60
// @variation 30
// @variations 1,2,4,6,8,10,11,12
// @sweeps thickness, swirl, light
// @still 21
// @teaches Thin-film interference, color from a film's thickness
// @category Fragment
// @tags thin-film interference, spectral rendering, color matching functions, fresnel, procedural sound
// @final Soap Bubble | Its back wall reflects the room too: the window again, upside down.
//
// A soap bubble has no color of its own. Its film, a few hundred
// nanometers of soapy water, reflects light twice: off its front and off
// its back. The two reflections meet a little out of step, by twice the
// film's thickness, and the front one is turned over by half a wave. A
// wavelength that comes back in step is bright; one that comes back out
// of step cancels. Which wavelengths survive depends on the thickness, so
// the thickness is the color. Here 16 wavelengths are reflected one by
// one, added up through the eye's color matching curves, and the film
// drains under gravity, thin at the top and thick at the bottom, while it
// swirls. Where it is thinnest it reflects nothing and goes black.
// 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 thickness 1 0.2 3 How thick the film is: thicker gives paler colors
// @param swirl 1 0 2 How much the film swirls as it drains
// @param light 1 0.3 3 How bright the room the bubble reflects
// @param size 1 0.6 1.3 How big the bubble is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// Everything loops in this many seconds.
constant float LOOP = 60.0;
// Soapy water's refractive index.
constant float FILM_N = 1.33;
// What one surface reflects head on, ((n - 1) / (n + 1))².
constant float F0 = 0.0201;

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

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

float fbm3(float3 p, int octaves) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < octaves; i++) {
        v += a * vnoise3(p);
        p = p * 2.02 + float3(17.1, 9.2, 4.7);
        a *= 0.5;
    }
    return v;
}

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

// Half a bell curve each side of mu.
float lobe(float x, float mu, float lo, float hi) {
    float k = (x - mu) / (x < mu ? lo : hi);
    return exp(-0.5 * k * k);
}

// A wavelength (nm) as linear RGB: the CIE 1931 color matching curves,
// then a screen's red, green and blue.
float3 wavelengthColor(float w) {
    float x = 1.056 * lobe(w, 599.8, 37.9, 31.0)
            + 0.362 * lobe(w, 442.0, 16.0, 26.7)
            - 0.065 * lobe(w, 501.1, 20.4, 26.2);
    float y = 0.821 * lobe(w, 568.8, 46.9, 40.5)
            + 0.286 * lobe(w, 530.9, 16.3, 31.1);
    float z = 1.217 * lobe(w, 437.0, 11.8, 36.0)
            + 0.681 * lobe(w, 459.0, 26.0, 13.8);
    return float3( 3.2406 * x - 1.5372 * y - 0.4986 * z,
                  -0.9689 * x + 1.8758 * y + 0.0415 * z,
                   0.0557 * x - 0.2040 * y + 1.0570 * z);
}

// The share of wavelength w a film d nm thick reflects: 0 at d = 0.
float filmReflect(float d, float w, float cosT, float F) {
    float delta = 2.0 * TAU * FILM_N * d * cosT / w;
    float c = cos(delta);
    return 2.0 * F * (1.0 - c) / (1.0 + F * F - 2.0 * F * c);
}

// 16 wavelengths, 400 to 700 nm, added up; white light gives white.
float3 filmColor(float d, float cosI) {
    // Snell's law: steeper inside the film.
    float cosT = sqrt(1.0 - (1.0 - cosI * cosI) / (FILM_N * FILM_N));
    // Fresnel: more at a glancing angle.
    float F = F0 + (1.0 - F0) * pow(1.0 - cosI, 5.0);
    float3 sum = float3(0.0), white = float3(0.0);
    for (int i = 0; i < 16; i++) {
        float w = 390.0 + 20.0 * (float(i) + 0.5);
        float3 s = wavelengthColor(w);
        sum += s * filmReflect(d, w, cosT, F);
        white += s;
    }
    return max(sum / white, 0.0);
}

// The film's thickness in nm at a point p on the bubble (from its center,
// length 1, y up) at time t.
float thicknessAt(float3 p, float t, constant Params& pr) {
    // Gravity drains it: about 30 nm near the top, 850 at the bottom.
    float drain = 0.5 - 0.5 * p.y;
    float d = 30.0 + 820.0 * pow(drain, 1.4);
    // Swirls: noise turned round once a minute, bent by noise that turns
    // twice.
    float a = TAU * t / LOOP;
    float3 r = float3(p.x * cos(a) - p.z * sin(a), p.y,
                      p.x * sin(a) + p.z * cos(a));
    float3 b = float3(cos(2.0 * a), sin(2.0 * a), 0.0);
    float3 warp = float3(fbm3(r * 1.7 + b, 3),
                         fbm3(r * 1.7 + b.yxz + 5.2, 3), 0.0);
    float n = fbm3(r * 2.2 + 2.5 * warp, 4);
    // They stir the film, less near the top.
    d *= 1.0 + pr.swirl * (1.3 * n - 0.65) * smoothstep(-0.1, 0.5, drain);
    // Black film: at the very top, about 6 nm, reflecting almost nothing.
    float cap = drain + 0.08 * (n - 0.5) - 0.02 * sin(3.0 * a);
    d = mix(6.0, d, smoothstep(0.11, 0.125, cap));
    return max(d, 0.0) * pr.thickness;
}

// What the bubble reflects from direction r (linear light): a dark warm
// room lit from the ceiling, a window up to the left with four panes, and
// the kiln's glow low on the right.
float3 room(float3 r, constant Params& p) {
    float3 col = pow(kiln(0.22 + 0.1 * r.y), 2.2);
    // A soft light from the ceiling, so the top of the bubble shows its film.
    col += float3(1.0, 0.95, 0.87) * 1.6 * smoothstep(0.2, 0.9, r.y);
    float3 w = normalize(float3(-0.55, 0.5, 0.67));
    float3 side = normalize(cross(float3(0, 1, 0), w));
    float3 up = cross(w, side);
    float2 f = float2(dot(r, side), dot(r, up)) / max(dot(r, w), 0.01);
    float pane = step(abs(f.x), 0.42) * step(abs(f.y), 0.32);
    pane *= step(0.025, abs(f.x)) * step(0.025, abs(f.y));
    pane *= step(0.0, dot(r, w));
    col += float3(1.0, 0.95, 0.87) * pane * 9.0;
    float3 g = normalize(float3(0.7, -0.45, 0.55));
    float glow = exp(-8.0 * (1.0 - dot(r, g)));
    col += pow(float3(1.0, 0.69, 0.38), 2.2) * glow * 6.0;
    return col * p.light;
}

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);
    float t = fmod(u.time, LOOP);
    float a = TAU * t / LOOP;
    // The background: near-black, warmed low on the right by the kiln.
    float glow = exp(-1.6 * length(q - float2(1.3, -1.2)));
    float3 bg = pow(kiln(0.06 + 0.3 * glow), 2.2);
    float3 col = bg;

    // The bubble drifts a little and comes back each minute.
    float2 c = float2(0.05 * sin(3.0 * a), 0.04 * sin(4.0 * a));
    // Smaller in a tall picture, so it still fits across.
    float fit = min(1.0, 0.9 * u.resolution.x / u.resolution.y);
    float R = 0.62 * p.size * fit;
    float2 s = (q - c) / R;
    float r2 = dot(s, s);
    if (r2 < 1.0) {
        // Its front: n is the point on the ball and the way it faces.
        float3 n = float3(s, sqrt(1.0 - r2));
        float cosI = n.z;
        float3 r = float3(2.0 * cosI * n.xy, 2.0 * cosI * cosI - 1.0);
        float3 front = room(r, p) * filmColor(thicknessAt(n, t, p), cosI);
        // Its back wall, seen through it from inside: the same reflection
        // turned round, so the window shows again, upside down.
        float3 b = float3(n.xy, -n.z);
        float3 rb = float3(-r.xy, r.z);
        float3 back = room(rb, p) * filmColor(thicknessAt(b, t, p), cosI);
        // Light goes through the film nearly untouched.
        col = col * 0.96 + front + 0.8 * back;
    }
    // A soft edge, a pixel wide.
    float px = 2.0 / u.resolution.y / R;
    float edge = smoothstep(1.0 + px, 1.0 - px, sqrt(r2));
    col = mix(bg, col, edge);
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}

// The bubble, heard. Three tones stand for three colors of light: 220 Hz
// for red (650 nm), 277.2 for green (550 nm), 329.6 for blue (450 nm).
// Each is played twice, the copy out of step by what the light's second
// reflection is at the film in the middle of the bubble, and turned over
// as the first reflection is. They add as the light does: a color the
// film keeps is loud, a color it cancels goes quiet, so the chord follows
// the color in the middle as the film swirls past.

// One tone and its copy, delta out of step and turned over.
float twoWaves(float t, float f, float delta) {
    return sin(TAU * f * t) - sin(TAU * f * t + delta);
}

float2 sound(float t, constant Params& p) {
    float d = thicknessAt(float3(0.0, 0.0, 1.0), t, p);
    float3 w = float3(650.0, 550.0, 450.0);
    float3 delta = 2.0 * TAU * FILM_N * d / w;
    float red = twoWaves(t, 220.0, delta.x);
    float green = twoWaves(t, 277.2, delta.y);
    float blue = twoWaves(t, 329.6, delta.z);
    // A faint octave over each, the film's shimmer.
    red += 0.25 * twoWaves(t, 440.0, 2.0 * delta.x);
    green += 0.25 * twoWaves(t, 554.4, 2.0 * delta.y);
    blue += 0.25 * twoWaves(t, 659.2, 2.0 * delta.z);
    // Red to the left, blue to the right, green in the middle.
    float2 mixLR = float2(0.8 * red + 0.5 * green + 0.25 * blue,
                          0.25 * red + 0.5 * green + 0.8 * blue);
    // Fade in over the first 50 ms, so it starts without a click.
    return mixLR * 0.12 * p.volume * min(t * 20.0, 1.0);
}
