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

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

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

vec2 hash22(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.xx + p3.yz) * p3.zy);
}

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);
    return mix(
        mix(hash12(i + vec2(0.0, 0.0)), hash12(i + vec2(1.0, 0.0)), u.x),
        mix(hash12(i + vec2(0.0, 1.0)), hash12(i + vec2(1.0, 1.0)), 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);
}

float fbm3(vec3 p) {
    float v = 0.0;
    float a = 0.5;
    for (int i = 0; i < 4; i++) {
        v += a * noise3(p);
        p = p * 2.03 + vec3(17.1, 31.7, 11.3);
        a *= 0.5;
    }
    return v;
}

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

float smax(float a, float b, float k) {
    return -smin(-a, -b, k);
}

// ============================================================================
// Seamless Cylindrical Alligator-Skin Voronoi Crack Field
// Returns: x = exact distance to nearest cell border (0 at crack center),
//          y = cell ID hash [0, 1],
//          z = signed block tilt/height offset [-1, 1]
// ============================================================================
vec3 alligatorVoronoi(vec2 p, float periodY) {
    vec2 n = floor(p);
    vec2 f = fract(p);

    vec2 mg, mr;
    float md = 8.0;
    float cellId = 0.0;

    for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
            vec2 g = vec2(float(i), float(j));
            vec2 cell = n + g;
            cell.y = mod(cell.y, periodY);
            // Controlled jitter keeps blocks quasi-rectangular like real charred oak
            vec2 o = 0.16 + 0.68 * hash22(cell);
            vec2 r = g + o - f;
            float d = dot(r, r);
            if (d < md) {
                md = d;
                mr = r;
                mg = g;
                cellId = hash12(cell + 19.37);
            }
        }
    }

    // Second pass: exact distance to cell border
    float edgeDist = 8.0;
    for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
            vec2 g = mg + vec2(float(i), float(j));
            vec2 cell = n + g;
            cell.y = mod(cell.y, periodY);
            vec2 o = 0.16 + 0.68 * hash22(cell);
            vec2 r = g + o - f;
            vec2 diff = r - mr;
            if (dot(diff, diff) > 0.00001) {
                float d = dot(0.5 * (mr + r), normalize(diff));
                edgeDist = min(edgeDist, d);
            }
        }
    }

    float tilt = (hash11(cellId * 71.3 + 5.1) - 0.5) * 2.0;
    return vec3(edgeDist, cellId, tilt);
}

// ============================================================================
// Physically Accurate Planck Blackbody Radiation
// Evaluates Planck's spectral radiance B(lambda, T) at sRGB primaries
// (R=650nm, G=535nm, B=460nm) and maps to scene-linear RGB radiance.
// ============================================================================
vec3 planckBlackbody(float tempK) {
    // Draper point (~798 K): below ~720 K thermal emission is negligible
    float t = clamp(tempK, 650.0, 2400.0);
    // hc / k_B = 1.438776877e-2 m*K -> in micrometers*K = 14387.77
    const vec3 lambdaUm = vec3(0.645, 0.538, 0.460);
    const vec3 c2 = vec3(14387.77);
    vec3 l5 = lambdaUm * lambdaUm * lambdaUm * lambdaUm * lambdaUm;

    // Raw Planck spectral radiance (normalized scale)
    vec3 denom = exp(c2 / (lambdaUm * t)) - 1.0;
    vec3 rad = (1.0 / l5) / max(denom, vec3(1e-6));

    // Reference normalization at 1750 K so peak ember core sits cleanly in HDR range
    vec3 denomRef = exp(c2 / (lambdaUm * 1750.0)) - 1.0;
    vec3 radRef = (1.0 / l5) / denomRef;
    float refScale = max(radRef.r, 1e-6);

    vec3 col = rad / refScale;

    // Smooth physical threshold below Draper point
    float draper = smoothstep(720.0, 860.0, tempK);
    // Subtle luminance shaping so deep cherry-red remains readable while 1850K core glows bright
    float lum = dot(col, vec3(0.2126, 0.7152, 0.0722));
    float compress = 1.0 / (1.0 + 0.14 * lum);
    return col * draper * 6.8 * compress;
}

