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

#ifdef FRAGMENT_SHADER

flat in int mat;

in vec2 texCoord;
in vec2 lmCoord;
in vec2 signMidCoordPos;
flat in vec2 absMidCoordPos;
flat in vec2 midCoord;

flat in vec3 upVec, sunVec, northVec, eastVec;
in vec3 normal;
in vec3 vertexPos;

in vec4 glColorRaw;

#if LU_RAIN_PUDDLES >= 1 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
    flat in vec3 binormal, tangent;
#endif

#ifdef LU_POM
    in vec3 viewVector;
    in vec4 vTexCoordAM;
#endif

#if LU_ANISOTROPIC_FILTER > 0
    in vec4 spriteBounds;
#endif

#if LU_COLORED_LIGHTING_INTERNAL > 0
    const float voxelDistance = 32.0;
#endif

float NdotU = dot(normal, upVec);
float NdotUmax0 = max(NdotU, 0.0);
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;

vec4 glColor = glColorRaw;

#ifdef OVERWORLD
    vec3 lightVec = sunVec * ((timeAngle < 0.5325 || timeAngle > 0.9675) ? 1.0 : -1.0);
#else
    vec3 lightVec = sunVec;
#endif

#if LU_RAIN_PUDDLES >= 1 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
    mat3 tbnMatrix = mat3(
        tangent.x, binormal.x, normal.x,
        tangent.y, binormal.y, normal.y,
        tangent.z, binormal.z, normal.z
    );
#endif

void lu_DoFoliageColorTweaks(inout vec3 color, inout vec3 shadowMult, inout float snowMinNdotU,
                         vec3 viewPos, vec3 nViewPos, float lViewPos, float dither) {
    #ifdef LU_DREAM_TWEAKED_LIGHTING
        return;
    #endif

    float factor = max(80.0 - lViewPos, 0.0);
    shadowMult *= 1.0 + 0.005 * noonFactor * factor;

    #if defined LU_IPBR && !defined IPBR_COMPATIBILITY_MODE
        if (signMidCoordPos.x < 0.0) {
            color.rgb *= 1.12;
        } else {
            color.rgb *= 0.91;
        }
    #endif

    #ifdef LU_FOLIAGE_ALT_SUBSURFACE
        float edgeSize = 0.15;
        float edgeEffectFactor = 0.85;

        edgeEffectFactor *= (lu_sqrt1(abs(dot(nViewPos, normal))) - 0.1) * 1.111;

        vec2 texCoordM = texCoord;
        texCoordM.y -= edgeSize * lu_pow2(dither) * absMidCoordPos.y;
        texCoordM.y = max(texCoordM.y, midCoord.y - absMidCoordPos.y);
        vec4 colorSample = texture2DLod(tex, texCoordM, 0);

        if (colorSample.a < 0.5) {
            float edgeFactor = dot(nViewPos, lightVec);
            shadowMult *= 1.0 + edgeEffectFactor * (1.2 + edgeFactor);
        }

        shadowMult *= 1.0 + 0.28 * edgeEffectFactor * (dot(normal, lightVec) - 1.0);
    #endif

    #ifdef SNOWY_WORLD
        if (glColor.g - glColor.b > 0.01) {
            snowMinNdotU = min(lu_pow2(lu_pow2(lu_max0(color.g * 2.2 - color.r - color.b))) * 6.0, 0.12);
        } else {
            snowMinNdotU = min(lu_pow2(lu_pow2(lu_max0(color.g * 2.2 - color.r - color.b))) * 3.5, 0.12) * 0.3;
        }

        #ifdef DISTANT_HORIZONS

            snowMinNdotU = mix(snowMinNdotU, 0.11, smoothstep(far * 0.4, far, lViewPos));
        #endif
    #endif
}

void lu_DoBrightBlockTweaks(vec3 color, float minLight, inout vec3 shadowMult, inout float highlightMult) {
    float factor = mix(minLight, 1.0, lu_pow2(lu_pow2(color.r)));
    shadowMult = vec3(factor);
    highlightMult /= factor;

    if (factor > 0.8) {
        shadowMult *= 1.1;
    }
}

