uniform sampler2D color_texture;
uniform vec2      color_texture_pow2_sz;

varying vec2 texCoord;

float decay(float d)
{
    float curveA = 0.0072 / (d*d*d + 0.0057) - d * 0.53;
    float curveB = min(0.006 / (d*d), 0.1) - d * 0.07;
    return clamp(max(curveA, curveB), 0.0, 1.0);
}

// Phosphor Shape
float sqd(vec2 center, vec2 current)
{
    vec2 a = center - current;
    a *= vec2(0.7, 0.8); // Aspect ratio correction
    
    float d = max(abs(a.x), abs(a.y)); // Rectangle distance
    d = mix(d, length(a) * 0.82, 0.6); // Blend with circle
    return d * 0.577;
}

void main()
{
    vec2 p = texCoord * color_texture_pow2_sz;
    
    vec3 col = vec3(0.0);
    
    for(int i = -2; i <= 2; i++)
    for(int j = -1; j <= 1; j++)
    {
        vec2 offset = vec2(float(i), float(j));
        vec2 tap = floor(p) + 0.5 + offset;
        vec2 uv = tap / color_texture_pow2_sz;
        vec3 rez = texture2D(color_texture, uv).rgb;

        float dist = sqd(tap, p);
        rez *= decay(dist);

        col += rez;
    }
    col *= 1.01;
    gl_FragColor = vec4(col, 1.0);
}
