
#include "/lib/config/master.glsl"

#ifdef FRAGMENT_SHADER

in vec2 texCoord;
flat in vec3 upVec, sunVec;
in vec4 glColor;

float SdotU = dot(sunVec, upVec);
float sunFactor = SdotU < 0.0 ? clamp(SdotU + 0.375, 0.0, 0.75) / 0.75 : clamp(SdotU + 0.03125, 0.0, 0.0625) / 0.0625;
float sunVisibility = clamp(SdotU + 0.0625, 0.0, 0.125) / 0.125;
float sunVisibility2 = sunVisibility * sunVisibility;
float shadowTimeVar1 = abs(sunVisibility - 0.5) * 2.0;
float shadowTimeVar2 = shadowTimeVar1 * shadowTimeVar1;
float shadowTime = shadowTimeVar2 * shadowTimeVar2;

#include "/lib/sky/globals.glsl"
#include "/lib/sky/aero/main.glsl"

#ifdef LU_TAA
    #include "/lib/filter/offset.glsl"
#endif

#ifdef COLOR_CODED_PROGRAMS
    #include "/lib/fx/unified.glsl"
#endif

void main() {

    vec4 color = texture2D(tex, texCoord);
    vec3 colorP = color.rgb;
    color *= glColor;

    vec3 screenPos = vec3(gl_FragCoord.xy / vec2(viewWidth, viewHeight), gl_FragCoord.z);
    #ifdef LU_TAA
        vec3 viewPos = lu_ScreenToView(vec3(lu_TAAJitter(screenPos.xy, -0.5), screenPos.z));
    #else
        vec3 viewPos = lu_ScreenToView(screenPos);
    #endif

    float lViewPos = length(viewPos);
    vec3 nViewPos = normalize(viewPos);
    vec3 playerPos = lu_ViewToPlayer(viewPos);
    float VdotU = dot(nViewPos, upVec);
    float VdotS = dot(nViewPos, sunVec);

    float dither = Bayer64(gl_FragCoord.xy);
    #ifdef LU_TAA
        dither = fract(dither + goldenRatio * mod(float(frameCounter), 3600.0));
    #endif

    #ifdef ATM_COLOR_MULTS
        atmColorMult = GetAtmColorMult();
    #endif

    #ifdef LU_IPBR
        float emission = dot(colorP, colorP);

        if (0.5 > color.a && color.a > 0.01) {
            color.a = 0.101;
            emission = lu_pow2(lu_pow2(emission)) * 0.1;
        }

        color.rgb *= color.rgb * emission * 1.75;
        color.rgb += emission * 0.05;
    #else

        color.rgb *= color.rgb * 4.0;
    #endif

    color.rgb *= 0.5 + 0.5 * exp(-lViewPos * 0.04);

    #ifdef COLOR_CODED_PROGRAMS
        lu_ColorCodeProgram(color, -1);
    #endif

    float sky = 0.0;
    if (playerPos.y > 0.0) {

        playerPos.y = pow(playerPos.y / renderDistance, 0.15) * renderDistance;
    }

    lu_DoFog(color.rgb, sky, lViewPos, playerPos, VdotU, VdotS, dither);
    color.a *= 1.0 - sky;

    /* DRAWBUFFERS:06 */
    gl_FragData[0] = color;
    gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);
}

#endif

#ifdef VERTEX_SHADER

out vec2 texCoord;
flat out vec3 upVec, sunVec;
out vec4 glColor;

#ifdef LU_TAA
    #include "/lib/filter/offset.glsl"
#endif

void main() {

    gl_Position = ftransform();

    #ifdef LU_TAA
        gl_Position.xy = lu_TAAJitter(gl_Position.xy, gl_Position.w);
    #endif

    upVec = normalize(gbufferModelView[1].xyz);
    sunVec = GetSunVector();

    texCoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy;
    glColor = gl_Color;
}

#endif
