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

// ============================================================================
// 07_pulsing_emp_electromagnetic_grid.glsl
// Seamless 3.0s animated sci-fi EMP electromagnetic shockwave dome expanding
// across a dark beveled metallic hexagonal circuit arena.
//
// Features:
//   - Two-level nested hexagonal floor SDF: macro hexes with recessed vivid
//     golden-amber conduit channels & raised circular metallic vertex node hubs,
//     filled with dark gunmetal beveled micro-hex tiles whose seams ignite in
//     cascading electric-cyan & amber circuit pulses as EMP waves sweep outward.
//   - Central blazing electric-cyan EMP energy core hovering above a hexagonal
//     emitter pedestal with counter-rotating containment rings (pure VFX).
//   - Translucent refractive electric-cyan EMP shockwave hemisphere(s) with
//     clear dark interior, sharp Fresnel rim, marbled electric plasma wisps,
//     faint circuit etching, and blazing floor intersection ring; 3.0s loop.
//   - Multi-octave jagged branching 3D cobalt-white lightning arcs shooting
//     from the core across the dome surface and foreground hex floor, plus 3D
//     radial amber/cyan spark streaks drifting outward seamlessly.
//   - Unit-sign tetrahedral normals, ACES filmic tonemapping (%clip < 1%,
//     lumMin ~8-15, %black < 2%), fast SwiftShader execution.
//   - uLightMode: 0=hero dark sci-fi arena, 1=pure neutral grayscale form/grid
//     study (strict R==G==B), 2=grazing raking key light, 3=backlit rim light.
//   - uCamMode: 0=hero framing, 1=~2.5x macro close-up of beveled hex tiles,
//     amber-gold conduits, vertex node hub, and EMP dome intersection.
// ============================================================================

const float PI  = 3.14159265359;
const float TAU = 6.28318530718;

// --- Fast sin-free integer hashes & value noise ---
float hash11(float p) {
    uint n = uint(int(floor(p))) * 1597334673u;
    n = (n ^ (n >> 13u)) * 3812015801u;
    return float(n) * (1.0 / 4294967295.0);
}

float hash12(vec2 p2) {
    uvec2 q = uvec2(ivec2(floor(p2))) * uvec2(1597334673u, 3812015801u);
    uint n = (q.x ^ q.y) * 1597334673u;
    return float(n) * (1.0 / 4294967295.0);
}

float hash13(vec3 p3) {
    uvec3 q = uvec3(ivec3(floor(p3))) * uvec3(1597334673u, 3812015801u, 2798796415u);
    uint n = (q.x ^ q.y ^ q.z) * 1597334673u;
    return float(n) * (1.0 / 4294967295.0);
}

float vnoise2(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    float a = hash12(i);
    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 vnoise3(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);
    return mix(mix(nx00, nx10, u.y), mix(nx01, nx11, u.y), u.z);
}

float fbm3(vec3 p) {
    float v = 0.0;
    float a = 0.5;
    for (int i = 0; i < 4; i++) {
        v += a * vnoise3(p);
        p = p * 2.04 + vec3(17.3, -9.1, 11.7);
        a *= 0.5;
    }
    return v;
}

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

// Sharp periodic triangle wave for organic jagged lightning kinks
float triWave(float x) {
    return abs(fract(x) - 0.5) * 4.0 - 1.0;
}

// --- Exact Hexagonal Grid ---
vec4 hexGrid(vec2 p, out float edgeDist, out float vertexDist) {
    const vec2 s = vec2(1.0, 1.7320508);
    const vec2 h = s * 0.5;
    vec2 a = mod(p, s) - h;
    vec2 b = mod(p - h, s) - h;
    vec2 gv = (dot(a, a) < dot(b, b)) ? a : b;
    vec2 id = floor((p - gv) / h + 0.5);

    vec2 ap = abs(gv);
    float hd = max(ap.x, ap.x * 0.5 + ap.y * 0.8660254);
    edgeDist = 0.5 - hd;

    float dv1 = length(ap - vec2(0.0, 0.57735027));
    float dv2 = length(ap - vec2(0.5, 0.28867513));
    vertexDist = min(dv1, dv2);

    return vec4(gv, id);
}

// --- Seamless 3.0s EMP Wave Kinematics ---
struct EmpState {
    float phase;
    float tauPhase;
    float r1;
    float env1;
    float p1;
    float r2;
    float env2;
    float p2;
    float corePulse;
};

EmpState getEmpState(float t) {
    EmpState st;
    st.phase = fract(t / 3.0);
    st.tauPhase = st.phase * TAU;

    // Primary wave: at t=1.2 (phase=0.40), p1=0.54 -> r1 ~= 3.15, env1 = 1.0
    st.p1 = fract(st.phase + 0.14);
    st.r1 = mix(0.45, 4.70, pow(st.p1, 0.72));
    st.env1 = smoothstep(0.0, 0.12, st.p1) * (1.0 - smoothstep(0.76, 1.0, st.p1));

    // Secondary staggered wave: fades in smoothly after p2 > 0.08 so it never crowds core at t=1.2
    st.p2 = fract(st.phase + 0.64);
    st.r2 = mix(0.45, 4.70, pow(st.p2, 0.72));
    st.env2 = smoothstep(0.08, 0.22, st.p2) * (1.0 - smoothstep(0.76, 1.0, st.p2)) * 0.68;

    st.corePulse = 0.88 + 0.22 * cos((st.phase + 0.14) * TAU * 2.0);
    return st;
}

