// RTMultiShadow closest-hit (runs in SHADE). The multi-light counterpart
// of RTStress: EVERY light emits its own shadow ray from this single
// invocation, so several rays for the same pixel resolve in the next SHADE
// pass — exactly the contention the atomic rtAccumulate exists for (#30).
// Before the atomic accumulator their rtAccumulate calls raced (lost
// updates → flickering dark noise); before RTPass::raysPerPixel the extra
// rays were silently dropped by the capacity guard. The host sets
// raysPerPixel = LIGHT_COUNT so every emit fits the bounce.
//
// Payload declared here so the assembler sees it before wfPayload / SHADE.
struct Payload {
    color:     vec3<f32>,   // shadow ray: pending direct contribution
    shadowRay: u32,         // 0 primary, 1 shadow
};

// Point lights, color premultiplied with intensity; 1/d² falloff at shade
// time. Four distinct hues so each occluder casts four separable shadows —
// any accumulator race or dropped shadow ray is immediately visible as
// noise / a missing color in the overlap regions.
const LIGHT_COUNT: u32 = 4u;
struct Light {
    pos:   vec3<f32>,
    color: vec3<f32>,
};
var<private> LIGHTS: array<Light, 4> = array<Light, 4>(
    Light(vec3<f32>( 14.0,  9.0,   2.0), vec3<f32>(250.0, 205.0, 140.0)),  // warm white
    Light(vec3<f32>(-13.0,  8.0,   7.0), vec3<f32>(235.0,  45.0,  30.0)),  // red
    Light(vec3<f32>(  3.0,  8.0, -14.0), vec3<f32>( 55.0, 225.0, 105.0)),  // green
    Light(vec3<f32>( -5.0, 10.0,  13.0), vec3<f32>( 65.0, 105.0, 250.0)),  // blue
);

const AMBIENT_COLOR: vec3<f32> = vec3<f32>(0.030, 0.034, 0.045);

// Ground (customIndex 0) is a subtle checker so the colored shadows read;
// pillars hash their instance index like RTStress.
fn surfaceAlbedo(customIndex: u32, worldPos: vec3<f32>) -> vec3<f32> {
    if (customIndex == 0u) {
        let cx = u32(floor(worldPos.x * 0.25 + 100.0));
        let cz = u32(floor(worldPos.z * 0.25 + 100.0));
        return mix(vec3<f32>(0.60), vec3<f32>(0.76), f32((cx + cz) & 1u));
    }
    let h = customIndex * 2654435761u;
    return vec3<f32>(
        0.45 + 0.5 * f32((h >>  0u) & 255u) / 255.0,
        0.45 + 0.5 * f32((h >>  8u) & 255u) / 255.0,
        0.45 + 0.5 * f32((h >> 16u) & 255u) / 255.0);
}

fn closesthit_main(ray: RayDesc, hit: HitInfo, payload: ptr<function, Payload>) {
    let meshRec = meshRecords[tlasEntries[hit.instanceId].blasMeshIdx];
    let verts = _rtFetchTri(meshRec, hit.primitiveId);
    let nObj = normalize(cross(verts[1] - verts[0], verts[2] - verts[0]));
    let nWorld = normalize(vec3<f32>(
        dot(hit.objectToWorldR0.xyz, nObj),
        dot(hit.objectToWorldR1.xyz, nObj),
        dot(hit.objectToWorldR2.xyz, nObj)));

    let worldPos = ray.origin + ray.direction * hit.t;
    let nFacing  = select(-nWorld, nWorld, dot(nWorld, -ray.direction) > 0.0);
    let albedo   = surfaceAlbedo(hit.customIndex, worldPos);

    rtAccumulate(albedo * AMBIENT_COLOR);

    // One shadow ray PER LIGHT from this one closest-hit invocation. All of
    // them carry the same pixel; the ones that miss (light visible) each
    // rtAccumulate their light's contribution in the same SHADE pass.
    let shadowOrigin = worldPos + nFacing * 0.05;
    for (var i: u32 = 0u; i < LIGHT_COUNT; i = i + 1u) {
        let toLight = LIGHTS[i].pos - shadowOrigin;
        let dist    = length(toLight);
        let dir     = toLight / dist;
        let nDotL   = dot(nFacing, dir);
        if (nDotL <= 0.0) { continue; }
        var sp: Payload;
        sp.color     = albedo * LIGHTS[i].color * (nDotL / (dist * dist));
        sp.shadowRay = 1u;
        // tMax stops at the light so geometry beyond it can't occlude.
        rtEmitRay(shadowOrigin, 0.01, dir, dist,
                  RT_FLAG_SKIP_CLOSEST_HIT | RT_FLAG_TERMINATE_ON_FIRST_HIT,
                  0xFFu, 0u, 0u, sp);
    }
}