// ============================================================================
// Log Local Coordinate Transform & Crack Evaluation
// ============================================================================
struct CharData {
    float fissureDepth;   // 0 = outer char face, 1 = deepest glowing fissure core
    float crackMask;      // 1 in primary/secondary fissures
    float endMask;        // 1 on cut log ends
    float cellId;         // per-char-block random ID
    float ashMask;        // 1 on outer flaky ash tips/ridges
    float grain;          // wood grain striation
    float deepSplit;      // 1 inside the main axial heartwood split
    vec3 localP;          // point in log-local space
};

vec3 toLogSpace(vec3 p) {
    // Center log resting solidly on y = 0 bench, angled slightly for 3/4 silhouette
    vec3 q = p - vec3(0.0, 0.395, 0.02);
    q.xz = rot2(-0.24) * q.xz;
    return q;
}

// Evaluates both the charred oak log SDF and detailed surface/fissure fields
float evalCharredLog(vec3 p, out CharData cd) {
    vec3 q = toLogSpace(p);
    cd.localP = q;

    // Slight natural oak trunk bow & twist
    float bow = 0.028 * sin(q.x * 1.9 + 0.4);
    q.y -= bow;
    q.z += 0.022 * cos(q.x * 1.5 - 0.3);

    float halfLen = 0.90;
    // Slightly irregular axe/saw-cut end faces
    float endWarp = 0.032 * sin(atan(q.z, q.y) * 3.0 + sign(q.x) * 1.2)
                  + 0.018 * noise3(q * 3.5);
    float axDist = abs(q.x) - (halfLen + endWarp);

    // Cylindrical coordinates around log axis
    float ang = atan(q.z, q.y);
    float rad = length(q.yz);

    // Organic oak cross-section: slight ovalness + 4 bark lobes + subtle taper
    float taper = 1.0 + 0.045 * q.x;
    float lobes = 0.026 * cos(ang * 3.0 + q.x * 0.9)
                + 0.018 * sin(ang * 5.0 - q.x * 1.4)
                + 0.012 * cos(ang * 7.0 + 0.8);
    float baseRadius = (0.435 + lobes) * taper;
    // Slight oval compression vertically (resting log settles slightly)
    float ovalRad = length(vec2(q.y * 1.04, q.z * 0.96));
    float dCyl = ovalRad - baseRadius;

    // Base rounded cylinder with organic beveled cut ends
    vec2 w = vec2(dCyl, axDist);
    float dBase = min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - 0.035;

    // Flatten the bottom slightly so the charred log rests flush on the studio bench
    float flatBottom = -(p.y + 0.002);
    dBase = smax(dBase, flatBottom, 0.035);

    // Deep axial heartwood split wedge along the upper-front flank (facing camera)
    // Gives a dramatic glowing deep ember canyon running through the log
    float splitAng = ang - (0.72 + 0.14 * sin(q.x * 2.1 + 0.5));
    splitAng = atan(sin(splitAng), cos(splitAng));
    float splitProfile = abs(splitAng) - (0.095 + 0.035 * sin(q.x * 3.7));
    float splitMaskX = smoothstep(0.92, 0.55, abs(q.x));
    float splitCanyon = max(splitProfile * 0.42, -(rad - 0.27));
    float deepSplitCarve = (1.0 - smoothstep(0.0, 0.075, abs(splitAng))) * splitMaskX;

    // Quick bounding bailout for far-away rays (keeps raymarch fast and Lipschitz-clean)
    if (dBase > 0.22) {
        cd.fissureDepth = 0.0;
        cd.crackMask = 0.0;
        cd.endMask = 0.0;
        cd.cellId = 0.5;
        cd.ashMask = 0.0;
        cd.grain = 0.5;
        cd.deepSplit = 0.0;
        return dBase;
    }

    // End-cap blend mask
    float endMask = smoothstep(-0.08, 0.02, axDist - dCyl);

    // ------------------------------------------------------------------------
    // Alligator-Skin Cubic Char Blocks (Cylindrical Surface)
    // ------------------------------------------------------------------------
    // Domain warp makes the char grid organic rather than mechanical
    float warpA = (noise3(q * 3.8 + vec3(2.1, 0.0, 4.3)) - 0.5) * 0.36;
    float warpX = (noise3(q * 3.4 + vec3(9.4, 5.2, 1.7)) - 0.5) * 0.24;

    // Period around circumference = 16.0 blocks, axial density ~ 5.8 blocks/unit
    const float circPeriod = 16.0;
    vec2 uvPrimary = vec2(q.x * 5.8 + warpX, (ang / TAU + 0.5) * circPeriod + warpA);
    vec3 v1 = alligatorVoronoi(uvPrimary, circPeriod);

    // Secondary finer subdivision cracks inside larger char plates
    const float circPeriod2 = 32.0;
    vec2 uvSec = vec2(q.x * 12.2 + warpX * 1.4, (ang / TAU + 0.5) * circPeriod2 + warpA * 1.3);
    vec3 v2 = alligatorVoronoi(uvSec, circPeriod2);

    // Primary fissure profile: sharp-walled deep V/U groove between cubic char plates
    float crack1 = 1.0 - smoothstep(0.025, 0.145, v1.x);
    float crack1Sharp = 1.0 - smoothstep(0.012, 0.068, v1.x);
    // Secondary hairline fissures
    float crack2 = (1.0 - smoothstep(0.018, 0.085, v2.x)) * 0.55;

    // ------------------------------------------------------------------------
    // Cut-End Growth Rings & Radial Checking Cracks
    // ------------------------------------------------------------------------
    float ringWarp = noise3(q * 6.0) * 0.035;
    float rings = sin((rad + ringWarp) * 68.0) * 0.5 + 0.5;
    float ringCrack = smoothstep(0.78, 0.98, rings) * smoothstep(0.06, 0.35, rad);
    float radAngle = ang + 0.25 * noise3(q * 4.5);
    float radialSpokes = pow(abs(sin(radAngle * 7.0 + 0.4 * sin(rad * 12.0))), 18.0);
    float radialCheck = smoothstep(0.35, 0.92, radialSpokes) * smoothstep(0.04, 0.38, rad);
    float endCrack = clamp(radialCheck * 0.85 + ringCrack * 0.40, 0.0, 1.0);

    // Blend cylindrical alligator cracks with end-grain cracks
    float combinedCrack = mix(max(crack1, crack2), endCrack, endMask);
    float deepCrack = mix(crack1Sharp, radialCheck, endMask);

    // Per-block stepped elevation & slight cubic facet bevel
    float blockHeight = (v1.z * 0.011) * (1.0 - crack1) * (1.0 - endMask);

    // Fine axial charcoal wood-grain striation + blister micro-roughness
    float grain = noise3(vec3(q.x * 14.0, ang * 26.0, rad * 18.0));
    float microChar = (noise3(q * 34.0) - 0.5) * 0.0055
                    + (grain - 0.5) * 0.0045;

    // Carve fissures & main axial split into the base log
    float fissureCarve = combinedCrack * 0.048 + deepCrack * 0.026;
    float splitDepth = deepSplitCarve * 0.088;

    float d = dBase + fissureCarve + splitDepth - blockHeight + microChar;
    // Softly reinforce the split canyon inner walls
    d = smax(d, -splitCanyon - 0.06, 0.025);

    // Re-enforce bench floor contact cleanly
    d = smax(d, -(p.y + 0.001), 0.012);

    // Populate CharData for shading & blackbody temperature
    cd.fissureDepth = clamp(combinedCrack * 0.65 + deepCrack * 0.45 + deepSplitCarve * 0.95, 0.0, 1.0);
    cd.crackMask = clamp(combinedCrack + deepSplitCarve, 0.0, 1.0);
    cd.endMask = endMask;
    cd.cellId = v1.y;
    cd.grain = grain;
    cd.deepSplit = deepSplitCarve;

    // Pale flaky ash settles on outer block edges, upward-facing ridges, and raised corners
    float outerEdge = smoothstep(0.08, 0.24, v1.x) * (1.0 - smoothstep(0.24, 0.42, v1.x));
    float topBias = smoothstep(0.22, 0.72, q.y / max(baseRadius, 0.1));
    float ashNoise = fbm3(q * 11.5 + vec3(3.1, 7.4, 2.2));
    float flake = smoothstep(0.54, 0.80, ashNoise + outerEdge * 0.28 + topBias * 0.22);
    cd.ashMask = flake * (1.0 - smoothstep(0.05, 0.22, cd.fissureDepth)) * smoothstep(0.05, 0.22, p.y);

    return d;
}