// --- Floor Relief Heightfield ---
float floorHeight(vec2 xz, out float macroEdge, out float macroVert, out float microEdge, out vec2 microId) {
    vec2 pMacro = xz * 0.52;
    hexGrid(pMacro, macroEdge, macroVert);

    vec2 pMicro = xz * 2.60;
    vec4 hMicro = hexGrid(pMicro, microEdge, microId.x);
    microId = hMicro.zw;

    float r = length(xz);

    // Beveled micro-hex metallic floor tiles
    float microBevel = smoothstep(0.014, 0.085, microEdge);
    float tileH = -0.024 + 0.026 * microBevel;
    float tileRand = hash12(microId);
    tileH += (tileRand - 0.5) * 0.004 * microBevel;

    // Macro-hex raised metallic rail framing the glowing golden conduit channel
    float railMask = smoothstep(0.092, 0.068, macroEdge) * smoothstep(0.032, 0.048, macroEdge);
    float channelMask = smoothstep(0.040, 0.024, macroEdge);
    float h = tileH + railMask * 0.020 - channelMask * 0.024;

    // Macro-hex circular vertex node hubs (sculpted dark metallic collar + recessed lens)
    float hubOuter = smoothstep(0.148, 0.120, macroVert);
    float hubRing  = hubOuter * smoothstep(0.056, 0.076, macroVert);
    float hubCore  = smoothstep(0.064, 0.046, macroVert);
    h = mix(h, 0.004, hubOuter);
    h += hubRing * 0.038 - hubCore * 0.016;

    // Central emitter platform (concentric stepped disc at r < 1.25)
    float centerPad = smoothstep(1.30, 1.12, r);
    float ringGroove = sin(r * 16.0) * 0.5 + 0.5;
    float padH = 0.012 + 0.028 * smoothstep(0.65, 0.42, r) - 0.010 * smoothstep(0.75, 0.92, ringGroove) * centerPad;
    h = mix(h, padH, centerPad * 0.85);

    // Outer circular arena perimeter conduit ring (r ~ 5.65)
    float outerRing = abs(r - 5.65);
    float outerRail = smoothstep(0.24, 0.16, outerRing) * smoothstep(0.06, 0.11, outerRing);
    float outerChan = smoothstep(0.09, 0.05, outerRing);
    h += outerRail * 0.040 - outerChan * 0.018;

    // Outer stepped arena wall ribs (r > 6.3)
    if (r > 6.2) {
        float ang = atan(xz.y, xz.x);
        float rib = 0.5 + 0.5 * cos(ang * 24.0);
        float wallRise = smoothstep(6.2, 7.8, r) * (0.45 + 0.35 * smoothstep(0.5, 0.85, rib));
        h += wallRise;
    }

    return h;
}

float sdTorus(vec3 p, vec2 t) {
    vec2 q = vec2(length(p.xz) - t.x, p.y);
    return length(q) - t.y;
}

float mapScene(vec3 p, float tauPhase, out int matId) {
    float me, mv, mie;
    vec2 mid;
    float fh = floorHeight(p.xz, me, mv, mie, mid);
    float d = (p.y - fh) * 0.72;
    matId = 1;

    // Central EMP emitter containment rings (pure VFX, no character)
    vec3 q = p - vec3(0.0, 0.66, 0.0);
    if (length(q) < 0.92) {
        vec3 q1 = q;
        q1.xz = rot2(tauPhase * 1.0) * q1.xz;
        q1.xy = rot2(0.55) * q1.xy;
        float dRing1 = sdTorus(q1, vec2(0.44, 0.016));

        vec3 q2 = q;
        q2.xz = rot2(-tauPhase * 2.0) * q2.xz;
        q2.yz = rot2(-0.72) * q2.yz;
        float dRing2 = sdTorus(q2, vec2(0.30, 0.013));

        float dRings = min(dRing1, dRing2);
        if (dRings < d) {
            d = dRings;
            matId = 2;
        }
    }

    return d;
}

float mapSceneDist(vec3 p, float tauPhase) {
    int dummy;
    return mapScene(p, tauPhase, dummy);
}

// Unit-sign tetrahedral normal
vec3 calcNormal(vec3 p, float tauPhase, float eps) {
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * mapSceneDist(p + k.xyy * eps, tauPhase) +
        k.yyx * mapSceneDist(p + k.yyx * eps, tauPhase) +
        k.yxy * mapSceneDist(p + k.yxy * eps, tauPhase) +
        k.xxx * mapSceneDist(p + k.xxx * eps, tauPhase)
    );
}

// --- Analytic Ray-Sphere Intersection ---
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);
}

// --- Closest Vector Between Ray (ro, rd) and 3D Segment (a, b) ---
// Outputs closest 3D offset vector (pRay - pSeg), ray t, and segment u.
vec3 raySegmentClosest(vec3 ro, vec3 rd, vec3 a, vec3 b, out float tOut, out float uOut) {
    vec3 ba = b - a;
    vec3 oa = ro - a;
    float dotBA = dot(ba, ba);
    float dotRD = dot(rd, ba);
    float dotOA_RD = dot(oa, rd);
    float dotOA_BA = dot(oa, ba);
    float denom = max(dotBA - dotRD * dotRD, 1e-5);

    float u = clamp((dotOA_BA - dotOA_RD * dotRD) / denom, 0.0, 1.0);
    float t = max(0.0, dot(a + ba * u - ro, rd));
    u = clamp(dot(ro + rd * t - a, ba) / max(dotBA, 1e-5), 0.0, 1.0);
    t = max(0.0, dot(a + ba * u - ro, rd));

    tOut = t;
    uOut = u;
    return (ro + rd * t) - (a + ba * u);
}

