uniform sampler2D textureSampler;
varying vec2 texCoord;

const vec2 pixelSize = vec2(1.0/1280.0, 1.0/800.0);

vec4 hq2x()
{
    vec4 c = texture2D(textureSampler, texCoord);
    vec4 t = texture2D(textureSampler, texCoord + vec2(0.0, pixelSize.y)); 
    vec4 tl = texture2D(textureSampler, texCoord + vec2(-pixelSize.x, -pixelSize.y));
    vec4 tr = texture2D(textureSampler, texCoord + vec2(pixelSize.x, -pixelSize.y));
    vec4 l = texture2D(textureSampler, texCoord + vec2(-pixelSize.x, 0.0));
    vec4 r = texture2D(textureSampler, texCoord + vec2(pixelSize.x, 0.0));
    vec4 b = texture2D(textureSampler, texCoord + vec2(0.0, -pixelSize.y));
    vec4 bl = texture2D(textureSampler, texCoord + vec2(-pixelSize.x, pixelSize.y));
    vec4 br = texture2D(textureSampler, texCoord + vec2(pixelSize.x, pixelSize.y));

    vec4 result = c;
    if (c.a > 0.0) {
        float pattern = 0.0;
        pattern += (length(c - t) > 0.1) ? 1.0 : 0.0;
        pattern += (length(c - l) > 0.1) ? 2.0 : 0.0;
        pattern += (length(c - r) > 0.1) ? 4.0 : 0.0;
        pattern += (length(c - b) > 0.1) ? 8.0 : 0.0;

        if (pattern == 1.0) result = mix(c, t, 0.5);
        else if (pattern == 2.0) result = mix(c, l, 0.5);
    }
    return result;
}

void main()
{
    vec2 fragCoord = texCoord * vec2(1280.0, 800.0);
    vec2 subCoord = fract(fragCoord);
    
    if (subCoord.x < 0.5 && subCoord.y < 0.5)
        gl_FragColor = hq2x();
    else
        gl_FragColor = texture2D(textureSampler, texCoord);
}
