#version 300 es
precision highp float;
precision highp int;

uniform vec2 uResolution;
uniform float uTime;
uniform float uOpen;
uniform int uLightMode;
uniform int uCamMode;

out vec4 fragColor;

// -----------------------------------------------------------------------------
// Constants & Math Helpers
// -----------------------------------------------------------------------------
const float PI  = 3.14159265359;
const float TAU = 6.28318530718;

float saturate(float x) { return clamp(x, 0.0, 1.0); }

mat2 rot2(float a) {
    float c = cos(a), s = sin(a);
    return mat2(c, -s, s, c);
}

// -----------------------------------------------------------------------------
// Procedural Hashing & 3D Noise (Zero External Textures)
// -----------------------------------------------------------------------------
float hash11(float p) {
    p = fract(p * 0.1031);
    p *= p + 33.33;
    p *= p + p;
    return fract(p);
}

float hash12(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * 0.1031);
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.x + p3.y) * p3.z);
}

float hash13(vec3 p3) {
    p3 = fract(p3 * 0.1031);
    p3 += dot(p3, p3.zyx + 31.32);
    return fract((p3.x + p3.y) * p3.z);
}

float noise2(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    float a = hash12(i + vec2(0.0, 0.0));
    float b = hash12(i + vec2(1.0, 0.0));
    float c = hash12(i + vec2(0.0, 1.0));
    float d = hash12(i + vec2(1.0, 1.0));
    return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

float noise3(vec3 p) {
    vec3 i = floor(p);
    vec3 f = fract(p);
    vec3 u = f * f * (3.0 - 2.0 * f);

    float n000 = hash13(i + vec3(0.0, 0.0, 0.0));
    float n100 = hash13(i + vec3(1.0, 0.0, 0.0));
    float n010 = hash13(i + vec3(0.0, 1.0, 0.0));
    float n110 = hash13(i + vec3(1.0, 1.0, 0.0));
    float n001 = hash13(i + vec3(0.0, 0.0, 1.0));
    float n101 = hash13(i + vec3(1.0, 0.0, 1.0));
    float n011 = hash13(i + vec3(0.0, 1.0, 1.0));
    float n111 = hash13(i + vec3(1.0, 1.0, 1.0));

    float nx00 = mix(n000, n100, u.x);
    float nx10 = mix(n010, n110, u.x);
    float nx01 = mix(n001, n101, u.x);
    float nx11 = mix(n011, n111, u.x);

    float nxy0 = mix(nx00, nx10, u.y);
    float nxy1 = mix(nx01, nx11, u.y);

    return mix(nxy0, nxy1, u.z);
}

const mat3 M3 = mat3(
     0.00,  0.80,  0.60,
    -0.80,  0.36, -0.48,
    -0.60, -0.48,  0.64
);

float fbm3(vec3 p) {
    float v = 0.0;
    float a = 0.52;
    for (int i = 0; i < 4; i++) {
        v += a * noise3(p);
        p = M3 * p * 2.07 + vec3(13.1, 7.7, 5.3);
        a *= 0.49;
    }
    return v;
}

// High-definition billowy cauliflower FBM for sculpted explosion lobes & crevices
float billowFbm3(vec3 p) {
    float v = 0.0;
    float a = 0.54;
    for (int i = 0; i < 5; i++) {
        float n = noise3(p);
        float b = 1.0 - abs(n * 2.0 - 1.0);
        b = b * b;
        v += a * b;
        p = M3 * p * 2.10 + vec3(9.2, 4.1, 11.7);
        a *= 0.48;
    }
    return v;
}

// Fast 3-octave version for shadow taps
float billowFbm3Fast(vec3 p) {
    float v = 0.0;
    float a = 0.56;
    for (int i = 0; i < 3; i++) {
        float n = noise3(p);
        float b = 1.0 - abs(n * 2.0 - 1.0);
        v += a * (b * b);
        p = M3 * p * 2.10 + vec3(9.2, 4.1, 11.7);
        a *= 0.48;
    }
    return v;
}

float fbm2(vec2 p) {
    float v = 0.0;
    float a = 0.5;
    mat2 m = mat2(0.8, 0.6, -0.6, 0.8);
    for (int i = 0; i < 5; i++) {
        v += a * noise2(p);
        p = m * p * 2.04 + vec2(17.3, 9.1);
        a *= 0.5;
    }
    return v;
}

// -----------------------------------------------------------------------------
// Dynamic Blast Parameters (Sedov-Taylor inspired expansion across 0..3s)
// -----------------------------------------------------------------------------
struct BlastState {
    float t;
    vec3  domeCenter;
    float domeR;
    float ringR;
    float capY;
    float capScale;
    float stemBright;
};

BlastState getBlastState() {
    BlastState s;
    float t = max(uTime, 0.0);
    float openMod = 0.96 + 0.08 * saturate(uOpen);
    s.t = t;

    float shockPhase = pow(clamp(t * 0.44 + 0.14, 0.05, 1.8), 0.58);
    s.domeR = (0.86 + 0.66 * shockPhase) * openMod;
    s.domeCenter = vec3(0.0, 2.06 + 0.16 * smoothstep(0.0, 3.0, t), 0.0);

    float ringPhase = pow(clamp(t * 0.46 + 0.11, 0.05, 1.8), 0.56);
    s.ringR = (0.94 + 0.64 * ringPhase) * openMod;

    s.capY = 1.86 + 0.18 * smoothstep(0.0, 3.0, t);
    s.capScale = (0.90 + 0.16 * smoothstep(0.0, 2.8, t)) * openMod;

    float flicker = 0.96 + 0.04 * sin(t * 19.0) * cos(t * 11.3);
    s.stemBright = mix(1.06, 0.94, smoothstep(0.4, 3.0, t)) * flicker;
    return s;
}

// -----------------------------------------------------------------------------
// Calibrated Physical Blackbody Fire Palette (Rich Deep Orange -> White-Gold Stem)
// -----------------------------------------------------------------------------
vec3 blackbodyFire(float temp) {
    // Carefully calibrated so mushroom cap (temp 0.2..0.85) stays rich fiery orange-amber,
    // while only the blinding narrow stem core (temp 1.05..1.38) reaches white-gold!
    float t = clamp(temp, 0.0, 1.4);
    vec3 c0 = vec3(0.14, 0.015, 0.002); // deep charred ember
    vec3 c1 = vec3(0.95, 0.16,  0.012); // deep fiery crimson-orange
    vec3 c2 = vec3(2.15, 0.58,  0.055); // rich vivid orange-amber
    vec3 c3 = vec3(3.10, 1.48,  0.28);  // hot golden-yellow
    vec3 c4 = vec3(4.60, 3.85,  2.55);  // incandescent white-gold (stem core only)

    vec3 col = mix(c0, c1, smoothstep(0.08, 0.36, t));
    col = mix(col, c2, smoothstep(0.34, 0.68, t));
    col = mix(col, c3, smoothstep(0.66, 1.02, t));
    col = mix(col, c4, smoothstep(1.00, 1.34, t));
    return col;
}

float hgPhase(float cosTheta, float g) {
    float g2 = g * g;
    return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * cosTheta, 0.001), 1.5));
}