float mapHero(vec3 p) {
    CharData dummy;
    return evalCharredLog(p, dummy);
}

float mapScene(vec3 p) {
    return min(mapHero(p), p.y);
}

// ============================================================================
// Normals, Soft Shadow & Ambient Occlusion (Zero-Bug Contract)
// ============================================================================
// Rule (1): Unit-weight tetrahedral normals
vec3 calcNormal(vec3 p) {
    const float e = 0.0016;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * mapScene(p + k.xyy * e) +
        k.yyx * mapScene(p + k.yyx * e) +
        k.yxy * mapScene(p + k.yxy * e) +
        k.xxx * mapScene(p + k.xxx * e)
    );
}

// Rule (3): Clean res = min(res, k*h/t) hero-only soft shadow (no ph)
float softShadowHero(vec3 p, vec3 N, vec3 rd, float k) {
    vec3 ro = p + N * 0.014;
    float res = 1.0;
    float t = 0.025;
    for (int i = 0; i < 44; i++) {
        float h = mapHero(ro + rd * t);
        if (h < 0.0008) return 0.0;
        res = min(res, k * h / t);
        t += max(h, 0.015);
        if (t > 4.5) break;
    }
    return clamp(res, 0.0, 1.0);
}

float calcAO(vec3 p, vec3 N) {
    float occ = 0.0;
    float sca = 1.0;
    for (int i = 1; i <= 5; i++) {
        float h = 0.018 + 0.042 * float(i);
        float d = mapScene(p + N * h);
        occ += (h - d) * sca;
        sca *= 0.68;
    }
    return clamp(1.0 - 2.3 * occ, 0.06, 1.0);
}