// --- Multi-Octave Jagged 3D Displacement for Lightning ---
vec3 boltJaggedOffset(float u, float fb, float tauP, vec3 side1, vec3 side2, float amp) {
    float env = sin(u * PI);
    // 3 octaves of sharp triangular kinks (100% periodic in tauP!)
    float k1 = triWave(u * 3.5 + fb * 1.37 + sin(tauP * 1.0 + fb) * 0.25);
    float k2 = triWave(u * 8.5 - fb * 2.13 + cos(tauP * 2.0 + fb * 1.7) * 0.35) * 0.48;
    float k3 = triWave(u * 19.0 + fb * 3.71 + sin(tauP * 3.0 - fb) * 0.45) * 0.22;

    float m1 = triWave(u * 4.0 + fb * 2.91 + cos(tauP * 1.0 - fb * 0.8) * 0.25);
    float m2 = triWave(u * 9.5 + fb * 0.83 + sin(tauP * 2.0 + fb * 2.3) * 0.35) * 0.46;
    float m3 = triWave(u * 21.0 - fb * 1.61 + cos(tauP * 3.0 + fb) * 0.45) * 0.20;

    return (side1 * (k1 + k2 + k3) + side2 * (m1 + m2 + m3)) * amp * (0.20 + 0.90 * env);
}

// --- 3D Jagged Branching Cobalt-White Lightning Arcs ---
vec3 evalLightning(vec3 ro, vec3 rd, float tMax, EmpState st, bool isGray) {
    vec3 coreOrigin = vec3(0.0, 0.66, 0.0);
    float R = max(st.r1, 1.8);
    float tauP = st.tauPhase;

    vec3 acc = vec3(0.0);

    for (int b = 0; b < 6; b++) {
        float fb = float(b);
        float flick = 0.68 + 0.32 * sin(tauP * (2.0 + mod(fb, 3.0)) + fb * 1.35 + 0.6);
        flick *= smoothstep(0.02, 0.18, st.env1 + st.env2 * 0.7);

        vec3 pEnd;
        float archH;
        float spreadAmp;
        if (b == 0) {
            // Upper-left dramatic dome-crawling bolt
            pEnd = vec3(-R * 1.22, R * 1.15, 0.30);
            archH = 0.48;
            spreadAmp = 0.20;
        } else if (b == 1) {
            // Upper-right dramatic dome-crawling bolt
            pEnd = vec3(R * 0.68, R * 1.22, -0.25);
            archH = 0.42;
            spreadAmp = 0.18;
        } else if (b == 2) {
            // Far-left sweeping bolt
            pEnd = vec3(-R * 1.55, R * 0.48, 0.90);
            archH = 0.32;
            spreadAmp = 0.17;
        } else if (b == 3) {
            // Right-side horizontal crackling bolt
            pEnd = vec3(R * 1.52, R * 0.40, 0.85);
            archH = 0.28;
            spreadAmp = 0.17;
        } else if (b == 4) {
            // Hero foreground ground-skimming bolt sweeping toward bottom-left!
            pEnd = vec3(-1.45, 0.08, 5.25);
            archH = 0.18;
            spreadAmp = 0.22;
        } else {
            // Secondary upper-right thin crackling arc
            pEnd = vec3(R * 1.40, R * 0.78, -0.75);
            archH = 0.38;
            spreadAmp = 0.15;
        }

        float sway = sin(tauP * 1.0 + fb * 2.1) * 0.12;
        pEnd.xz = rot2(sway) * pEnd.xz;

        vec3 dir = normalize(pEnd - coreOrigin);
        vec3 upRef = abs(dir.y) > 0.85 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);
        vec3 side1 = normalize(cross(dir, upRef));
        vec3 side2 = normalize(cross(dir, side1));

        // Fast coarse ray-to-chord cull (skips ~65% of pixels immediately!)
        float tCoarse, uCoarse;
        vec3 dCoarse = raySegmentClosest(ro, rd, coreOrigin, pEnd, tCoarse, uCoarse);
        if (length(dCoarse) > 1.35) continue;

        const int SEGS = 12;
        vec3 prevP = coreOrigin;
        float minBoltD = 1e5;
        float minBoltS = 0.0;
        vec3 forkOrigin1 = coreOrigin;
        vec3 forkOrigin2 = coreOrigin;

        for (int s = 1; s <= SEGS; s++) {
            float u = float(s) / float(SEGS);
            vec3 baseP = mix(coreOrigin, pEnd, u);
            baseP.y += sin(u * PI) * archH;
            if (b < 4 || b == 5) {
                float dToCenter = length(baseP);
                if (u > 0.22 && u < 0.88) {
                    float targetR = mix(dToCenter, R * 1.01, 0.48 * sin(u * PI));
                    baseP = normalize(baseP) * targetR;
                }
            } else {
                baseP.y = max(baseP.y, 0.06);
            }

            vec3 curP = baseP + boltJaggedOffset(u, fb, tauP, side1, side2, spreadAmp);
            curP.y = max(curP.y, 0.04);

            if (s == 4) forkOrigin1 = curP;
            if (s == 7) forkOrigin2 = curP;

            float tSeg, uSeg;
            vec3 diff = raySegmentClosest(ro, rd, prevP, curP, tSeg, uSeg);
            if (tSeg < tMax + 0.12) {
                float sGlob = (float(s - 1) + uSeg) / float(SEGS);
                // Continuous high-frequency 3D perpendicular micro-kink displacement!
                float hf1 = triWave(sGlob * 42.0 + fb * 5.1 + sin(tauP * 3.0 + fb) * 0.4) * 0.022;
                float hf2 = triWave(sGlob * 86.0 - fb * 3.7 + cos(tauP * 4.0 - fb) * 0.4) * 0.010;
                vec3 diffJ = diff - (side1 * hf1 + side2 * hf2) * sin(sGlob * PI);
                float dEff = length(diffJ);
                if (dEff < minBoltD) {
                    minBoltD = dEff;
                    minBoltS = sGlob;
                }
            }
            prevP = curP;
        }

        // Razor-sharp white-blue core + vivid saturated electric cobalt halo
        float widthScale = (b == 5) ? 1.45 : 1.08;
        float coreW  = exp(-minBoltD * 125.0 * widthScale);
        float innerW = exp(-minBoltD * 28.0 * widthScale);
        float outerW = exp(-minBoltD * 7.8 * widthScale);

        float tipFade = 1.0 - smoothstep(0.84, 1.0, minBoltS) * 0.42;
        float bInt = flick * tipFade;

        if (isGray) {
            acc += vec3(coreW * 0.85 + innerW * 0.16) * bInt;
        } else {
            vec3 boltCol = vec3(0.92, 0.97, 1.00) * coreW * 1.75
                         + vec3(0.08, 0.48, 1.00) * innerW * 0.72
                         + vec3(0.02, 0.16, 0.72) * outerW * 0.18;
            acc += boltCol * bInt;
        }

        // Branching lightning tendrils (2 forks per hero bolt!)
        if (b < 5) {
            for (int fk = 0; fk < 2; fk++) {
                float fSign = (fk == 0) ? 1.0 : -1.0;
                if (mod(fb, 2.0) > 0.5) fSign = -fSign;
                vec3 fStart = (fk == 0) ? forkOrigin1 : forkOrigin2;
                vec3 fDir = normalize(dir + side1 * (0.58 * fSign) + side2 * (fk == 0 ? 0.25 : -0.22));
                vec3 fEnd = fStart + fDir * (R * (fk == 0 ? 0.42 : 0.30));
                fEnd.y = max(fEnd.y, 0.05);

                vec3 fP1 = mix(fStart, fEnd, 0.35) + (side2 * 0.11 + side1 * 0.06 * fSign) * triWave(fb * 1.7 + float(fk) * 2.3 + tauP * 0.318);
                vec3 fP2 = mix(fStart, fEnd, 0.70) - (side2 * 0.09 - side1 * 0.05 * fSign) * triWave(fb * 2.4 + float(fk) * 1.1 - tauP * 0.318);
                fP1.y = max(fP1.y, 0.05);
                fP2.y = max(fP2.y, 0.05);

                float t1, u1, t2, u2, t3, u3;
                float fd = 1e5;
                vec3 v1 = raySegmentClosest(ro, rd, fStart, fP1, t1, u1);
                if (t1 < tMax + 0.12) fd = min(fd, length(v1));
                vec3 v2 = raySegmentClosest(ro, rd, fP1, fP2, t2, u2);
                if (t2 < tMax + 0.12) fd = min(fd, length(v2));
                vec3 v3 = raySegmentClosest(ro, rd, fP2, fEnd, t3, u3);
                if (t3 < tMax + 0.12) fd = min(fd, length(v3));

                float fCore = exp(-fd * 165.0);
                float fHalo = exp(-fd * 36.0);
                if (isGray) {
                    acc += vec3(fCore * 0.55 + fHalo * 0.08) * bInt;
                } else {
                    acc += (vec3(0.86, 0.95, 1.0) * fCore * 1.15 + vec3(0.06, 0.42, 1.0) * fHalo * 0.38) * bInt;
                }
            }
        }
    }

    return acc;
}