// -----------------------------------------------------------------------------
// Geometry Intersections
// -----------------------------------------------------------------------------
vec2 intersectSphere(vec3 ro, vec3 rd, vec3 center, float radius) {
    vec3 oc = ro - center;
    float b = dot(oc, rd);
    float c = dot(oc, oc) - radius * radius;
    float h = b * b - c;
    if (h < 0.0) return vec2(-1.0);
    h = sqrt(h);
    return vec2(-b - h, -b + h);
}

vec2 intersectCylinderY(vec3 ro, vec3 rd, float radius, float yMin, float yMax) {
    float a = rd.x * rd.x + rd.z * rd.z;
    float b = 2.0 * (ro.x * rd.x + ro.z * rd.z);
    float c = ro.x * ro.x + ro.z * ro.z - radius * radius;
    float disc = b * b - 4.0 * a * c;
    if (disc < 0.0) return vec2(-1.0);
    float s = sqrt(disc);
    float t0 = (-b - s) / max(2.0 * a, 1e-6);
    float t1 = (-b + s) / max(2.0 * a, 1e-6);

    if (abs(rd.y) > 1e-5) {
        float ty0 = (yMin - ro.y) / rd.y;
        float ty1 = (yMax - ro.y) / rd.y;
        float tya = min(ty0, ty1);
        float tyb = max(ty0, ty1);
        t0 = max(t0, tya);
        t1 = min(t1, tyb);
    } else if (ro.y < yMin || ro.y > yMax) {
        return vec2(-1.0);
    }
    if (t1 < t0 || t1 < 0.0) return vec2(-1.0);
    return vec2(max(t0, 0.0), t1);
}

// -----------------------------------------------------------------------------
// Lighting Configuration for uLightMode 0..3
// -----------------------------------------------------------------------------
struct LightRig {
    vec3 keyDir;
    vec3 keyCol;
    vec3 fillCol;
    vec3 rimDir;
    vec3 rimCol;
    vec3 skyZenith;
    vec3 skyHorizon;
    float fireEmissionScale;
    float blastLightScale;
    float dustAlbedoBoost;
};

LightRig getLightRig() {
    LightRig L;
    if (uLightMode == 1) {
        // Pure neutral grayscale study: sculptural key/shadow contrast, muted emission
        L.keyDir = normalize(vec3(0.72, 0.56, 0.41));
        L.keyCol = vec3(0.95);
        L.fillCol = vec3(0.055);
        L.rimDir = normalize(vec3(-0.62, 0.36, -0.69));
        L.rimCol = vec3(0.42);
        L.skyZenith = vec3(0.008);
        L.skyHorizon = vec3(0.022);
        L.fireEmissionScale = 0.018;
        L.blastLightScale = 0.055;
        L.dustAlbedoBoost = 0.92;
    } else if (uLightMode == 2) {
        // Grazing raking key light
        L.keyDir = normalize(vec3(0.95, 0.18, 0.25));
        L.keyCol = vec3(1.55, 1.24, 0.92);
        L.fillCol = vec3(0.020, 0.026, 0.042);
        L.rimDir = normalize(vec3(-0.82, 0.22, -0.52));
        L.rimCol = vec3(0.22, 0.30, 0.46);
        L.skyZenith = vec3(0.0022, 0.0032, 0.0058);
        L.skyHorizon = vec3(0.0075, 0.0080, 0.0115);
        L.fireEmissionScale = 0.78;
        L.blastLightScale = 0.75;
        L.dustAlbedoBoost = 1.0;
    } else if (uLightMode == 3) {
        // Backlit rim light
        L.keyDir = normalize(vec3(-0.22, 0.34, -0.91));
        L.keyCol = vec3(1.45, 1.58, 1.85);
        L.fillCol = vec3(0.018, 0.024, 0.038);
        L.rimDir = normalize(vec3(0.28, 0.42, -0.86));
        L.rimCol = vec3(1.05, 1.15, 1.38);
        L.skyZenith = vec3(0.0024, 0.0035, 0.0065);
        L.skyHorizon = vec3(0.0085, 0.0105, 0.0155);
        L.fireEmissionScale = 0.85;
        L.blastLightScale = 0.82;
        L.dustAlbedoBoost = 0.95;
    } else {
        // Mode 0: Hero photoreal deep night charcoal-navy desert proving ground (lumMin ~6-12)
        L.keyDir = normalize(vec3(0.62, 0.58, 0.52));
        L.keyCol = vec3(0.24, 0.29, 0.40);
        L.fillCol = vec3(0.012, 0.016, 0.026);
        L.rimDir = normalize(vec3(-0.55, 0.38, -0.74));
        L.rimCol = vec3(0.18, 0.24, 0.36);
        L.skyZenith = vec3(0.0015, 0.0021, 0.0036);
        L.skyHorizon = vec3(0.0038, 0.0046, 0.0068);
        L.fireEmissionScale = 1.0;
        L.blastLightScale = 1.0;
        L.dustAlbedoBoost = 0.95;
    }
    return L;
}