// ============================================================================
// Studio Sky with Softboxes & Negative-Fill Flags
// ============================================================================
vec3 studioEnv(vec3 rd, int lightMode) {
    float y = rd.y;
    vec3 baseCol;

    if (lightMode == 1) {
        // Pure neutral grayscale inspection studio
        baseCol = mix(vec3(0.06), vec3(0.16), smoothstep(-0.2, 0.85, y));
    } else if (lightMode == 2) {
        // Grazing: darker moody studio so raking light sculpts the char relief
        baseCol = mix(vec3(0.025, 0.027, 0.032), vec3(0.065, 0.070, 0.082), smoothstep(-0.2, 0.85, y));
    } else if (lightMode == 3) {
        // Backlit: cool dark backdrop with bright rear softbox halo
        baseCol = mix(vec3(0.022, 0.026, 0.034), vec3(0.075, 0.085, 0.105), smoothstep(-0.2, 0.85, y));
    } else {
        // Hero: museum dark-slate studio cyclorama
        baseCol = mix(vec3(0.028, 0.030, 0.035), vec3(0.078, 0.082, 0.094), smoothstep(-0.2, 0.85, y));
    }

    // Overhead key softbox
    vec3 keyDir = (lightMode == 2) ? normalize(vec3(0.88, 0.24, 0.38))
                : (lightMode == 3) ? normalize(vec3(-0.18, 0.45, -0.87))
                                   : normalize(vec3(0.55, 0.72, 0.42));
    float keyBox = smoothstep(0.82, 0.96, dot(rd, keyDir));

    // Cool fill softbox (left)
    vec3 fillDir = normalize(vec3(-0.78, 0.42, 0.46));
    float fillBox = smoothstep(0.76, 0.94, dot(rd, fillDir));

    // Crisp rim softbox (back-top)
    vec3 rimDir = normalize(vec3(-0.12, 0.56, -0.82));
    float rimBox = smoothstep(0.84, 0.97, dot(rd, rimDir));

    // Negative-fill flags (dark velvet cards on sides to carve crisp charcoal reflections)
    float negFlagL = smoothstep(0.70, 0.90, dot(rd, normalize(vec3(-0.92, 0.05, -0.35))));
    float negFlagR = smoothstep(0.72, 0.92, dot(rd, normalize(vec3(0.92, 0.04, -0.38))));

    vec3 keyTint  = (lightMode == 1) ? vec3(1.0) : vec3(1.00, 0.96, 0.91);
    vec3 fillTint = (lightMode == 1) ? vec3(0.85) : vec3(0.76, 0.84, 0.96);
    vec3 rimTint  = (lightMode == 1) ? vec3(0.95) : vec3(0.88, 0.93, 1.00);

    float keyGain  = (lightMode == 1) ? 1.55 : (lightMode == 3 ? 2.40 : 1.35);
    float fillGain = (lightMode == 1) ? 0.75 : 0.48;
    float rimGain  = (lightMode == 3) ? 2.60 : 0.85;

    vec3 env = baseCol;
    env += keyTint * keyBox * keyGain;
    env += fillTint * fillBox * fillGain;
    env += rimTint * rimBox * rimGain;

    // Apply negative-fill absorption
    env *= (1.0 - 0.65 * negFlagL) * (1.0 - 0.60 * negFlagR);
    return env;
}