void lu_DoOceanBlockTweaks(inout float smoothnessD) {
    smoothnessD *= lu_max0(lmCoord.y - 0.93) * 25.0;
}

#include "/lib/sky/globals.glsl"
#include "/lib/light/core.glsl"

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

#if defined LU_GENERATED_NORMALS || defined LU_COATED_TEXTURES || LU_ANISOTROPIC_FILTER > 0 || defined LU_DISTANT_LIGHT_BOKEH

    vec2 dcdx = dFdx(texCoord.xy);
    vec2 dcdy = dFdy(texCoord.xy);
    vec2 midCoordPos = absMidCoordPos * signMidCoordPos;

    vec2 mipx = dcdx / absMidCoordPos * 8.0;
    vec2 mipy = dcdy / absMidCoordPos * 8.0;

    float mipDelta = max(dot(mipx, mipx), dot(mipy, mipy));
    float miplevel = max(0.5 * log2(mipDelta), 0.0);

    #if !defined LU_GBUFFERS_ENTITIES && !defined LU_GBUFFERS_HAND
        vec2 atlasSizeM = atlasSize;
    #else
        vec2 atlasSizeM = atlasSize.x + atlasSize.y > 0.5 ? atlasSize : textureSize(tex, 0);
    #endif
#endif

#ifdef LU_GENERATED_NORMALS
    #include "/lib/mtl_method/normals.glsl"
#endif

#ifdef LU_COATED_TEXTURES
    #include "/lib/mtl_method/coated.glsl"
#endif

#if LU_IPBR_EMISSIVE_MODE != 1
    #include "/lib/mtl_method/emission.glsl"
#endif

#ifdef LU_CUSTOM_PBR
    #include "/lib/mtl_handle/custom.glsl"
#endif

#if defined COLOR_CODED_PROGRAMS || defined LU_DISTANT_LIGHT_BOKEH
    #include "/lib/fx/unified.glsl"
#endif

#if LU_ANISOTROPIC_FILTER > 0
    #include "/lib/mtl_method/aniso.glsl"
#endif

#ifdef LU_PUDDLE_VOXELIZATION

#endif

#ifdef SNOWY_WORLD
    #include "/lib/mtl_method/snow.glsl"
#endif

#ifdef LU_DISTANT_LIGHT_BOKEH

#endif