// -----------------------------------------------------------------------------
// Desert Proving Ground Heightfield & Shading
// -----------------------------------------------------------------------------
float desertHeight(vec2 xz, float ringR) {
    float r = length(xz);
    float broad = (fbm2(xz * 0.42 + vec2(3.1, 1.7)) - 0.5) * 0.09;
    float grit = (fbm2(xz * 3.8 + vec2(7.4, 2.9)) - 0.5) * 0.024;

    vec2 cell = floor(xz * 2.4);
    vec2 f = fract(xz * 2.4) - 0.5;
    float rnd = hash12(cell);
    vec2 rockOff = (vec2(hash12(cell + 19.1), hash12(cell + 47.3)) - 0.5) * 0.45;
    float rockD = length(f - rockOff);
    float rockMask = step(0.75, rnd);
    float rockSize = 0.09 + 0.11 * hash12(cell + 83.7);
    float rock = rockMask * smoothstep(rockSize, 0.0, rockD) * (0.048 + 0.055 * hash12(cell + 12.4));

    float crater = -0.045 * exp(-r * r * 1.1) + 0.035 * exp(-pow((r - ringR) * 2.6, 2.0));
    return broad + grit + rock + crater;
}

vec3 desertNormal(vec2 xz, float ringR) {
    float e = 0.018;
    float hC = desertHeight(xz, ringR);
    float hX = desertHeight(xz + vec2(e, 0.0), ringR);
    float hZ = desertHeight(xz + vec2(0.0, e), ringR);
    return normalize(vec3(hC - hX, e, hC - hZ));
}

vec3 shadeDesertGround(vec3 ro, vec3 rd, float tHit, BlastState bs, LightRig L) {
    vec3 p = ro + rd * tHit;
    for (int i = 0; i < 4; i++) {
        float h = desertHeight(p.xz, bs.ringR);
        float dh = p.y - h;
        p += rd * (dh / max(-rd.y, 0.15)) * 0.55;
    }

    vec3 N = desertNormal(p.xz, bs.ringR);
    vec3 V = -rd;
    float r = length(p.xz);

    // Dry dusty desert terrain albedo
    float soilN = fbm2(p.xz * 1.45);
    float fineN = fbm2(p.xz * 11.5);
    float pebbleN = noise2(p.xz * 26.0);
    vec3 sandCol = vec3(0.30, 0.23, 0.165);
    vec3 dirtCol = vec3(0.15, 0.11, 0.082);
    vec3 pebbleCol = vec3(0.36, 0.30, 0.24);
    vec3 albedo = mix(dirtCol, sandCol, smoothstep(0.25, 0.78, soilN));
    albedo = mix(albedo, pebbleCol, smoothstep(0.68, 0.90, pebbleN) * 0.45);
    albedo *= 0.74 + 0.46 * fineN;

    float scorch = smoothstep(0.85, 0.10, r);
    albedo = mix(albedo, vec3(0.11, 0.08, 0.06), scorch * 0.45);
    albedo *= L.dustAlbedoBoost;

    // Micro-bump self-shadowing toward the central blast stem
    vec2 toCenter = normalize(-p.xz + vec2(1e-5));
    float h0 = desertHeight(p.xz, bs.ringR);
    float h1 = desertHeight(p.xz + toCenter * 0.065, bs.ringR);
    float h2 = desertHeight(p.xz + toCenter * 0.14, bs.ringR);
    float microOcc = saturate(1.0 - max(h1 - h0, (h2 - h0) * 0.6) * 15.0);

    // Strong soft shadow cast by the billowing dust torus ring onto outer ground
    float ringShadow = 1.0 - 0.78 * smoothstep(bs.ringR - 0.06, bs.ringR + 0.28, r)
                                  * smoothstep(bs.ringR + 2.8, bs.ringR + 0.40, r);
    float ang = atan(p.z, p.x);
    ringShadow = mix(ringShadow, 1.0, 0.18 * noise2(vec2(ang * 4.5, bs.t * 0.4)));

    // 1. Inverse-square detonation stem base light
    vec3 stemPos = vec3(0.0, 0.36, 0.0);
    vec3 toStem = stemPos - p;
    float dStem2 = dot(toStem, toStem);
    vec3 lStem = toStem / sqrt(dStem2);
    float ndlStem = max(dot(N, lStem), 0.0);
    float attStem = 1.0 / (0.18 + dStem2 * 0.62);
    vec3 stemLightCol = vec3(2.8, 1.55, 0.58) * bs.stemBright * L.blastLightScale;

    // 2. Inverse-square upper fireball bounce light
    vec3 capPos = vec3(0.0, bs.capY + 0.10, 0.0);
    vec3 toCap = capPos - p;
    float dCap2 = dot(toCap, toCap);
    vec3 lCap = toCap / sqrt(dCap2);
    float ndlCap = max(dot(N, lCap), 0.0);
    float attCap = 1.0 / (0.95 + dCap2 * 0.35);
    vec3 capLightCol = vec3(1.65, 0.62, 0.16) * bs.stemBright * L.blastLightScale;

    // 3. Key, rim, and ambient fill
    float ndlKey = max(dot(N, L.keyDir), 0.0);
    float ndlRim = max(dot(N, L.rimDir), 0.0);

    vec3 Hstem = normalize(lStem + V);
    float specStem = pow(max(dot(N, Hstem), 0.0), 20.0) * 0.22 * ringShadow * microOcc;
    vec3 Hkey = normalize(L.keyDir + V);
    float specKey = pow(max(dot(N, Hkey), 0.0), 24.0) * 0.12;

    vec3 diff = vec3(0.0);
    diff += stemLightCol * (ndlStem * attStem * ringShadow * microOcc);
    diff += capLightCol  * (ndlCap * attCap * (0.42 + 0.58 * microOcc));
    diff += L.keyCol     * (ndlKey * 0.60);
    diff += L.rimCol     * (ndlRim * 0.30);
    diff += L.fillCol    * (0.50 + 0.50 * N.y);

    vec3 col = albedo * diff + stemLightCol * specStem * attStem + L.keyCol * specKey;

    // Warm ground glow directly under stem footprint
    float footprintGlow = exp(-r * r * 6.5) * 0.85 * bs.stemBright * L.blastLightScale;
    col += vec3(1.65, 0.92, 0.35) * footprintGlow;

    // Smooth dark desert horizon blend
    float fog = 1.0 - exp(-tHit * tHit * 0.0026);
    col = mix(col, L.skyHorizon, saturate(fog));

    return col;
}

