#version 300 es
precision highp float;

// these are our textures
uniform sampler2D msdf;

uniform vec2 unitRange;
uniform vec4 bgColor;

// this comes from the vertex shader
in vec2 uv_a;
in vec2 uv_b;
in vec4 fontColor;
in float msdf_mix;

out vec4 outputColor;

float median(float r, float g, float b) {
    return max(min(r, g), min(max(r, g), b));
}

//float screenPxRange() {
    ////ivec2 ts = textureSize(msdf, 0);
    ////vec2 unitRange = vec2(pxRange)/vec2(ts);
    //vec2 screenTexSize = vec2(1.0)/fwidth(texCoordVarying);
    //return max(0.5*dot(unitRange, screenTexSize), 1.0);
//}

//float screenPxDistance(vec3 msdf_rgb) {
    //float sd = median(msdf_rgb.r, msdf_rgb.g, msdf_rgb.b);
    //return screenPxRange()*(sd - 0.5);
//}

void main()
{
    vec4 bgColor = vec4(fontColor.rgb,0.0);
    vec4 fgColor = fontColor;

    vec3 msdf_rgb_a = texture( msdf, uv_a ).rgb;
    vec3 msdf_rgb_b = texture( msdf, uv_b ).rgb;
    vec2 sz = vec2(textureSize( msdf, 0 ));
    float dx_a = dFdx( uv_a.x ) * sz.x;
    float dy_a = dFdy( uv_a.y ) * sz.y;
    float dx_b = dFdx( uv_b.x ) * sz.x;
    float dy_b = dFdy( uv_b.y ) * sz.y;
    float toPixels_a = 8.0 * inversesqrt( dx_a * dx_a + dy_a * dy_a );
    float toPixels_b = 8.0 * inversesqrt( dx_b * dx_b + dy_b * dy_b );
    float sigDist_a = median( msdf_rgb_a.r, msdf_rgb_a.g, msdf_rgb_a.b ) - 0.5;
    float sigDist_b = median( msdf_rgb_b.r, msdf_rgb_b.g, msdf_rgb_b.b ) - 0.5;
    float opacity_a = clamp( sigDist_a * toPixels_a + 0.5, 0.0, 1.0 );
    float opacity_b = clamp( sigDist_b * toPixels_b + 0.5, 0.0, 1.0 );

    float opacity = mix(opacity_a, opacity_b, msdf_mix);

    if (opacity < 0.5)
        discard;

    outputColor = vec4(vec3(fgColor),1.0); //mix(bgColor, fgColor, opacity);

    //outputColor = vec4(opacity, 1.0-opacity, 0.0, 1.0);
    //outputColor = vec4(1.0-msdf_rgb.rgb, 1.0);
    //outputColor = vec4(1.0,0.0,1.0,1.0);
}
