/*
====================================================================================================

    Copyright (C) 2020 RRe36

    All Rights Reserved unless otherwise explicitly stated.


    By downloading this you have agreed to the license and terms of use.
    These can be found inside the included license-file
    or here: https://rre36.com/copyright-license

    Violating these terms may be penalized with actions according to the Digital Millennium
    Copyright Act (DMCA), the Information Society Directive and/or similar laws
    depending on your country.

====================================================================================================
*/

#include "/lib/head.glsl"

out vec2 coord;

flat out float exposure;

const bool colortex0MipmapEnabled = true;

uniform sampler2D colortex0;
uniform sampler2D colortex4;

uniform sampler2D depthtex1;

uniform float frameTime;
uniform float viewHeight;
uniform float viewWidth;
uniform float nightVision;

uniform vec2 pixelSize, viewSize;

float getImageLuma(sampler2D tex) {
    vec3 sample1    = textureLod(tex, vec2(0.5), ceil(log2(max(viewHeight, viewWidth))*1.5)).rgb;
    //vec3 sample2    = textureLod(tex, vec2(0.5), ceil(log2(max(viewHeight, viewWidth)))*rcp(1.5)).rgb;

    return getLuma(sample1);
}

float temporalExp() {

    #if DIM == -1
    const float maxExposure = 30.0;
    const float minExposure = 60.0;
    #elif DIM == 1
    const float maxExposure = 5.0;
    const float minExposure = 30.0;
    #else
    const float maxExposure = 0.16;
    const float minExposure = 80.0;
    #endif

    float expCurr   = clamp(texture(colortex4, vec2(0.5)).a, 0.0, 65535.0);
    float expTarg   = rcp(getImageLuma(colortex0));
        expTarg     = clamp(expTarg, maxExposure, minExposure * rcp(exposureMinlum) + nightVision*15.0);
        expTarg     = log2(expTarg * rcp(6.6));    //adjust this
        expTarg     = 1.2 * pow(2.0, expTarg);

    float adaptBaseSpeed = expTarg < expCurr ? 0.05 : 0.035;

    return mix(expCurr, expTarg, adaptBaseSpeed * exposureSpeed * (frameTime * crcp(0.033)));
}

void main() {
    gl_Position = vec4(gl_Vertex.xy * 2.0 - 1.0, 0.0, 1.0);
    coord = gl_MultiTexCoord0.xy;

    exposure  = temporalExp();
}