// -----------------------------------------------------------------------------
// Deep Night Charcoal-Navy Desert Sky (lumMin ~6-12, %black = 0%)
// -----------------------------------------------------------------------------
vec3 evalSky(vec3 rd, BlastState bs, LightRig L) {
    float h = saturate(rd.y * 1.85 + 0.06);
    vec3 sky = mix(L.skyHorizon, L.skyZenith, pow(h, 0.58));

    // Tight, subtle radial warm scatter right behind the blast (never washes the night sky brown)
    vec3 toBlast = normalize(vec3(0.0, 1.85, 0.0) - vec3(0.0, 1.24, 6.18));
    float cosB = max(dot(rd, toBlast), 0.0);
    float halo = pow(cosB, 22.0) * 0.022 + pow(cosB, 64.0) * 0.028;
    sky += vec3(0.35, 0.15, 0.05) * halo * L.blastLightScale;

    if (uLightMode == 3) {
        float backSun = pow(max(dot(rd, L.keyDir), 0.0), 12.0);
        sky += vec3(0.18, 0.22, 0.30) * backSun;
    }

    float haze = exp(-abs(rd.y) * 18.0);
    sky += L.skyHorizon * haze * 0.28;
    return sky;
}

// -----------------------------------------------------------------------------
// Volumetric Density & Emission Field (Fireball, Stem, Smoke Collar, Dust Ring)
// -----------------------------------------------------------------------------
struct VolSample {
    float density;   // total extinction density
    float smokeFrac; // 0 = pure fire, 1 = opaque smoke/dust
    float dustFrac;  // 1 = ground sandy dust, 0 = explosion smoke
    float temp;      // temperature for blackbody emission
    float cavity;    // local billow crevice/ridge factor for fine sculptural shading
};

