uniform mat4 u_ColorMatrix;
varying vec2 v_TexCoord;
varying vec2 v_TexCoord2;
varying vec2 v_TexCoord3;
varying vec2 v_Position;
uniform sampler2D u_Tex0;
uniform float u_Time;
uniform vec2 u_Resolution;

const float offset = 0.1 / 128.0;

const float animation_time = 1.5;
const float base = 0.3;

const float num_colors = 3.0;

void main()
{
    vec4 colors[3];
    colors[0] = vec4(1.0, 0.0, 0.0, 0.8);
    colors[1] = vec4(0.0, 1.0, 0.0, 0.8);
    colors[2] = vec4(0.0, 0.2, 1.0, 0.8);
    
    gl_FragColor = texture2D(u_Tex0, v_TexCoord);
    vec4 texcolor = texture2D(u_Tex0, v_TexCoord2);
    if(texcolor.r > 0.9) {
        gl_FragColor *= texcolor.g > 0.9 ? u_ColorMatrix[0] : u_ColorMatrix[1];
    } else if(texcolor.g > 0.9) {
        gl_FragColor *= u_ColorMatrix[2];
    } else if(texcolor.b > 0.9) {
        gl_FragColor *= u_ColorMatrix[3];
    }

    if(gl_FragColor.a < 1.0) {
        float a = texture2D(u_Tex0, vec2(v_TexCoord.x + offset, v_TexCoord.y)).a +
            texture2D(u_Tex0, vec2(v_TexCoord.x, v_TexCoord.y - offset)).a +
            texture2D(u_Tex0, vec2(v_TexCoord.x - offset, v_TexCoord.y)).a +
            texture2D(u_Tex0, vec2(v_TexCoord.x, v_TexCoord.y + offset)).a;

        if (a > 0.0) {
            float interval = animation_time / num_colors;
            float t = mod(u_Time, animation_time);

            float x = mod(t, interval);

            float p = 1.0 - abs((x / interval) * (1.0 - base) * 2.0 - (1.0 - base));

            int cur_color = int (t / interval);
            texcolor = colors[cur_color];

            texcolor.r *= (base + p);
            texcolor.g *= (base + p);
            texcolor.b *= (base + p);

            gl_FragColor = texcolor;
        }
    }
}