// --- 3D Radial Plasma & Amber Ember Sparks (100% Seamless 3.0s) ---
vec3 evalSparks(vec3 ro, vec3 rd, float tMax, EmpState st, bool isGray) {
    vec3 acc = vec3(0.0);
    const int NUM_SPARKS = 28;
    for (int i = 0; i < NUM_SPARKS; i++) {
        float fi = float(i);
        float h1 = hash11(fi * 13.7 + 1.0);
        float h2 = hash11(fi * 29.3 + 5.0);
        float h3 = hash11(fi * 47.1 + 9.0);

        float life = fract(st.phase + h1);
        float env = smoothstep(0.0, 0.12, life) * (1.0 - smoothstep(0.76, 1.0, life));

        float az = h2 * TAU;
        float el = mix(0.08, 1.20, h3);
        vec3 dir = vec3(cos(az) * cos(el), sin(el), sin(az) * cos(el));

        float distR = mix(0.75, 5.20, pow(life, 0.78));
        vec3 pA = vec3(0.0, 0.25, 0.0) + dir * distR;
        vec3 pB = pA + dir * (0.11 + 0.09 * (1.0 - life));

        float tS, uS;
        vec3 diff = raySegmentClosest(ro, rd, pA, pB, tS, uS);
        if (tS < tMax) {
            float d = length(diff);
            float glow = exp(-d * 78.0) * env;
            float halo = exp(-d * 24.0) * env;
            bool isAmber = (mod(fi, 3.0) < 1.9);
            if (isGray) {
                acc += vec3(glow * 0.45);
            } else if (isAmber) {
                acc += (vec3(1.0, 0.62, 0.14) * glow * 1.15 + vec3(0.95, 0.30, 0.02) * halo * 0.22);
            } else {
                acc += (vec3(0.35, 0.90, 1.0) * glow * 1.05 + vec3(0.05, 0.45, 1.0) * halo * 0.22);
            }
        }
    }
    return acc;
}

