uniform mat4 u_Color;
varying vec2 v_TexCoord;
varying vec2 v_TexCoord2;
uniform sampler2D u_Tex0;
uniform float u_Time;

void main()
{
    vec4 base = texture2D(u_Tex0, v_TexCoord);
    vec4 mask = texture2D(u_Tex0, v_TexCoord2);

    if(mask.r > 0.9) {
        base *= mask.g > 0.9 ? u_Color[0] : u_Color[1];
    } else if(mask.g > 0.9) {
        base *= u_Color[2];
    } else if(mask.b > 0.9) {
        base *= u_Color[3];
    }

    float thickness = 3.0;
    vec2 texel = vec2(thickness / 1024.0, thickness / 1728.0);

    float l = texture2D(u_Tex0, v_TexCoord + vec2(-texel.x, 0.0)).a;
    float r = texture2D(u_Tex0, v_TexCoord + vec2( texel.x, 0.0)).a;
    float u = texture2D(u_Tex0, v_TexCoord + vec2(0.0,  texel.y)).a;
    float d = texture2D(u_Tex0, v_TexCoord + vec2(0.0, -texel.y)).a;

    float outline = (1.0 - l * r * u * d) * base.a;

    vec3 rainbow;
    rainbow.r = 0.5 + 0.5 * sin(u_Time);
    rainbow.g = 0.5 + 0.5 * sin(u_Time + 2.094);
    rainbow.b = 0.5 + 0.5 * sin(u_Time + 4.188);

    vec4 outlineColor = vec4(rainbow, 1.0);

    gl_FragColor = mix(base, outlineColor, outline);

    if(gl_FragColor.a < 0.01) discard;
}