// ============================================================================
// GGX Microfacet Specular BRDF
// ============================================================================
float D_GGX(float NoH, float rough) {
    float a = rough * rough;
    float a2 = a * a;
    float d = NoH * NoH * (a2 - 1.0) + 1.0;
    return a2 / (PI * d * d + 1e-6);
}

float G_Smith(float NoV, float NoL, float rough) {
    float k = (rough + 1.0);
    k = (k * k) * 0.125;
    float gv = NoV / (NoV * (1.0 - k) + k);
    float gl = NoL / (NoL * (1.0 - k) + k);
    return gv * gl;
}

vec3 F_Schlick(float cosT, vec3 F0) {
    return F0 + (1.0 - F0) * pow(clamp(1.0 - cosT, 0.0, 1.0), 5.0);
}

vec3 shadeLight(vec3 N, vec3 V, vec3 L, vec3 lightCol, vec3 albedo, float rough, vec3 F0) {
    float NoL = max(dot(N, L), 0.0);
    if (NoL <= 0.0) return vec3(0.0);
    float NoV = max(dot(N, V), 0.001);
    vec3 H = normalize(V + L);
    float NoH = max(dot(N, H), 0.0);
    float VoH = max(dot(V, H), 0.0);

    float D = D_GGX(NoH, rough);
    float G = G_Smith(NoV, NoL, rough);
    vec3  F = F_Schlick(VoH, F0);

    vec3 spec = (D * G * F) / max(4.0 * NoV * NoL, 0.001);
    vec3 diff = (vec3(1.0) - F) * albedo / PI;
    return (diff + spec) * lightCol * NoL;
}

// ============================================================================
// Blackbody Temperature Field Across the Charred Oak Log
// ============================================================================
float evalLogTemperature(vec3 p, CharData cd, float openVal) {
    vec3 q = cd.localP;

    // Gentle convection draft waves drifting along the log
    float draft1 = sin(q.x * 2.6 - uTime * 1.15 + q.z * 2.2) * 0.5 + 0.5;
    float draft2 = noise3(q * 2.8 - vec3(uTime * 0.35, uTime * 0.22, 0.0));
    float breath = 0.5 + 0.5 * sin(uTime * 0.85 + q.x * 1.4);
    float draftBoost = (draft1 * 0.55 + draft2 * 0.45) * 140.0 + breath * 55.0;

    // Core heat is strongest along the central body and inner fissures, cooler near far ends
    float axialProfile = 1.0 - 0.28 * smoothstep(0.42, 0.95, abs(q.x));

    // Per-block thermal variation so neighboring fissures have realistic hot/cool pockets
    float pocket = noise3(q * 3.1 + vec3(4.2, 1.8, 6.5));

    // uOpen (0..1) fans or cools the blackbody temperature across the log
    // 0.0 -> cooler smoldering cherry-red; 0.5 -> balanced yellow-white/orange/red; 1.0 -> fanned hot
    float fanShift = mix(-270.0, 290.0, clamp(openVal, 0.0, 1.0));

    // Base temperature driven by fissure depth:
    // outer char surface ~ 560 K (matte black)
    // fissure rim ~ 920 K (deep cherry-red)
    // mid fissure wall ~ 1320 K (bright orange)
    // deepest fissure / axial split core ~ 1780 K (incandescent yellow-white)
    float depthCurve = pow(clamp(cd.fissureDepth, 0.0, 1.0), 0.78);
    float tempK = 540.0 + depthCurve * 1180.0 * axialProfile
                + cd.deepSplit * 210.0
                + (pocket - 0.5) * 240.0 * smoothstep(0.08, 0.55, cd.fissureDepth)
                + draftBoost * smoothstep(0.12, 0.65, cd.fissureDepth)
                + fanShift * smoothstep(0.06, 0.45, cd.fissureDepth);

    // Ash-covered tips cool faster
    tempK -= cd.ashMask * 240.0;
    return clamp(tempK, 450.0, 2250.0);
}

