#include "core.fsh"
#include "idioms.sh"

in vec2 UV_f;
layout(location = 0) out half fs_shadowIntensity;

uniform lowp sampler2D ShadowIntensityTexture;

const float2 _Dither2x2PositionMap[4] = float2[4](
    float2(0.0, 0.0),
    float2(1.0, 1.0),
    float2(0.0, 1.0),
    float2(1.0, 0.0)
 );

 half ApplyDitheringFilter(float2 uv, float4 texSizeParams) {

    float2 texPos = uv * texSizeParams.xy;
    int2 indexBits = int2(greaterThan(fract(texPos * 0.5), float2(0.25)));
    float2 offset = _Dither2x2PositionMap[indexBits.x + indexBits.y * 2];
    uv += offset * texSizeParams.zw;

    float2 tapU = uv.xx + float2(-1.5, 0.5) * texSizeParams.zz;
    float2 tapV = uv.yy + float2(-1.5, 0.5) * texSizeParams.ww;

    half result;
    result  = texture(ShadowIntensityTexture, float2(tapU.x, tapV.x)).r;
    result += texture(ShadowIntensityTexture, float2(tapU.y, tapV.x)).r;
    result += texture(ShadowIntensityTexture, float2(tapU.x, tapV.y)).r;
    result += texture(ShadowIntensityTexture, float2(tapU.y, tapV.y)).r;

    return result * inl_half(0.25);
}

void main() {
    float2 texSize = float2(textureSize(ShadowIntensityTexture, 0));
    float4 texSizeParams = float4(texSize, rcp(texSize));
    fs_shadowIntensity = ApplyDitheringFilter(UV_f, texSizeParams);
}