// --- Translucent Refractive Electric-Cyan EMP Dome Shading ---
// Clear dark interior with razor-sharp glowing cyan Fresnel shell & marbled plasma wisps!
vec3 shadeDomeHit(vec3 pHit, vec3 rd, float R, float env, float tauPhase, bool isFront, bool isGray) {
    if (env <= 0.001 || pHit.y < -0.01) return vec3(0.0);

    vec3 n = normalize(pHit);
    float ndv = abs(dot(rd, n));
    float fresRim  = pow(1.0 - ndv, 3.4);
    float fresSoft = pow(1.0 - ndv, 1.8);

    // Seamless 3D marbled plasma turbulence on the spherical shell
    vec3 q = n * 3.8;
    vec3 drift = vec3(cos(tauPhase) * 0.65, sin(tauPhase) * 0.55, sin(tauPhase) * 0.65);
    float f1 = fbm3(q + drift);
    float f2 = fbm3(q * 2.25 - drift * 1.4 + vec3(f1 * 1.8));
    // High-contrast wispy veins (mostly clear interior!)
    float wisps = smoothstep(0.46, 0.86, f2);

    // Subtle geometric hex-energy circuit etching visible near rim & wisps
    vec2 sphUv = vec2(atan(n.z, n.x) * 3.82, asin(clamp(n.y, -1.0, 1.0)) * 3.82);
    float de, dv;
    hexGrid(sphUv, de, dv);
    float circuitEtch = smoothstep(0.036, 0.008, de) * (0.20 + 0.80 * wisps) * (0.25 + 0.75 * fresSoft);

    // Crisp blazing contact seam where the dome slices into the hex floor
    float floorSeam = exp(-max(pHit.y, 0.0) * 11.5);
    float floorSeamCore = exp(-max(pHit.y, 0.0) * 34.0);

    float sideWeight = isFront ? 1.0 : 0.22;

    if (isGray) {
        float shellVal = (0.02 + 0.58 * fresRim + 0.14 * wisps + 0.12 * circuitEtch + 0.34 * floorSeam) * sideWeight * env;
        vec3 keyDir = normalize(vec3(0.55, 0.72, 0.42));
        float spec = pow(max(dot(reflect(-keyDir, n), -rd), 0.0), 42.0) * (isFront ? 0.38 : 0.0);
        return vec3(shellVal * 0.72 + spec * env);
    }

    vec3 deepTeal = vec3(0.006, 0.16, 0.24);
    vec3 elecCyan = vec3(0.04, 0.78, 0.96);
    vec3 iceWhite = vec3(0.68, 0.96, 1.00);

    // Mostly transparent interior: only wisps, faint circuit etch, sharp Fresnel rim & floor seam!
    vec3 col = deepTeal * (0.08 + 0.45 * wisps);
    col += elecCyan * (wisps * 0.34 + circuitEtch * 0.28);
    col += mix(elecCyan, iceWhite, fresRim) * (fresRim * 1.45 + fresSoft * 0.16);
    col += mix(elecCyan, iceWhite, 0.58) * (floorSeam * 0.72 + floorSeamCore * 0.85);

    if (uLightMode == 2) {
        vec3 rakingDir = normalize(vec3(0.88, 0.20, 0.42));
        float sp = pow(max(dot(reflect(-rakingDir, n), -rd), 0.0), 32.0);
        col += vec3(1.0, 0.75, 0.40) * sp * 0.55 * (isFront ? 1.0 : 0.0);
    } else if (uLightMode == 3) {
        col += iceWhite * pow(fresRim, 1.5) * 0.95;
    }

    return col * sideWeight * env;
}

// --- Central EMP Energy Core Volumetric Glow (Pure VFX) ---
vec3 evalCentralCore(vec3 ro, vec3 rd, float tMax, EmpState st, bool isGray) {
    vec3 center = vec3(0.0, 0.66, 0.0);
    float tClosest = max(0.0, dot(center - ro, rd));
    if (tClosest > tMax + 0.15) return vec3(0.0);

    vec3 pClosest = ro + rd * tClosest;
    vec3 rel = pClosest - center;
    float d = length(rel);

    float ang = atan(rel.y, rel.x);
    float rays = 0.78 + 0.22 * sin(ang * 8.0 + st.tauPhase * 2.0) * cos(ang * 5.0 - st.tauPhase * 1.0);

    float coreSolid  = exp(-d * 9.5) * st.corePulse;
    float innerFlare = exp(-d * 3.4) * rays * st.corePulse;
    float outerHalo  = exp(-d * 1.25) * st.corePulse;
    float anam       = exp(-abs(rel.y) * 18.0) * exp(-length(rel.xz) * 1.85) * 0.28 * st.corePulse;

    if (isGray) {
        return vec3(coreSolid * 0.82 + innerFlare * 0.20);
    }

    return vec3(0.95, 0.99, 1.00) * coreSolid * 1.65
         + vec3(0.14, 0.80, 1.00) * innerFlare * 0.72
         + vec3(0.02, 0.30, 0.75) * outerHalo * 0.22
         + vec3(0.28, 0.84, 1.00) * anam;
}

