/***********************************************/
/*           Copyright (c) 2025 Belmu          */
/*             All Rights Reserved             */
/***********************************************/

layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;

const ivec3 workGroups = ivec3(1, 1, 1);

#include "/settings.glsl"
#include "/include/uniforms.glsl"

#if MANUAL_CAMERA == 0 && EXPOSURE > 0

    layout (r32f) uniform image2D colorimg2;

    #if EXPOSURE == 2
        uniform usampler1D histogramSampler;
    #endif

    void main() {
        float averageLuminance;

        #if EXPOSURE == 1
            averageLuminance = luminance(texture(DOWNSAMPLED_BUFFER, vec2(0.25)).rgb);
        #else
            averageLuminance = uintBitsToFloat(texelFetch(histogramSampler, 0, 0).r);
        #endif

        float previousLuminance = texelFetch(LUMINANCE_BUFFER, ivec2(0), 0).r;
              previousLuminance = previousLuminance > 0.0 ? previousLuminance : averageLuminance;
              previousLuminance = isnan(previousLuminance) || isinf(previousLuminance) ? averageLuminance : previousLuminance;

        float exposureSpeed = averageLuminance < previousLuminance ? EXPOSURE_GROWTH : EXPOSURE_DECAY;

        averageLuminance = mix(averageLuminance, previousLuminance, exp(-exposureSpeed * frameTime));

        imageStore(colorimg2, ivec2(0), vec4(averageLuminance, 0.0, 0.0, 0.0));
    }

#else

    void main() {
        return;
    }

#endif