VolSample evalVolume(vec3 p, BlastState bs, bool fastShadow) {
    VolSample vs;
    vs.density = 0.0;
    vs.smokeFrac = 0.0;
    vs.dustFrac = 0.0;
    vs.temp = 0.0;
    vs.cavity = 0.5;

    float rXZ = length(p.xz);
    float t = bs.t;

    if (p.y < -0.02 || p.y > bs.domeCenter.y + bs.domeR + 0.25 || rXZ > bs.ringR + 0.85) {
        return vs;
    }

    // -----------------------------------------------------------------
    // 1. Expanding Radial Ground Dust Torus Ring (y in [0, 0.62])
    // -----------------------------------------------------------------
    if (p.y < 0.70 && rXZ > bs.ringR - 0.62 && rXZ < bs.ringR + 0.72) {
        vec2 radDir = p.xz / max(rXZ, 1e-4);
        float dr = rXZ - bs.ringR;
        float dy = (p.y - 0.15) * 1.32;
        float torusD = length(vec2(dr * 0.84, dy));

        vec3 dustP = p * 2.55 - vec3(radDir.x * t * 0.85, t * 0.28, radDir.y * t * 0.85);
        float nBillow = fastShadow ? billowFbm3Fast(dustP) : billowFbm3(dustP);
        float nFine = fastShadow ? 0.5 : fbm3(dustP * 2.4 + vec3(4.2, 1.7, 8.1));

        float tubeR = 0.24 + 0.17 * nBillow + 0.04 * nFine;
        // Sharper opaque boundary for crisp turbulent dirt clouds
        float ringDens = smoothstep(tubeR, tubeR * 0.42, torusD);
        ringDens *= smoothstep(-0.02, 0.05, p.y);

        float wisp = smoothstep(0.52, 0.14, abs(dr - 0.06)) * smoothstep(0.64, 0.15, p.y)
                   * smoothstep(0.42, 0.80, nFine) * 0.18;

        float totalDust = ringDens * 4.8 + wisp * 1.2;
        if (totalDust > 0.01) {
            vs.density += totalDust;
            vs.smokeFrac = 1.0;
            vs.dustFrac = 1.0;
            vs.cavity = nBillow;
        }
    }

    // -----------------------------------------------------------------
    // 2. Incandescent Detonation Stem (y in [0.0, 1.56])
    // -----------------------------------------------------------------
    if (p.y < 1.64 && rXZ < 0.78) {
        float yNorm = saturate(p.y / 1.52);
        // Flares at ground impact, tight energetic column, feeds into mushroom throat
        float stemR = mix(0.30, 0.16, smoothstep(0.0, 0.28, yNorm))
                    + 0.22 * smoothstep(0.68, 1.0, yNorm);

        vec3 stemP = p * vec3(3.3, 2.0, 3.3) - vec3(0.0, t * 1.55, 0.0);
        float nStem = fastShadow ? billowFbm3Fast(stemP) : billowFbm3(stemP);
        float nWisp = fastShadow ? 0.5 : fbm3(stemP * 1.9 + vec3(2.1, 0.0, 5.7));

        float radial = rXZ - (stemR + (nStem - 0.46) * 0.22);
        float stemMask = smoothstep(0.14, -0.10, radial) * smoothstep(1.62, 1.22, p.y)
                       * smoothstep(-0.02, 0.04, p.y);

        if (stemMask > 0.005) {
            float coreHeat = smoothstep(stemR * 0.95, 0.0, rXZ) * (0.76 + 0.36 * nStem);
            // Blinding white-yellow strictly confined to the narrow central stem & base
            float baseBoost = 0.42 * exp(-p.y * 1.55);
            float stemTemp = clamp((coreHeat * 1.15 + baseBoost) * bs.stemBright, 0.0, 1.36);

            float stemD = stemMask * (4.2 + 2.4 * nWisp);
            vs.density += stemD;
            vs.temp = max(vs.temp, stemTemp);
            float edgeSmoke = smoothstep(0.58, 0.14, coreHeat);
            vs.smokeFrac = mix(vs.smokeFrac, edgeSmoke * 0.78, saturate(stemD / max(vs.density, 1e-4)));
            vs.dustFrac *= 1.0 - saturate(stemMask * 2.0);
            vs.cavity = mix(vs.cavity, nStem, saturate(stemMask));
        }
    }

    // -----------------------------------------------------------------
    // 3. Mushroom Cloud: Sculpted Smoke Collar + Fiery Cauliflower Cap
    // -----------------------------------------------------------------
    if (p.y > 0.82 && p.y < 3.05 && rXZ < 1.65) {
        vec2 radDir = p.xz / max(rXZ, 1e-4);

        // --- 3a. Wide Billowing Smoke Collar / Skirt (y ~ 1.15..1.80) ---
        vec3 collarP = p - vec3(0.0, bs.capY - 0.44, 0.0);
        float collarDist = length(vec3(collarP.x * 0.72, collarP.y * 2.15, collarP.z * 0.72)) / bs.capScale;

        vec3 cNoiseP = collarP * 2.65 - vec3(radDir.x * t * 0.32, t * 0.42, radDir.y * t * 0.32);
        float cBillow = fastShadow ? billowFbm3Fast(cNoiseP) : billowFbm3(cNoiseP);
        float cDetail = fastShadow ? 0.5 : fbm3(cNoiseP * 2.3 + vec3(6.3, 3.1, 1.9));

        float collarEdge = 0.90 + 0.38 * cBillow;
        float collarShape = smoothstep(collarEdge, collarEdge - 0.34, collarDist);
        float collarDens = collarShape * (5.6 + 2.4 * cDetail);

        // --- 3b. Upper Fiery Cauliflower Mushroom Cap (y ~ 1.55..2.70) ---
        vec3 capP = p - vec3(0.0, bs.capY + 0.16, 0.0);
        float capR = length(vec3(capP.x * 0.96, capP.y * 1.22, capP.z * 0.96)) / bs.capScale;

        float rollOut = smoothstep(-0.3, 0.4, capP.y);
        vec3 fNoiseP = capP * 3.05 - vec3(radDir.x * rollOut * t * 0.28, t * 0.58, radDir.y * rollOut * t * 0.28);
        float fBillow = fastShadow ? billowFbm3Fast(fNoiseP) : billowFbm3(fNoiseP);
        float fFine = fastShadow ? 0.5 : fbm3(fNoiseP * 2.6 + vec3(11.2, 4.7, 3.3));

        float capEdge = 0.80 + 0.40 * fBillow;
        // Sharp opaque cauliflower silhouette edge
        float capShape = smoothstep(capEdge, capEdge - 0.30, capR);
        float capDens = capShape * (6.4 + 3.0 * fFine);

        float cloudDens = collarDens + capDens;
        if (cloudDens > 0.01) {
            // Fiery deep orange-amber core peeking through deep cauliflower crevices
            vec3 fireCenter = vec3(-0.08, bs.capY + 0.10, 0.06);
            float fireDist = length((p - fireCenter) * vec3(1.12, 1.32, 1.12)) / bs.capScale;

            // Crevices (low fBillow ridges / turbulent cracks) glow deep orange; outer puffs cool to smoke
            float crevice = smoothstep(0.18, 0.78, 1.0 - fBillow * 0.72) * 0.65 + (1.0 - fFine) * 0.35;
            float capFireMask = smoothstep(0.86, 0.16, fireDist) * (0.35 + 0.82 * crevice);

            // Outer right & upper-right cauliflower billows cool into crisp sculpted dense smoke (matching 03.png)
            float coolMantle = smoothstep(0.10, 0.78, p.x * 0.72 + (p.y - bs.capY) * 0.48 + 0.12)
                             * smoothstep(0.32, 0.72, capR);
            capFireMask *= (1.0 - 0.88 * coolMantle);

            // Collar is mostly sculpted smoke with warm fire peeking in central throat
            float throatHeat = smoothstep(0.48, 0.10, rXZ) * smoothstep(1.80, 1.15, p.y) * 0.62;
            // Cap temperature deliberately capped around 0.88 so it stays rich fiery orange-amber!
            float fireTemp = clamp(max(capFireMask * 0.88, throatHeat) * bs.stemBright, 0.0, 0.92);

            float localSmoke = mix(0.98, 0.28, smoothstep(0.28, 0.82, fireTemp));
            localSmoke = max(localSmoke, smoothstep(0.18, 0.65, collarDens / max(cloudDens, 1e-4)) * 0.92);

            vs.density += cloudDens;
            float w = cloudDens / max(vs.density, 1e-4);
            vs.smokeFrac = mix(vs.smokeFrac, localSmoke, w);
            vs.dustFrac = mix(vs.dustFrac, 0.0, w);
            vs.temp = max(vs.temp, fireTemp * smoothstep(0.06, 0.45, capShape + throatHeat));
            float localCav = mix(fBillow, cBillow, collarDens / max(cloudDens, 1e-4));
            vs.cavity = mix(vs.cavity, localCav, w);
        }
    }

    return vs;
}