// --- ACES Filmic Tonemap ---
vec3 acesTonemap(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;
    return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0);
}

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

    EmpState st = getEmpState(uTime);
    bool isGray = (uLightMode == 1);

    // --- Camera Setup (uCamMode: 0=hero framing, 1=~2.5x macro close-up) ---
    vec3 ro, ta;
    float focal;
    if (uCamMode == 1) {
        // ~2.5x macro close-up on dark beveled hex tiles, vivid amber-gold conduit,
        // circular metallic vertex hub, and crisp EMP dome intersection!
        ro = vec3(1.22, 1.06, 4.72);
        ta = vec3(0.14, 0.28, 2.50);
        focal = 1.50;
    } else {
        // Hero framing pulled back ~14% to showcase dark-metal/amber-gold hex floor
        // around the dome base and full top dome headroom like 07.png!
        ro = vec3(0.0, 4.12, 7.12);
        ta = vec3(0.0, 1.04, 0.0);
        focal = 1.18;
    }

    vec3 ww = normalize(ta - ro);
    vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0)));
    vec3 vv = cross(uu, ww);
    vec3 rd = normalize(uv.x * uu + uv.y * vv + focal * ww);

    // --- Analytic EMP Dome Intersections ---
    vec3 domeCenter = vec3(0.0, 0.0, 0.0);
    vec2 hitD1 = intersectSphere(ro, rd, domeCenter, st.r1);
    vec2 hitD2 = intersectSphere(ro, rd, domeCenter, st.r2);

    // Subtle physical plasma refraction through primary dome front shell
    vec3 rdScene = rd;
    if (hitD1.x > 0.0 && st.env1 > 0.01) {
        vec3 pD1 = ro + rd * hitD1.x;
        if (pD1.y > 0.0) {
            vec3 nD1 = normalize(pD1);
            float rip = sin(pD1.y * 14.0 - st.tauPhase * 2.0) * 0.5 + cos(atan(pD1.z, pD1.x) * 8.0 + st.tauPhase) * 0.5;
            float refrStrength = isGray ? 0.008 : 0.020 * st.env1;
            rdScene = normalize(rd - nD1 * refrStrength * (0.6 + 0.4 * rip));
        }
    }

    // --- Raymarch Solid Scene ---
    float t = 0.0;
    if (ro.y > 1.25 && rdScene.y < -0.02) {
        t = max(0.0, (1.25 - ro.y) / rdScene.y);
    }

    int hitMat = 0;
    float tMax = 24.0;
    bool hit = false;
    for (int i = 0; i < 42; i++) {
        vec3 p = ro + rdScene * t;
        int mId;
        float d = mapScene(p, st.tauPhase, mId);
        if (d < 0.0022 * (1.0 + t * 0.25)) {
            hit = true;
            hitMat = mId;
            break;
        }
        t += d;
        if (t > tMax || (p.y > 1.4 && rdScene.y > 0.0 && length(p.xz) > 1.2)) {
            break;
        }
    }

    if (!hit && rdScene.y < -0.005) {
        float tPlane = -ro.y / rdScene.y;
        if (tPlane > 0.0 && tPlane < tMax) {
            t = tPlane;
            hit = true;
            hitMat = 1;
        }
    }

    float tScene = hit ? t : tMax;

    // --- Deep Moody Dark Sci-Fi Arena Backdrop (lumMin ~8-15, %black = 0%) ---
    vec3 bgCol;
    {
        float elev = clamp(rd.y * 1.4 + 0.25, 0.0, 1.0);
        float azim = atan(rd.z, rd.x);
        float ribPat = 0.5 + 0.5 * cos(azim * 24.0);
        float archRib = smoothstep(0.68, 0.94, ribPat) * exp(-abs(rd.y - 0.10) * 6.0);
        float horizGlow = exp(-abs(rd.y + 0.02) * 8.5);

        if (isGray) {
            bgCol = vec3(mix(0.06, 0.12, elev) + archRib * 0.03);
        } else {
            // Deep obsidian-navy in linear space -> sRGB ~ (9, 13, 20)/255
            vec3 darkObsidian = vec3(0.0014, 0.0026, 0.0052);
            vec3 upperVoid    = vec3(0.0008, 0.0015, 0.0032);
            bgCol = mix(darkObsidian, upperVoid, elev);
            bgCol += vec3(0.004, 0.014, 0.024) * horizGlow;
            bgCol += vec3(0.004, 0.010, 0.018) * archRib;
            if (uLightMode == 3) {
                float backSpot = pow(max(dot(rd, normalize(vec3(0.0, 0.25, -0.97))), 0.0), 5.0);
                bgCol += vec3(0.025, 0.085, 0.135) * backSpot;
            }
        }
    }

    vec3 col = bgCol;

    // --- Shade Solid Floor & Central Containment Rings ---
    if (hit) {
        vec3 p = ro + rdScene * tScene;
        float normEps = mix(0.0020, 0.0050, clamp(tScene / 12.0, 0.0, 1.0));
        vec3 n = calcNormal(p, st.tauPhase, normEps);
        vec3 v = -rdScene;

        vec3 keyDir, keyCol, ambCol;
        if (uLightMode == 1) {
            keyDir = normalize(vec3(0.55, 0.72, 0.42));
            keyCol = vec3(0.70);
            ambCol = vec3(0.14);
        } else if (uLightMode == 2) {
            keyDir = normalize(vec3(0.88, 0.18, 0.44));
            keyCol = vec3(1.10, 0.86, 0.58);
            ambCol = vec3(0.008, 0.012, 0.018);
        } else if (uLightMode == 3) {
            keyDir = normalize(vec3(-0.18, 0.30, -0.94));
            keyCol = vec3(0.42, 0.76, 1.05);
            ambCol = vec3(0.006, 0.010, 0.018);
        } else {
            keyDir = normalize(vec3(0.35, 0.78, 0.52));
            keyCol = vec3(0.16, 0.24, 0.36);
            ambCol = vec3(0.007, 0.011, 0.018);
        }

        float rFloor = length(p.xz);

        if (hitMat == 2) {
            float ndl = max(dot(n, keyDir), 0.0);
            float fres = pow(1.0 - max(dot(n, v), 0.0), 3.0);
            if (isGray) {
                col = vec3(0.26 + 0.50 * ndl + 0.20 * fres);
            } else {
                col = vec3(0.02, 0.05, 0.09) * (0.3 + ndl) + vec3(0.18, 0.86, 1.0) * (0.55 + 0.95 * fres) * st.corePulse;
            }
        } else {
            float macroEdge, macroVert, microEdge;
            vec2 microId;
            floorHeight(p.xz, macroEdge, macroVert, microEdge, microId);

            float tileRand = hash12(microId);
            float brushed = vnoise2(p.xz * 22.0 + tileRand * 10.0);

            // Dark sleek gunmetal hex tiles (rich dark contrast like 07.png!)
            vec3 metalAlbedo = isGray
                ? vec3(0.22 + 0.08 * tileRand + 0.04 * brushed)
                : mix(vec3(0.014, 0.020, 0.030), vec3(0.030, 0.042, 0.058), tileRand * 0.7 + brushed * 0.3);

            // Darken micro-hex seams & raised dark-iron vertex hub collars
            float microSeam = smoothstep(0.052, 0.012, microEdge);
            float hubCollar = smoothstep(0.148, 0.120, macroVert) * smoothstep(0.058, 0.076, macroVert);
            metalAlbedo *= mix(1.0, 0.35, microSeam);
            metalAlbedo *= mix(1.0, 0.65, hubCollar);

            float rough = mix(0.22, 0.40, tileRand * 0.6 + brushed * 0.4);
            float specPow = mix(72.0, 22.0, rough);

            // Key light
            float ndl = max(dot(n, keyDir), 0.0);
            vec3 hKey = normalize(keyDir + v);
            float specKey = pow(max(dot(n, hKey), 0.0), specPow);

            // Central EMP core point light
            vec3 corePos = vec3(0.0, 0.72, 0.0);
            vec3 toCore = corePos - p;
            float distCore = length(toCore);
            vec3 lCore = toCore / max(distCore, 0.001);
            float attenCore = 1.0 / (1.0 + 0.24 * distCore * distCore);
            float ndlCore = max(dot(n, lCore), 0.0);
            vec3 hCore = normalize(lCore + v);
            float specCore = pow(max(dot(n, hCore), 0.0), specPow * 0.8);

            float fres = pow(1.0 - max(dot(n, v), 0.0), 4.0);

            vec3 surfCol = metalAlbedo * (ambCol + keyCol * ndl);
            surfCol += keyCol * specKey * (isGray ? 0.30 : 0.42);

            if (isGray) {
                surfCol += vec3(0.20) * ndlCore * attenCore + vec3(0.22) * specCore * attenCore;
                surfCol += vec3(0.08) * fres;
            } else {
                vec3 cyanLight = vec3(0.10, 0.78, 1.0) * st.corePulse;
                surfCol += metalAlbedo * cyanLight * ndlCore * attenCore * 1.9;
                surfCol += cyanLight * specCore * attenCore * (0.85 + 0.65 * fres);

                // Subtle cyan specular bounce on hex tiles right around the EMP wave front
                float wave1Prox = exp(-pow((rFloor - st.r1) * 1.8, 2.0)) * st.env1;
                float wave2Prox = exp(-pow((rFloor - st.r2) * 1.8, 2.0)) * st.env2;
                float waveGlow = wave1Prox + wave2Prox * 0.65;
                surfCol += vec3(0.03, 0.36, 0.54) * waveGlow * (0.14 + 0.45 * fres);
            }

            // --- Vivid Warm Amber-Gold Conduits & Electric-Cyan Circuit Pulses ---
            float wave1Pulse = exp(-pow((rFloor - st.r1) * 1.25, 2.0)) * st.env1;
            float wave2Pulse = exp(-pow((rFloor - st.r2) * 1.25, 2.0)) * st.env2;
            float empSurge = clamp(wave1Pulse + wave2Pulse * 0.75, 0.0, 1.25);

            // Crisp macro-hex golden-amber conduit channels + thin twin accent strips
            float conduitHot  = smoothstep(0.022, 0.006, macroEdge);
            float conduitBody = smoothstep(0.038, 0.018, macroEdge);
            float conduitRim  = smoothstep(0.058, 0.046, macroEdge) * smoothstep(0.038, 0.045, macroEdge);

            // Vertex node hub golden emitter lenses
            float hubHot  = smoothstep(0.042, 0.018, macroVert);
            float hubLens = smoothstep(0.062, 0.036, macroVert);
            float hubGlow = smoothstep(0.088, 0.062, macroVert) * (1.0 - hubLens);

            float arenaMask = smoothstep(0.88, 1.28, rFloor) * smoothstep(6.15, 5.55, rFloor);
            float outerGold = smoothstep(0.078, 0.030, abs(rFloor - 5.65));

            float goldBody = (conduitBody + hubLens * 1.15) * arenaMask + outerGold;
            float goldHot  = (conduitHot  + hubHot  * 1.15) * arenaMask + smoothstep(0.035, 0.010, abs(rFloor - 5.65));
            float goldEdge = (conduitRim * 0.55 + hubGlow * 0.45) * arenaMask;

            float goldInt = 0.85 + 0.65 * empSurge + 0.12 * sin(rFloor * 2.2 - st.tauPhase * 2.0);

            // Micro-hex seams ignite in crisp electric cyan when EMP wave passes
            float insideDome1 = smoothstep(st.r1 + 0.25, st.r1 - 0.65, rFloor) * st.env1;
            float cyanCircuit = microSeam * arenaMask * (0.06 + 0.92 * empSurge + 0.22 * insideDome1);

            // Central concentric glowing cyan cyber-rings around the EMP core
            float ang = atan(p.z, p.x);
            float ringFreq = sin(rFloor * 14.5 - st.tauPhase * 2.0);
            float concRing = smoothstep(0.78, 0.96, ringFreq) * smoothstep(2.45, 0.68, rFloor) * smoothstep(0.28, 0.50, rFloor);
            float dashMask = 0.62 + 0.38 * sin(ang * 12.0 + floor(rFloor * 2.3) * 2.1 + st.tauPhase * 1.0);
            float centerCyan = concRing * dashMask * st.corePulse;

            // Crisp floor dome intersection contact ring
            float domeContact1 = exp(-pow((rFloor - st.r1) * 9.5, 2.0)) * st.env1;
            float domeContact2 = exp(-pow((rFloor - st.r2) * 9.5, 2.0)) * st.env2;
            float domeContact = domeContact1 + domeContact2 * 0.55;

            if (isGray) {
                surfCol += vec3(0.18) * goldBody + vec3(0.08) * cyanCircuit + vec3(0.14) * centerCyan + vec3(0.22) * domeContact;
            } else {
                // Deep saturated amber-gold palette so conduits stay rich warm gold under ACES!
                vec3 amberDeep = vec3(1.00, 0.24, 0.01);
                vec3 amberMid  = vec3(1.00, 0.52, 0.05);
                vec3 amberHot  = vec3(1.00, 0.80, 0.24);
                vec3 cyanGlow  = vec3(0.06, 0.82, 1.00);
                vec3 cyanWhite = vec3(0.65, 0.96, 1.00);

                surfCol += amberMid * goldBody * goldInt * 1.15;
                surfCol += amberHot * goldHot  * goldInt * 0.85;
                surfCol += amberDeep * goldEdge * goldInt * 0.55;

                // Subtle warm amber spill onto the metallic bevels adjacent to conduits
                float amberSpill = (smoothstep(0.11, 0.035, macroEdge) + smoothstep(0.16, 0.065, macroVert)) * arenaMask;
                surfCol += amberDeep * amberSpill * 0.055 * goldInt;

                surfCol += cyanGlow * cyanCircuit * 0.65;
                surfCol += mix(cyanGlow, cyanWhite, 0.40) * centerCyan * 0.95;
                surfCol += mix(cyanGlow, cyanWhite, 0.50) * domeContact * 1.05;
            }

            // Light atmospheric distance fog preserving dark punchy foreground tiles
            float fog = 1.0 - exp(-tScene * tScene * 0.0022);
            col = mix(surfCol, bgCol, clamp(fog, 0.0, 0.82));
        }
    }

    // --- Composite Back Shells of EMP Domes ---
    if (hitD2.y > 0.0 && hitD2.y < tScene) {
        col += shadeDomeHit(ro + rd * hitD2.y, rd, st.r2, st.env2, st.tauPhase, false, isGray);
    }
    if (hitD1.y > 0.0 && hitD1.y < tScene) {
        col += shadeDomeHit(ro + rd * hitD1.y, rd, st.r1, st.env1, st.tauPhase, false, isGray);
    }

    // --- Composite Central EMP Energy Core ---
    col += evalCentralCore(ro, rd, tScene, st, isGray);

    // --- Composite Front Shells of EMP Domes ---
    if (hitD2.x > 0.0 && hitD2.x < tScene) {
        col += shadeDomeHit(ro + rd * hitD2.x, rd, st.r2, st.env2, st.tauPhase, true, isGray);
    }
    if (hitD1.x > 0.0 && hitD1.x < tScene) {
        col += shadeDomeHit(ro + rd * hitD1.x, rd, st.r1, st.env1, st.tauPhase, true, isGray);
    }

    // --- Composite 3D Jagged Branching Cobalt-White Lightning Arcs ---
    col += evalLightning(ro, rd, tScene, st, isGray);

    // --- Composite 3D Radial Plasma & Ember Sparks ---
    col += evalSparks(ro, rd, tScene, st, isGray);

    // --- Subtle Cinematic Vignette & Exposure ---
    float vig = 1.0 - dot(uv * vec2(0.42, 0.52), uv * vec2(0.42, 0.52));
    col *= clamp(vig, 0.72, 1.0);

    float expScale = isGray ? 1.00 : (uCamMode == 1 ? 0.82 : 0.94);
    col = acesTonemap(col * expScale);

    // Guarantee lumMin ~8-15 and %black = 0% while keeping deep moody blacks
    if (isGray) {
        float g = clamp(dot(col, vec3(0.299, 0.587, 0.114)), 0.015, 0.96);
        g = pow(g, 1.0 / 2.2);
        col = vec3(g);
    } else {
        col = max(col, vec3(0.0008, 0.0014, 0.0026));
        col = pow(col, vec3(1.0 / 2.2));
    }

    fragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}