// ============================================================================
// Warm Firelight Cast onto the Dark Studio Bench (Multi-Tap Ember Line Light)
// ============================================================================
vec3 benchEmberFirelight(vec3 p, vec3 N, vec3 V, vec3 albedo, float rough, vec3 F0, float openVal) {
    vec3 total = vec3(0.0);
    float fanPower = mix(0.32, 1.75, clamp(openVal, 0.0, 1.0));
    float baseTemp = mix(1050.0, 1580.0, clamp(openVal, 0.0, 1.0));

    // 5 glowing ember emission zones distributed along the charred log's lower/front flank
    for (int i = 0; i < 5; i++) {
        float fi = (float(i) / 4.0) * 2.0 - 1.0; // -1 .. +1
        vec3 localEmit = vec3(fi * 0.72, 0.20, 0.30);
        // Inverse of toLogSpace rotation (+0.24)
        vec3 worldEmit = localEmit;
        worldEmit.xz = rot2(0.24) * worldEmit.xz;
        worldEmit += vec3(0.0, 0.0, 0.02);

        vec3 toL = worldEmit - p;
        float dist2 = dot(toL, toL) + 0.10;
        float dist = sqrt(dist2);
        vec3 L = toL / dist;

        // Subtle flicker per zone
        float pulse = 0.88 + 0.12 * sin(uTime * 1.4 + fi * 3.1);
        float zoneTemp = baseTemp + 130.0 * sin(fi * 2.2 + 0.7) + 60.0 * sin(uTime * 1.1 + fi * 4.0);
        vec3 emitCol = planckBlackbody(zoneTemp) * 0.24 * fanPower * pulse;

        // Soft attenuation + contact-gap dimming very close to underneath the log
        float atten = 1.0 / (dist2 * (1.0 + 0.55 * dist));
        // Gentle hero shadow occlusion for firelight so glow wraps realistically around the log base
        float sh = clamp(mapHero(p + L * 0.14) * 5.5 + 0.32, 0.18, 1.0);
        total += shadeLight(N, V, L, emitCol * atten * sh, albedo, rough, F0);
    }
    return total;
}

// ============================================================================
// ACES Filmic Tone Mapping (Calibrated for Hero Lum 10..248, 0% Clipped)
// ============================================================================
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);
}