// -----------------------------------------------------------------------------
// Wilson Condensation Dome Shell Shading (Fresnel, Wispy Mist, Glistening Spec)
// -----------------------------------------------------------------------------
vec4 evalCondensationShell(vec3 p, vec3 N, vec3 rd, bool isFront, BlastState bs, LightRig L) {
    vec3 local = (p - bs.domeCenter) / bs.domeR;
    vec3 V = -rd;
    vec3 Nf = isFront ? N : -N;
    float NdotV = saturate(dot(Nf, V));

    float bottomFade = smoothstep(-0.78, -0.44, local.y);
    if (bottomFade <= 0.001) return vec4(0.0);

    // Wispy condensation streaks & vapor clouds hugging the upper hemisphere
    vec3 flowP = local * 3.5 + vec3(0.0, -bs.t * 0.18, 0.0);
    flowP.xz = rot2(local.y * 0.65 + bs.t * 0.08) * flowP.xz;
    float wisp1 = fbm3(flowP);
    float wisp2 = billowFbm3Fast(flowP * 1.9 + vec3(5.4, 2.2, 8.7));

    // Clearer center window so inner orange fireball reads crisply (especially in Macro Close-up!)
    float upperCap = smoothstep(0.05, 0.78, local.y);
    float mistBands = smoothstep(0.36, 0.80, wisp1 * 0.62 + wisp2 * 0.38);
    float mistAlpha = (0.025 + 0.24 * upperCap * mistBands + 0.08 * mistBands) * bottomFade;

    // Physically-motivated Fresnel rim
    float fresnel = 0.035 + 0.965 * pow(1.0 - NdotV, 3.8);
    float rimGlow = pow(1.0 - NdotV, 2.4) * 0.58 + pow(1.0 - NdotV, 7.0) * 0.95;

    // Micro-normal ripple for glistening condensed water-droplet speculars
    vec3 microPerturb = vec3(
        fbm3(local * 7.5 + vec3(1.1, 0.0, 0.0)) - 0.5,
        fbm3(local * 7.5 + vec3(0.0, 2.3, 0.0)) - 0.5,
        fbm3(local * 7.5 + vec3(0.0, 0.0, 3.7)) - 0.5
    );
    vec3 Nspec = normalize(Nf + microPerturb * 0.15);

    vec3 keySpecDir = normalize(vec3(0.68, 0.42, 0.60));
    vec3 H1 = normalize(keySpecDir + V);
    float spec1 = pow(max(dot(Nspec, H1), 0.0), 54.0) * 1.45
                + pow(max(dot(Nspec, H1), 0.0), 14.0) * 0.18;

    vec3 rimSpecDir = normalize(vec3(-0.74, -0.16, 0.65));
    vec3 H2 = normalize(rimSpecDir + V);
    float spec2 = pow(max(dot(Nspec, H2), 0.0), 38.0) * 0.68;

    vec3 lightKeyH = normalize(L.keyDir + V);
    float specRig = pow(max(dot(Nspec, lightKeyH), 0.0), 36.0) * 0.65;

    // Cool silver-white condensation mist + subtle warm internal fireball scatter
    vec3 coolMistCol = vec3(0.76, 0.84, 0.95) * (0.20 + 0.36 * saturate(dot(Nf, L.keyDir) * 0.5 + 0.5));
    coolMistCol += L.keyCol * (0.22 * max(dot(Nf, L.keyDir), 0.0) + 0.10);
    coolMistCol += L.rimCol * (0.42 * pow(1.0 - NdotV, 2.2));

    vec3 toFire = normalize(vec3(0.0, bs.capY + 0.05, 0.0) - p);
    float fireFace = saturate(dot(-N, toFire) * 0.65 + 0.35);
    float lowerWarmth = smoothstep(0.45, -0.40, local.y);
    vec3 warmBounce = vec3(0.95, 0.40, 0.10) * (0.12 + 0.34 * lowerWarmth) * fireFace
                    * bs.stemBright * L.blastLightScale;

    vec3 shellCol = coolMistCol + warmBounce;

    float alpha = saturate((mistAlpha + fresnel * 0.38) * (isFront ? 1.0 : 0.42)) * bottomFade;
    vec3 emission = shellCol * (mistAlpha * 0.92 + rimGlow * (isFront ? 0.56 : 0.22));

    if (isFront) {
        vec3 specCol = (uLightMode == 1) ? vec3(0.92) : vec3(0.94, 0.97, 1.0);
        emission += specCol * (spec1 + spec2 * 0.65 + specRig * 0.38) * bottomFade * (0.35 + 0.65 * fresnel);
    }

    return vec4(emission, alpha);
}

// -----------------------------------------------------------------------------
// Ballistic Glowing Sparks & Flying Dirt Embers
// -----------------------------------------------------------------------------
vec3 evalSparks(vec3 ro, vec3 rd, float maxT, BlastState bs, LightRig L) {
    if (uLightMode == 1) return vec3(0.0);

    vec3 sparkSum = vec3(0.0);
    for (int i = 0; i < 28; i++) {
        float fi = float(i);
        float h1 = hash11(fi * 17.31 + 1.7);
        float h2 = hash11(fi * 31.17 + 4.3);
        float h3 = hash11(fi * 47.89 + 9.1);
        float h4 = hash11(fi * 73.13 + 2.9);

        float ang = h1 * TAU + 0.25 * sin(fi);
        float cycle = fract(bs.t * (0.34 + 0.32 * h2) + h3);
        float life = sin(cycle * PI);

        bool fromRing = (i >= 14);
        float r0 = fromRing ? (bs.ringR * (0.78 + 0.32 * h4)) : (0.18 + 0.35 * h4);
        float y0 = fromRing ? (0.08 + 0.16 * h2) : (0.35 + 1.15 * h2);

        float speedR = fromRing ? (1.1 + 1.35 * h3) : (1.35 + 1.65 * h3);
        float speedY = fromRing ? (0.85 + 1.15 * h4) : (0.45 + 1.45 * h4);

        vec3 vel = vec3(cos(ang) * speedR, speedY - 1.35 * cycle, sin(ang) * speedR);
        vec3 pos = vec3(
            cos(ang) * (r0 + speedR * cycle),
            max(0.03, y0 + speedY * cycle - 0.68 * cycle * cycle),
            sin(ang) * (r0 + speedR * cycle)
        );

        vec3 segDir = normalize(vel + vec3(1e-4));
        float segLen = 0.055 + 0.065 * h2;
        vec3 pA = pos - segDir * segLen * 0.5;
        vec3 pB = pos + segDir * segLen * 0.5;

        float tProj = dot(pos - ro, rd);
        if (tProj > 0.1 && tProj < maxT) {
            vec3 q = ro + rd * tProj;
            vec3 ab = pB - pA;
            float u = saturate(dot(q - pA, ab) / max(dot(ab, ab), 1e-6));
            float d = length(q - (pA + ab * u));

            float size = 0.0080 + 0.0065 * h4;
            float glow = exp(-d * d / (size * size));
            vec3 sCol = mix(vec3(2.5, 0.85, 0.16), vec3(3.4, 1.95, 0.68), h4);
            sparkSum += sCol * glow * life * 0.90 * L.fireEmissionScale;
        }
    }
    return sparkSum;
}

