precision highp float;

// these are our textures
uniform sampler2D msdf;

uniform vec4 fontColor;
uniform float pxRange;

// this comes from the vertex shader
varying vec2 texCoordVarying;

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

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

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

    vec3 msdf_rgb = texture2D(msdf, texCoordVarying).rgb;
    float sd = median(msdf_rgb.r, msdf_rgb.g, msdf_rgb.b);
    float screenPxDistance = screenPxRange()*(sd - 0.5);
    float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
    gl_FragColor = mix(bgColor, fgColor, opacity);
}