void main() {

    #if LU_ANISOTROPIC_FILTER == 0
        vec4 color = texture2D(tex, texCoord);
    #else
        vec4 color = lu_textureAF(tex, texCoord);
    #endif

    float smoothnessD = 0.0, materialMask = 0.0, skyLightFactor = 0.0;

    #if !defined LU_POM || !defined POM_ALLOW_CUTOUT
        if (color.a <= 0.00001) discard;
    #endif

    vec3 colorP = color.rgb;
    color.rgb *= glColor.rgb;

    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 = vertexPos;

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

    int subsurfaceMode = 0;
    bool noSmoothLighting = false, noDirectionalShading = false, noVanillaAO = false;
    bool centerShadowBias = false, noGeneratedNormals = false, doTileRandomisation = true;
    float smoothnessG = 0.0, highlightMult = 1.0, emission = 0.0, noiseFactor = 1.0;
    float snowFactor = 1.0, snowMinNdotU = 0.0, noPuddles = 0.0;
    vec2 lmCoordM = lmCoord;
    vec3 normalM = normal, geoNormal = normal, shadowMult = vec3(1.0);
    vec3 worldGeoNormal = normalize(lu_ViewToPlayer(geoNormal * 10000.0));

    #ifdef LU_IPBR
        vec3 maRecolor = vec3(0.0);
        #include "/lib/mtl_handle/terrain.glsl"

        #ifdef LU_GENERATED_NORMALS
            if (!noGeneratedNormals) {
                lu_GenerateNormals(normalM, colorP);
            }
        #endif

        #ifdef LU_COATED_TEXTURES
            lu_CoatTextures(color.rgb, noiseFactor, playerPos, doTileRandomisation);
        #endif

        #if LU_IPBR_EMISSIVE_MODE != 1
            emission = GetCustomEmissionForIPBR(color, emission);

            if (emission > 0.0) {
                emission *= 1.3;
            }
        #endif
    #else

        #ifdef LU_CUSTOM_PBR
            lu_GetCustomMaterials(color, normalM, lmCoordM, NdotU, shadowMult,
                             smoothnessG, smoothnessD, highlightMult, emission,
                             materialMask, viewPos, lViewPos);
        #endif

        if (mat == 10001) {
            noDirectionalShading = true;
        } else if (mat == 10005) {
            subsurfaceMode = 1, noSmoothLighting = true, noDirectionalShading = true;
            lu_DoFoliageColorTweaks(color.rgb, shadowMult, snowMinNdotU, viewPos, nViewPos, lViewPos, dither);
        } else if (mat == 10009) {
            #include "/lib/blocks/terrain/leaves.glsl"

            smoothnessG *= 1.1;
        } else if (mat == 10013) {
            subsurfaceMode = 3, centerShadowBias = true;
            noSmoothLighting = true;
        } else if (mat == 10017) {
            subsurfaceMode = 1, noSmoothLighting = true, noDirectionalShading = true;
        } else if (mat == 10021) {
            subsurfaceMode = 1, noSmoothLighting = true, noDirectionalShading = true;
            lu_DoFoliageColorTweaks(color.rgb, shadowMult, snowMinNdotU, viewPos, nViewPos, lViewPos, dither);
        } else if (mat == 10028) {
            noSmoothLighting = true;
            noDirectionalShading = true;
            emission = lu_GetLuminance(color.rgb) * 3.0;
        }

        #ifdef SNOWY_WORLD
        else if (mat == 10132) {
            if (glColor.b < 0.999) {
                snowMinNdotU = min(lu_pow2(lu_pow2(color.g)) * 2.2, 0.12);
                color.rgb = color.rgb * 0.45 + 0.55 * (color.rgb / glColor.rgb);
            }
        }
        #endif

        else if (lmCoord.x > 0.99999) lmCoordM.x = 0.95;
    #endif

    #ifdef SNOWY_WORLD
        lu_DoSnowyWorld(color, smoothnessG, highlightMult, smoothnessD, emission,
                     playerPos, lmCoord, snowFactor, snowMinNdotU, NdotU, subsurfaceMode);
    #endif

    #if LU_RAIN_PUDDLES >= 1
        float puddleLightFactor = lu_max0(lmCoord.y * 35.0 - 34.0) * clamp((1.0 - 1.12 * lmCoord.x) * 11.0, 0.0, 1.0);
        float puddleNormalFactor = lu_pow2(lu_max0(NdotUmax0 - 0.45) * 2.22);
        float puddleMixer = puddleLightFactor * inRainy * puddleNormalFactor;

        #if LU_RAIN_PUDDLES < 3
            float wetnessM = wetness;
        #else

            float wetnessM = wetness;
        #endif

        #ifdef LU_PUDDLE_VOXELIZATION
            vec3 voxelPos = lu_SceneToPuddleVoxel(playerPos);
            vec3 voxel_sample_pos = lu_clamp01(voxelPos / vec3(puddle_voxelVolumeSize));
            if (lu_CheckInsidePuddleVoxelVolume(voxelPos)) {
                noPuddles += texture2D(puddle_sampler, voxel_sample_pos.xz).r;
            }
        #endif

        if (lu_pow2(lu_pow2(wetnessM)) * puddleMixer - noPuddles > 0.00001) {
            vec2 worldPosXZ = playerPos.xz + cameraPosition.xz;
            vec2 puddleWind = vec2(frameTimeCounter) * 0.035;

            #if LU_WATER_STYLE == 1
                vec2 puddlePosNormal = floor(worldPosXZ * 16.0) * 0.0625;
            #else
                vec2 puddlePosNormal = worldPosXZ;
            #endif

            puddlePosNormal *= 0.08;
            vec2 pNormalCoord1 = puddlePosNormal + vec2(puddleWind.x, puddleWind.y);
            vec2 pNormalCoord2 = puddlePosNormal + vec2(puddleWind.x * -1.8, puddleWind.y * -1.2);
            vec3 pNormalNoise1 = texture2D(noisetex, pNormalCoord1).rgb;
            vec3 pNormalNoise2 = texture2D(noisetex, pNormalCoord2).rgb;
            float pNormalMult = 0.035;

            vec3 puddleNormal = vec3((pNormalNoise1.xy + pNormalNoise2.xy - vec2(1.0)) * pNormalMult, 1.0);
            puddleNormal = clamp(normalize(puddleNormal * tbnMatrix), vec3(-1.0), vec3(1.0));

            #if LU_RAIN_PUDDLES == 1 || LU_RAIN_PUDDLES == 3
                vec2 puddlePosForm = puddlePosNormal * 0.045;
                float pFormNoise  = texture2D(noisetex, puddlePosForm).b        * 3.2;
                      pFormNoise += texture2D(noisetex, puddlePosForm * 0.5).b  * 5.5;
                      pFormNoise += texture2D(noisetex, puddlePosForm * 0.25).b * 8.5;
                      pFormNoise *= lu_sqrt1(wetnessM) * 0.6 + 0.4;
                      pFormNoise  = clamp(pFormNoise - 6.8, 0.0, 1.0);
            #else
                float pFormNoise = wetnessM;
            #endif
            puddleMixer *= pFormNoise;

            float puddleSmoothnessG = 0.75 - rainFactor * 0.25;
            float puddleHighlight = (1.7 - subsurfaceMode * 0.5 * invNoonFactor);
            smoothnessG = mix(smoothnessG, puddleSmoothnessG, puddleMixer);
            highlightMult = mix(highlightMult, puddleHighlight, puddleMixer);
            smoothnessD = mix(smoothnessD, 1.0, lu_sqrt1(puddleMixer));
            normalM = mix(normalM, puddleNormal, puddleMixer * rainFactor);
        }
    #endif

    #if LU_SHOW_LIGHT_LEVEL > 0

        #if LU_SHOW_LIGHT_LEVEL == 1
            if (heldItemId == 40000 || heldItemId2 == 40000)
        #elif LU_SHOW_LIGHT_LEVEL == 2
            if (heldBlockLightValue > 7.4 || heldBlockLightValue2 > 7.4)
        #endif

        if (NdotU > 0.99) {
            #ifdef OVERWORLD
                #if MC_VERSION < 11800
                    float lxMin = 0.533334;
                #else
                    float lxMin = 0.034;
                #endif
                    float lyMin = 0.533334;
            #else
                float lxMin = 0.8;
                float lyMin = 0.533334;
            #endif

            bool xDanger = lmCoord.x < lxMin;
            #ifndef NETHER
                bool yDanger = lmCoord.y < lyMin;
            #else
                bool yDanger = lmCoord.x < lyMin;
            #endif

            if (xDanger) {
                vec2 indicatePos = playerPos.xz + cameraPosition.xz;
                indicatePos = 1.0 - 2.0 * abs(fract(indicatePos) - 0.5);
                float minPos = min(indicatePos.x, indicatePos.y);

                if (minPos > 0.5) {
                    color.rgb = yDanger ? vec3(0.4, 0.05, 0.05) : vec3(0.3, 0.3, 0.05);

                    smoothnessG = 0.5;
                    highlightMult = 1.0;
                    smoothnessD = 0.0;

                    emission = 3.0;
                }
            }
        }
    #endif

    lu_DoLighting(color, shadowMult, playerPos, viewPos, lViewPos, geoNormal, normalM, dither,
               worldGeoNormal, lmCoordM, noSmoothLighting, noDirectionalShading, noVanillaAO,
               centerShadowBias, subsurfaceMode, smoothnessG, highlightMult, emission);

    #ifdef LU_IPBR
        color.rgb += maRecolor;
    #endif

    #ifdef LU_PBR_REFLECTIONS
        #ifdef OVERWORLD
            skyLightFactor = lu_pow2(max(lmCoord.y - 0.65, 0.0) * 3.7);
        #else
            skyLightFactor = dot(shadowMult, shadowMult) / 2.8;
        #endif
    #endif

    #ifdef COLOR_CODED_PROGRAMS
        lu_ColorCodeProgram(color, mat);
    #endif

    /* DRAWBUFFERS:06 */
    gl_FragData[0] = color;
    gl_FragData[1] = vec4(smoothnessD, materialMask, skyLightFactor, 1.0);

    #if LU_BLOCK_REFLECT_QUALITY >= 2 && LU_RP_MODE != 0

        /* DRAWBUFFERS:065 */
        gl_FragData[2] = vec4(mat3(gbufferModelViewInverse) * normalM, 1.0);
    #endif
}

