precision highp float;

out vec4 FragColor;

in vec2 FragCoord;

uniform sampler2D u_FontSampler;
uniform sampler2D u_TextSampler;
uniform vec2 u_Resolution;
uniform ivec2 u_ViewportOffset;

uniform r_Text {
    int baseline;
    int show;
} text;

void main() {
    ivec2 frag_coord = ivec2(gl_FragCoord.xy) - u_ViewportOffset;
    frag_coord.y = int(u_Resolution.y) - frag_coord.y;
    frag_coord /= 2;
    ivec2 cell = frag_coord / CELL_SIZE;
    cell.y += text.baseline;

    if (cell.y * 64 + cell.x > text.show) {
        discard;
    }
    
    int character = int(texelFetch(u_TextSampler, cell, 0).r * 255.);

    if (character < ASCII_RANGE.x) {
        discard;
    }

    if (character > ASCII_RANGE.y) {
        discard;
    }

    character -= ASCII_RANGE.x;
    ivec2 uv = frag_coord % CELL_SIZE;
    uv += ivec2(character % FONT_LINE_LENGTH, character / FONT_LINE_LENGTH) * CELL_SIZE;

    float sample = texelFetch(u_FontSampler, uv, 0).r;

    if (sample < 0.5) {
        discard;
    }

    FragColor = vec4(1.);
}