// ============================================================================
// Main Raymarch & Shading
// ============================================================================
void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution) / min(uResolution.x, uResolution.y);

    // Camera setup: uCamMode 0 = Hero 3/4 establishing view, 1 = ~2.5x Macro on glowing alligator cracks
    vec3 ro, ta;
    float fl;
    if (uCamMode == 1) {
        // ~2.5x macro close-up onto the fractured alligator-skin char blocks & deep glowing fissures
        ro = vec3(0.06, 0.72, 1.16);
        ta = vec3(-0.02, 0.44, 0.14);
        fl = 2.65;
    } else {
        // Hero establishing 3/4 view of full charred oak log section, cut ends, and bench/ash apron
        ro = vec3(0.48, 1.16, 3.18);
        ta = vec3(0.0, 0.34, 0.0);
        fl = 2.0;
    }

    vec3 cw = normalize(ta - ro);
    vec3 cu = normalize(cross(cw, vec3(0.0, 1.0, 0.0)));
    vec3 cv = cross(cu, cw);
    vec3 rd = normalize(uv.x * cu + uv.y * cv + fl * cw);

    // Raymarch scene
    float t = 0.0;
    bool hit = false;
    float maxT = 14.0;
    for (int i = 0; i < 160; i++) {
        vec3 p = ro + rd * t;
        float dHero = mapHero(p);
        float dScene = min(dHero, p.y);
        if (dScene < 0.00075) {
            hit = true;
            break;
        }
        // Conservative step near the displaced alligator-skin char surface
        float stepScale = (dHero < 0.25) ? 0.42 : 0.92;
        t += dScene * stepScale;
        if (t > maxT) break;
    }

    vec3 col = studioEnv(rd, uLightMode);

    if (hit) {
        vec3 p = ro + rd * t;
        CharData cd;
        float dHero = evalCharredLog(p, cd);
        // Rule (2): Exact bench classification
        bool isBench = (p.y <= dHero + 0.001);

        vec3 N = isBench ? vec3(0.0, 1.0, 0.0) : calcNormal(p);
        vec3 V = -rd;
        float ao = calcAO(p, N);

        // Configure studio lights per uLightMode
        vec3 keyDir, fillDir, rimDir;
        vec3 keyCol, fillCol, rimCol;
        float emitScale = (uLightMode == 1) ? 0.0 : 1.0;

        if (uLightMode == 1) {
            // Pure neutral grayscale studio — emission suppressed so charred log geometry reads cleanly
            keyDir  = normalize(vec3(0.55, 0.72, 0.45));
            fillDir = normalize(vec3(-0.75, 0.45, 0.50));
            rimDir  = normalize(vec3(-0.15, 0.55, -0.82));
            keyCol  = vec3(2.55);
            fillCol = vec3(1.10);
            rimCol  = vec3(1.45);
        } else if (uLightMode == 2) {
            // Grazing raking light skimming across the alligator-skin char blocks
            keyDir  = normalize(vec3(0.90, 0.22, 0.36));
            fillDir = normalize(vec3(-0.70, 0.35, 0.62));
            rimDir  = normalize(vec3(-0.20, 0.48, -0.85));
            keyCol  = vec3(2.85, 2.68, 2.45);
            fillCol = vec3(0.42, 0.48, 0.58);
            rimCol  = vec3(0.95, 1.00, 1.12);
        } else if (uLightMode == 3) {
            // Backlit silhouette sculpting
            keyDir  = normalize(vec3(-0.15, 0.42, -0.89));
            fillDir = normalize(vec3(0.70, 0.45, 0.55));
            rimDir  = normalize(vec3(0.45, 0.52, -0.72));
            keyCol  = vec3(3.20, 3.35, 3.65);
            fillCol = vec3(0.46, 0.50, 0.58);
            rimCol  = vec3(1.90, 2.00, 2.20);
        } else {
            // Hero museum studio lighting
            keyDir  = normalize(vec3(0.56, 0.74, 0.40));
            fillDir = normalize(vec3(-0.76, 0.42, 0.48));
            rimDir  = normalize(vec3(-0.14, 0.56, -0.82));
            keyCol  = vec3(2.15, 2.06, 1.96);
            fillCol = vec3(0.58, 0.66, 0.78);
            rimCol  = vec3(1.35, 1.42, 1.56);
        }

        float shKey = softShadowHero(p, N, keyDir, 10.0);
        float shRim = softShadowHero(p, N, rimDir, 8.0);

        if (isBench) {
            // Dark brushed basalt/slate studio bench
            float benchGrain = fbm3(vec3(p.x * 6.0, 0.0, p.z * 6.0));
            float microSpeck = noise2(p.xz * 42.0);
            vec3 benchAlbedo = (uLightMode == 1)
                ? vec3(0.11 + 0.025 * benchGrain)
                : vec3(0.052, 0.054, 0.060) * (0.85 + 0.30 * benchGrain);
            float benchRough = clamp(0.36 + 0.14 * benchGrain + 0.04 * microSpeck, 0.25, 0.62);
            vec3 benchF0 = vec3(0.042);

            // Subtle ash dust scattered around the base of the charred log
            vec3 qBench = toLogSpace(p);
            float distToLog = length(vec2(max(abs(qBench.x) - 0.86, 0.0), max(abs(qBench.z) - 0.36, 0.0)));
            float ashDust = smoothstep(0.45, 0.02, distToLog) * smoothstep(0.48, 0.78, fbm3(vec3(p.xz * 12.0, 1.7)));
            vec3 ashCol = (uLightMode == 1) ? vec3(0.34) : vec3(0.28, 0.27, 0.26);
            benchAlbedo = mix(benchAlbedo, ashCol, ashDust * 0.48);
            benchRough = mix(benchRough, 0.86, ashDust * 0.55);

            vec3 lit = vec3(0.0);
            lit += shadeLight(N, V, keyDir,  keyCol  * shKey, benchAlbedo, benchRough, benchF0);
            lit += shadeLight(N, V, fillDir, fillCol * (0.45 + 0.55 * ao), benchAlbedo, benchRough, benchF0);
            lit += shadeLight(N, V, rimDir,  rimCol  * shRim, benchAlbedo, benchRough, benchF0);

            // Studio environment IBL reflection & diffuse fill
            vec3 R = reflect(-V, N);
            vec3 envSpec = studioEnv(R, uLightMode);
            vec3 envDiff = studioEnv(N, uLightMode);
            vec3 Fv = F_Schlick(max(dot(N, V), 0.0), benchF0);
            lit += benchAlbedo * envDiff * 0.55 * ao;
            lit += envSpec * Fv * (1.0 - benchRough * 0.72) * (0.35 + 0.65 * shKey) * ao;

            // Warm firelight cast from glowing ember fissures onto the studio bench
            if (emitScale > 0.0) {
                lit += benchEmberFirelight(p, N, V, benchAlbedo, benchRough, benchF0, uOpen) * emitScale;
            }

            // Distance fade into studio cyclorama horizon
            float fog = smoothstep(3.2, 10.5, length(p.xz));
            col = mix(lit, studioEnv(rd, uLightMode), fog);
        } else {
            // ================================================================
            // Charred Oak Log Material: Charcoal Blocks + Flaky Ash + Embers
            // ================================================================
            float blockVar = cd.cellId;

            // Matte velvety charcoal black with subtle graphitic carbon sheen
            vec3 charAlbedo = (uLightMode == 1)
                ? vec3(0.18 + 0.06 * blockVar + 0.04 * cd.grain)
                : vec3(0.036, 0.035, 0.037) * (0.82 + 0.38 * blockVar) + vec3(0.008) * cd.grain;

            // Pale flaky ash tips along outer char ridges
            vec3 ashAlbedo = (uLightMode == 1)
                ? vec3(0.56 + 0.08 * cd.grain)
                : vec3(0.44, 0.42, 0.39) * (0.86 + 0.28 * cd.grain);

            // Deep fissure walls are slightly darker carbonized soot when unlit
            vec3 sootAlbedo = (uLightMode == 1)
                ? vec3(0.09)
                : vec3(0.018, 0.016, 0.016);

            vec3 albedo = mix(charAlbedo, sootAlbedo, smoothstep(0.15, 0.70, cd.fissureDepth));
            albedo = mix(albedo, ashAlbedo, cd.ashMask * 0.85);

            // Velvety matte charcoal (~0.72..0.88 rough), ultra-matte flaky ash (~0.95)
            float rough = mix(0.72 + 0.14 * blockVar - 0.04 * cd.grain, 0.92, smoothstep(0.25, 0.80, cd.fissureDepth));
            rough = mix(rough, 0.95, cd.ashMask);
            rough = clamp(rough, 0.68, 0.96);

            // Low dielectric F0 for true velvety matte charcoal
            vec3 F0 = mix(vec3(0.032), vec3(0.018), cd.ashMask);

            vec3 lit = vec3(0.0);
            lit += shadeLight(N, V, keyDir,  keyCol  * shKey, albedo, rough, F0);
            lit += shadeLight(N, V, fillDir, fillCol * (0.35 + 0.65 * ao), albedo, rough, F0);
            lit += shadeLight(N, V, rimDir,  rimCol  * shRim, albedo, rough, F0);

            // Studio IBL with physically restrained matte charcoal reflection
            vec3 R = reflect(-V, N);
            vec3 envSpec = studioEnv(R, uLightMode);
            vec3 envDiff = studioEnv(N, uLightMode);
            vec3 Fv = F_Schlick(max(dot(N, V), 0.0), F0);
            lit += albedo * envDiff * (uLightMode == 1 ? 0.72 : 0.62) * ao;
            lit += envSpec * Fv * pow(1.0 - rough, 2.2) * 0.35 * ao;

            // Physically accurate Planck blackbody thermal emission in recessed fissures
            if (emitScale > 0.0) {
                float tempK = evalLogTemperature(p, cd, uOpen);
                vec3 emberRad = planckBlackbody(tempK);

                // Subtle self-illumination bounce onto adjacent fissure shoulders
                float shoulderBounce = smoothstep(0.02, 0.42, cd.fissureDepth) * (1.0 - smoothstep(0.42, 0.85, cd.fissureDepth));
                vec3 bounceGlow = planckBlackbody(mix(920.0, 1280.0, clamp(uOpen, 0.0, 1.0))) * 0.065 * shoulderBounce;

                lit += (emberRad + bounceGlow) * emitScale;
            }

            col = lit;
        }
    }

    // Subtle studio vignette
    float vig = 1.0 - 0.16 * dot(uv, uv);
    col *= clamp(vig, 0.78, 1.0);

    // ACES filmic tone mapping
    col = acesToneMap(col * 1.05);

    // Gamma encode to sRGB
    col = pow(col, vec3(1.0 / 2.2));

    // Calibrated museum luminance guardrails: keep hero within [10..248] (0% crushed black / 0% clipped)
    col = mix(vec3(0.044), vec3(0.968), col);

    // Subtle 8-bit anti-banding dither
    float dither = (hash12(gl_FragCoord.xy + fract(uTime) * 37.0) - 0.5) / 255.0;
    col = clamp(col + dither, 0.0, 1.0);

    fragColor = vec4(col, 1.0);
}
