/***********************************************/
/*          Copyright (C) 2024 Belmu           */
/*       GNU General Public License V3.0       */
/***********************************************/

#include "/settings.glsl"
#include "/include/taau_scale.glsl"

#include "/include/common.glsl"

#if defined STAGE_VERTEX

    out vec2 textureCoords;
    out vec2 vertexCoords;
    out vec3 directIlluminance;

    void main() {
        gl_Position    = vec4(gl_Vertex.xy * 2.0 - 1.0, 1.0, 1.0);
        gl_Position.xy = gl_Position.xy * RENDER_SCALE + (RENDER_SCALE - 1.0) * gl_Position.w; + (RENDER_SCALE - 1.0);
        textureCoords  = gl_Vertex.xy;
        vertexCoords   = gl_Vertex.xy * RENDER_SCALE;

        #if defined WORLD_OVERWORLD
            directIlluminance = texelFetch(ILLUMINANCE_BUFFER, ivec2(0), 0).rgb;
        #endif
    }

#elif defined STAGE_FRAGMENT

    #if GI == 1
        /* RENDERTARGETS: 4,9,10 */

        layout (location = 0) out vec4 radiance;
        layout (location = 1) out vec3 directOut;
        layout (location = 2) out vec4 momentsOut;
    #else
        /* RENDERTARGETS: 4,10 */

        layout (location = 0) out vec4 radiance;
        layout (location = 1) out vec4 momentsOut;
    #endif

    in vec2 textureCoords;
    in vec2 vertexCoords;
    in vec3 directIlluminance;

    #include "/include/atmospherics/constants.glsl"

    #include "/include/utility/phase.glsl"

    #include "/include/fragment/brdf.glsl"
    #include "/include/atmospherics/celestial.glsl"

    #include "/include/post/exposure.glsl"

    #if GI == 1
        #include "/include/fragment/raytracer.glsl"
        #include "/include/fragment/pathtracer.glsl"

        #if RENDER_MODE == 0 && ATROUS_FILTER == 1
			float estimateSpatialVariance(sampler2D tex, vec2 moments) {
				float sum = moments.r, sqSum = moments.g, totalWeight = 1.0;

				const float waveletKernel[3] = float[3](1.0, 2.0 / 3.0, 1.0 / 6.0);

				vec2 stepSize = 5.0 * texelSize;

				for(int x = -1; x <= 1; x++) {
					for(int y = -1; y <= 1; y++) {
						if(x == 0 && y == 0) continue;

						vec2 sampleCoords = textureCoords + vec2(x, y) * stepSize;
						if(saturate(sampleCoords) != sampleCoords) continue;

						float weight    = waveletKernel[abs(x)] * waveletKernel[abs(y)];
						float luminance = luminance(texture(tex, sampleCoords).rgb);
                    
						sum   += luminance * weight;
						sqSum += luminance * luminance * weight;

						totalWeight += weight;
					}
				}
				sum   /= totalWeight;
				sqSum /= totalWeight;
				return abs(sqSum - sum * sum);
    		}
	    #endif
    #endif

    void main() {
        vec2 fragCoords = gl_FragCoord.xy * texelSize / RENDER_SCALE;
	    if(saturate(fragCoords) != fragCoords) { discard; return; }

        sampler2D depthTex = depthtex0;
        float     depth    = texture(depthtex0, vertexCoords).r;

        mat4 projection        = gbufferProjection;
        mat4 projectionInverse = gbufferProjectionInverse;

        float nearPlane = near;
        float farPlane  = far;

        #if defined DISTANT_HORIZONS
            if(depth >= 1.0) {
                depthTex = dhDepthTex0;
                depth    = texture(dhDepthTex0, vertexCoords).r;

                projection        = dhProjection;
                projectionInverse = dhProjectionInverse;

                nearPlane = dhNearPlane;
                farPlane  = dhFarPlane;
            }
        #endif

        vec3 viewPosition = screenToView(vec3(textureCoords, depth), projectionInverse, true);

        vec3 skyIlluminance = vec3(0.0);
        #if defined WORLD_OVERWORLD || defined WORLD_END
            skyIlluminance = texelFetch(ILLUMINANCE_BUFFER, ivec2(gl_FragCoord.xy), 0).rgb;
        #endif

        if(depth == 1.0) {
            vec3 sky = renderAtmosphere(vertexCoords, viewPosition, directIlluminance, skyIlluminance);
            #if GI == 1
                directOut = sky;
            #else
                radiance.rgb = sky;
            #endif
            return;
        }

        #if AO > 0 && AO_FILTER == 1 && GI == 0 || GI == 1 && TEMPORAL_ACCUMULATION == 1
            vec3 prevPosition = vec3(vertexCoords, depth) + getVelocity(vec3(textureCoords, depth), projectionInverse) * RENDER_SCALE;
            vec4 history      = texture(ACCUMULATION_BUFFER, prevPosition.xy);

            radiance.a  = history.a;
            radiance.a *= float(clamp(prevPosition.xy, 0.0, RENDER_SCALE) == prevPosition.xy);
            radiance.a *= float(depth >= handDepth);

            momentsOut = texture(MOMENTS_BUFFER, prevPosition.xy);

            #if RENDER_MODE == 0
                float prevDepth = exp2(momentsOut.a);
                
                momentsOut.a = log2(prevPosition.z);

                float linearDepth     = linearizeDepth(prevPosition.z, nearPlane, farPlane);
			    float linearPrevDepth = linearizeDepth(prevDepth     , nearPlane, farPlane);

                radiance.a *= step(abs(linearDepth - linearPrevDepth) / max(linearDepth, linearPrevDepth), 0.1);

                #if GI == 0
                    vec2 pixelCenterDist = 1.0 - abs(2.0 * fract(prevPosition.xy * viewSize) - 1.0);
                         radiance.a     *= sqrt(pixelCenterDist.x * pixelCenterDist.y) * 0.3 + 0.7;
                #else
                    radiance.a *= float(depth >= handDepth);
                #endif

                radiance.a = min(radiance.a, 60.0);
            #else
                radiance.a *= float(hideGUI);
            #endif

            radiance.a++;
        #endif

        Material material = getMaterial(vertexCoords);

        bool isMetal = material.F0 * maxFloat8 > 229.5;

        #if GI == 0
            radiance.rgb = vec3(0.0);

            float cloudsShadows = 1.0; vec4 shadowmap = vec4(1.0, 1.0, 1.0, 0.0);

            #if defined WORLD_OVERWORLD && CLOUDS_SHADOWS == 1 && CLOUDS_LAYER0_ENABLED == 1
                cloudsShadows = getCloudsShadows(viewToScene(viewPosition));
            #endif

            #if SHADOWS > 0
                shadowmap = texelFetch(SHADOWMAP_BUFFER, ivec2(max(gl_FragCoord.xy, vec2(1.0))), 0);
            #endif

            float ao = 1.0;
            #if AO > 0
                ao = texture(AO_BUFFER, vertexCoords).b;
            #endif

            radiance.rgb = computeDiffuse(viewPosition, shadowVec, material, isMetal, shadowmap, directIlluminance, skyIlluminance, ao, cloudsShadows);
        #else
            pathtrace(depthTex, projection, projectionInverse, directIlluminance, isMetal, radiance.rgb, vec3(vertexCoords, depth), directOut);

            #if TEMPORAL_ACCUMULATION == 1
                float weight = 1.0 / max(radiance.a, 1.0);
                radiance.rgb = mix(history.rgb, radiance.rgb, weight);

                #if RENDER_MODE == 0 && ATROUS_FILTER == 1
                    float luminance = luminance(radiance.rgb);
                    vec2  moments   = vec2(luminance, luminance * luminance);

                    momentsOut.rg = mix(momentsOut.rg, moments, weight);

                    if(radiance.a < VARIANCE_STABILIZATION_THRESHOLD) {
                        momentsOut.b = estimateSpatialVariance(ACCUMULATION_BUFFER, moments);
                    } else { 
                        momentsOut.b = abs(momentsOut.g - momentsOut.r * momentsOut.r);
                    }
                #endif
            #endif
        #endif

        // Alpha blending
        vec4 basic = texture(RASTER_BUFFER, vertexCoords);

        bool isEnchantmentGlint = basic.a == 0.0;
        bool isDamageOverlay    = basic.a > 0.0 && basic.a < 1e-2;

        if(isEnchantmentGlint) {
            float prevLuminance = texelFetch(HISTORY_BUFFER, ivec2(0), 0).a;

            // Inverting exposure for enchantment glints
            radiance.rgb += basic.rgb / computeExposure(prevLuminance);
        } else if(isDamageOverlay) {
            if(depth >= handDepth) radiance.rgb = 2.0 * basic.rgb * radiance.rgb;
        } else {
            radiance.rgb = mix(radiance.rgb, basic.rgb, basic.a);
        }
    }
#endif