#endif

#ifdef VERTEX_SHADER

flat out int mat;

out vec2 texCoord;
out vec2 lmCoord;
out vec2 signMidCoordPos;
flat out vec2 absMidCoordPos;
flat out vec2 midCoord;

flat out vec3 upVec, sunVec, northVec, eastVec;
out vec3 normal;
out vec3 vertexPos;

out vec4 glColorRaw;

#if LU_RAIN_PUDDLES >= 1 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
    flat out vec3 binormal, tangent;
#endif

#ifdef LU_POM
    out vec3 viewVector;
    out vec4 vTexCoordAM;
#endif

#if LU_ANISOTROPIC_FILTER > 0
    out vec4 spriteBounds;
#endif

attribute vec4 mc_Entity;
attribute vec4 mc_midTexCoord;

#if LU_RAIN_PUDDLES >= 1 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
    attribute vec4 at_tangent;
#endif

vec4 glColor = vec4(1.0);

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

#ifdef LU_WAVING_ANYTHING_TERRAIN
    #include "/lib/mtl_method/wave.glsl"
#endif

void main() {

    texCoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy;
    lmCoord  = GetLightMapCoordinates();

    glColorRaw = gl_Color;
    if (glColorRaw.a < 0.1) glColorRaw.a = 1.0;
    glColor = glColorRaw;

    normal = normalize(gl_NormalMatrix * gl_Normal);
    upVec = normalize(gbufferModelView[1].xyz);
    eastVec = normalize(gbufferModelView[0].xyz);
    northVec = normalize(gbufferModelView[2].xyz);
    sunVec = GetSunVector();

    midCoord = (gl_TextureMatrix[0] * mc_midTexCoord).st;
    vec2 texMinMidCoord = texCoord - midCoord;
    signMidCoordPos = sign(texMinMidCoord);
    absMidCoordPos  = abs(texMinMidCoord);

    mat = int(mc_Entity.x + 0.5);

    #if LU_ANISOTROPIC_FILTER > 0
        if (mc_Entity.y > 0.5 && dot(normal, upVec) < 0.999) {
            absMidCoordPos = vec2(0.0);
        }
    #endif

    vec4 position = gbufferModelViewInverse * gl_ModelViewMatrix * gl_Vertex;
    vertexPos = position.xyz;

    #ifdef LU_WAVING_ANYTHING_TERRAIN
        lu_DoWave(position.xyz, mat);
    #endif

    gl_Position = gl_ProjectionMatrix * gbufferModelView * position;

    #ifdef LU_FLICKERING_FIX
        if (mat == 10257) {
            gl_Position.z -= 0.00001;
        }
    #endif

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

    #if LU_RAIN_PUDDLES >= 1 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
        binormal = normalize(gl_NormalMatrix * cross(at_tangent.xyz, gl_Normal.xyz) * at_tangent.w);
        tangent  = normalize(gl_NormalMatrix * at_tangent.xyz);
    #endif

    #ifdef LU_POM
        mat3 tbnMatrix = mat3(
            tangent.x, binormal.x, normal.x,
            tangent.y, binormal.y, normal.y,
            tangent.z, binormal.z, normal.z
        );

        viewVector = tbnMatrix * (gl_ModelViewMatrix * gl_Vertex).xyz;

        vTexCoordAM.zw  = abs(texMinMidCoord) * 2;
        vTexCoordAM.xy  = min(texCoord, midCoord - texMinMidCoord);
    #endif

    #if LU_ANISOTROPIC_FILTER > 0
        vec2 spriteRadius = abs(texCoord - mc_midTexCoord.xy);
        vec2 bottomLeft = mc_midTexCoord.xy - spriteRadius;
        vec2 topRight = mc_midTexCoord.xy + spriteRadius;
        spriteBounds = vec4(bottomLeft, topRight);
    #endif
}

#endif