// -----------------------------------------------------------------------------
// ACES Filmic Tonemapping with Highlight Soft-Shoulder (%clip < 1%)
// -----------------------------------------------------------------------------
vec3 acesFilmicSoft(vec3 x) {
    const float a = 2.51;
    const float b = 0.03;
    const float c = 2.43;
    const float d = 0.59;
    const float e = 0.14;
    vec3 mapped = (x * (a * x + b)) / (x * (c * x + d) + e);
    mapped = mapped / (1.0 + 0.038 * mapped);
    return clamp(mapped, 0.0, 0.985);
}

// -----------------------------------------------------------------------------
// Main Render
// -----------------------------------------------------------------------------
void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution.xy) / uResolution.y;

    BlastState bs = getBlastState();
    LightRig L = getLightRig();

    // Camera setup: uCamMode 0 = Hero full framing, 1 = ~2.5x macro close-up of dome shell
    vec3 ro, ta;
    float fl;
    if (uCamMode == 1) {
        // ~2.5x macro close-up framing the curved condensation shell refracting the inner fireball
        ro = vec3(0.92, bs.domeCenter.y + 0.14, 3.28);
        ta = vec3(0.28, bs.domeCenter.y + 0.02, 0.0);
        fl = 1.88;
    } else {
        ro = vec3(0.0, 1.24, 6.18);
        ta = vec3(0.0, 1.66, 0.0);
        fl = 1.18;
    }

    vec3 fw = normalize(ta - ro);
    vec3 rt = normalize(cross(fw, vec3(0.0, 1.0, 0.0)));
    vec3 up = cross(rt, fw);
    vec3 rd = normalize(uv.x * rt + uv.y * up + fl * fw);

    // 1. Intersect desert ground plane (y = 0)
    float tGround = 1e5;
    bool hitGround = false;
    if (rd.y < -0.001) {
        float tg = -ro.y / rd.y;
        if (tg > 0.0 && tg < 60.0) {
            tGround = tg;
            hitGround = true;
        }
    }

    // 2. Intersect Wilson condensation dome sphere (front & back walls)
    vec2 tDome = intersectSphere(ro, rd, bs.domeCenter, bs.domeR);
    bool hitDome = (tDome.y > 0.0);
    float tDomeFront = max(tDome.x, 0.0);
    float tDomeBack  = tDome.y;

    // Physical refraction of interior rays passing through the curved shock shell
    vec3 rdRefract = rd;
    if (hitDome && tDome.x > 0.0) {
        vec3 pFront = ro + rd * tDomeFront;
        vec3 nFront = normalize(pFront - bs.domeCenter);
        vec3 nWave = nFront + 0.065 * (vec3(
            noise3(pFront * 3.8 + vec3(0.0, -bs.t * 0.4, 0.0)),
            noise3(pFront * 3.8 + vec3(4.1, -bs.t * 0.4, 2.3)),
            noise3(pFront * 3.8 + vec3(1.7, -bs.t * 0.4, 6.2))
        ) - 0.5);
        nWave = normalize(nWave);

        vec3 refr = refract(rd, nWave, 1.0 / 1.06);
        if (length(refr) > 0.001) {
            float edgeFade = smoothstep(0.08, 0.42, dot(nFront, -rd));
            rdRefract = normalize(mix(rd, refr, edgeFade * 0.88));
        }
    }

    // 3. Base background (deep night sky or bumpy desert terrain)
    vec3 bgCol = hitGround
        ? shadeDesertGround(ro, rd, tGround, bs, L)
        : evalSky(rd, bs, L);

    // 4. Beer-Lambert Volumetric Raymarch (60 steps) with Optical Self-Shadowing
    vec2 tVol = intersectCylinderY(ro, rd, bs.ringR + 0.92, -0.02, bs.domeCenter.y + bs.domeR + 0.25);

    vec3 accum = vec3(0.0);
    float T = 1.0;
    bool drewFrontShell = false;
    bool drewBackShell  = false;

    if (tVol.y > tVol.x) {
        float tStart = max(tVol.x, 0.05);
        float tEnd = min(tVol.y, hitGround ? tGround : tVol.y);

        if (tEnd > tStart) {
            const int STEPS = 60;
            float dt = (tEnd - tStart) / float(STEPS);
            float jitter = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
            float t = tStart + dt * jitter;

            vec3 stemLightPos = vec3(0.0, 0.48, 0.0);
            vec3 capLightPos  = vec3(0.0, bs.capY + 0.06, 0.0);

            float cosKey = dot(rd, L.keyDir);
            float cosRim = dot(rd, L.rimDir);
            float phaseKey = mix(hgPhase(cosKey, 0.28), hgPhase(cosKey, 0.62), 0.45);
            float phaseRim = hgPhase(cosRim, 0.58);

            for (int i = 0; i < STEPS; i++) {
                if (T < 0.006) break;

                // Composite front condensation dome shell at exact depth tDomeFront
                if (hitDome && !drewFrontShell && tDome.x > 0.0 && t >= tDomeFront && tDomeFront < tEnd) {
                    vec3 pShell = ro + rd * tDomeFront;
                    vec3 nShell = normalize(pShell - bs.domeCenter);
                    vec4 sh = evalCondensationShell(pShell, nShell, rd, true, bs, L);
                    accum += T * sh.rgb;
                    T *= (1.0 - sh.a);
                    drewFrontShell = true;
                }

                // Composite back condensation dome shell at exact depth tDomeBack
                if (hitDome && !drewBackShell && t >= tDomeBack && tDomeBack < tEnd) {
                    vec3 pShell = ro + rd * tDomeBack;
                    vec3 nShell = normalize(pShell - bs.domeCenter);
                    vec4 sh = evalCondensationShell(pShell, nShell, rd, false, bs, L);
                    accum += T * sh.rgb;
                    T *= (1.0 - sh.a);
                    drewBackShell = true;
                }

                vec3 p;
                if (hitDome && t > tDomeFront && t < tDomeBack) {
                    vec3 pEnter = ro + rd * tDomeFront;
                    p = pEnter + rdRefract * (t - tDomeFront);
                } else {
                    p = ro + rd * t;
                }

                VolSample vs = evalVolume(p, bs, false);

                if (vs.density > 0.005) {
                    // Strong Beer-Lambert extinction for solid, opaque smoke & dust billows
                    float sigmaT = vs.density * 1.75;
                    float stepT = exp(-sigmaT * dt);

                    // 3-tap directional optical depth toward key light (crisp sculptural self-shadowing!)
                    float dKey1 = evalVolume(p + L.keyDir * 0.14, bs, true).density;
                    float dKey2 = evalVolume(p + L.keyDir * 0.34, bs, true).density;
                    float dKey3 = evalVolume(p + L.keyDir * 0.64, bs, true).density;
                    float keyOD = (dKey1 * 0.16 + dKey2 * 0.24 + dKey3 * 0.34) * 1.45;
                    // Powder-effect style multi-scatter + deep shadow contrast
                    float keyTrans = exp(-keyOD) * (1.0 - 0.45 * exp(-vs.density * 0.45));

                    // Upward sky occlusion for dark undersides & deep billow crevices
                    float dUp = evalVolume(p + vec3(0.0, 0.26, 0.0), bs, true).density;
                    float skyOcc = exp(-dUp * 0.38) * (0.45 + 0.55 * vs.cavity);

                    // Smoke vs earthy desert dust albedo
                    vec3 smokeAlbedo = vec3(0.76, 0.72, 0.68);
                    vec3 dustAlbedo  = vec3(0.46, 0.35, 0.25) * L.dustAlbedoBoost;
                    vec3 albedo = mix(smokeAlbedo, dustAlbedo, vs.dustFrac);
                    // Deepen crevices slightly for rich cauliflower relief
                    albedo *= (0.62 + 0.46 * vs.cavity);

                    // External key + rim + ambient fill
                    vec3 scatter = vec3(0.0);
                    scatter += L.keyCol * (keyTrans * (0.52 + 2.0 * phaseKey));
                    scatter += L.rimCol * (exp(-dKey1 * 0.24) * (0.20 + 2.0 * phaseRim));
                    scatter += L.fillCol * (0.35 + 0.95 * skyOcc);

                    // Internal radial inverse-square blast lighting WITH optical self-shadowing!
                    vec3 toStem = stemLightPos - p;
                    float dStem = length(toStem);
                    vec3 dirStem = toStem / max(dStem, 1e-4);
                    // Sample dust/smoke occlusion between p and the detonation stem
                    float stemOcc1 = evalVolume(p + dirStem * min(0.18, dStem * 0.35), bs, true).density;
                    float stemOcc2 = evalVolume(p + dirStem * min(0.42, dStem * 0.65), bs, true).density;
                    float stemShadow = exp(-(stemOcc1 * 0.22 + stemOcc2 * 0.32) * 1.25);

                    float stemAtt = 1.0 / (0.32 + dStem * dStem * 0.95);
                    // Dust ring inner rim catches rich warm orange; outer side stays shadowed earthy brown
                    float innerFace = smoothstep(bs.ringR + 0.22, bs.ringR - 0.16, length(p.xz));
                    float ringMod = mix(1.0, 0.22 + 0.95 * innerFace, vs.dustFrac);
                    scatter += vec3(2.25, 0.98, 0.26) * stemAtt * stemShadow * ringMod
                             * bs.stemBright * L.blastLightScale;

                    // Internal mushroom fireball bounce light (attenuated by optical depth toward core)
                    vec3 toCap = capLightPos - p;
                    float dCap = length(toCap);
                    vec3 dirCap = toCap / max(dCap, 1e-4);
                    float capOcc = evalVolume(p + dirCap * min(0.22, dCap * 0.45), bs, true).density;
                    float capShadow = exp(-capOcc * 0.36);
                    float capAtt = 1.0 / (0.48 + dCap * dCap * 1.15);
                    // Dust ring gets gentler cap bounce so outer dust stays earthy brown
                    float capDustMod = mix(1.0, 0.32, vs.dustFrac);
                    scatter += vec3(1.85, 0.62, 0.12) * capAtt * capShadow * capDustMod
                             * bs.stemBright * L.blastLightScale;

                    // Calibrated blackbody emission (rich deep orange-amber in cap, white-gold in narrow stem)
                    float emitMask = smoothstep(0.14, 0.48, vs.temp) * (1.0 - vs.smokeFrac * 0.68);
                    vec3 fireEmit = blackbodyFire(vs.temp) * emitMask * 1.35 * L.fireEmissionScale;

                    // Energy-conserving Beer-Lambert step integration
                    vec3 S = albedo * scatter * (0.28 + 0.72 * vs.smokeFrac) + fireEmit;
                    accum += T * S * (1.0 - stepT);
                    T *= stepT;
                }

                t += dt;
            }
        }
    }

    // Composite condensation shell outside volume bounds (top of dome)
    if (hitDome && !drewFrontShell && tDome.x > 0.0 && tDomeFront < tGround) {
        vec3 pShell = ro + rd * tDomeFront;
        vec3 nShell = normalize(pShell - bs.domeCenter);
        vec4 sh = evalCondensationShell(pShell, nShell, rd, true, bs, L);
        accum += T * sh.rgb;
        T *= (1.0 - sh.a);
    }
    if (hitDome && !drewBackShell && tDomeBack > 0.0 && tDomeBack < tGround) {
        vec3 pShell = ro + rd * tDomeBack;
        vec3 nShell = normalize(pShell - bs.domeCenter);
        vec4 sh = evalCondensationShell(pShell, nShell, rd, false, bs, L);
        accum += T * sh.rgb;
        T *= (1.0 - sh.a);
    }

    vec3 col = accum + T * bgCol;

    // 5. Ballistic sparks & embers
    col += evalSparks(ro, rd, hitGround ? tGround : 25.0, bs, L) * (0.45 + 0.55 * T);

    // Subtle vignette
    float vig = 1.0 - 0.12 * dot(uv, uv);
    col *= vig;

    // 6. ACES Filmic Tonemapping + Gamma 2.2
    col = acesFilmicSoft(max(col, vec3(0.0)));
    col = pow(col, vec3(1.0 / 2.2));

    // Guarantee deep night sky floor (lumMin ~6-12, %black = 0%)
    col = max(col, vec3(0.024, 0.026, 0.034));

    // Mode 1: enforce exact neutral grayscale (R == G == B)
    if (uLightMode == 1) {
        float g = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = vec3(g);
    }

    fragColor = vec4(col, 1.0);
}
