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 = 2.1;
const float idle_time = 0.4;

const float num_colors = 3.0;

void main()
{
    vec4 colors[4];
    colors[0] = vec4(1.0, 0.0, 0.0, 0.9);
    colors[1] = vec4(0.0, 1.0, 0.0, 0.9);
    colors[2] = vec4(0.0, 0.0, 1.0, 0.9);
    colors[3] = colors[0];
    
    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 < 0.01) {
        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);

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

            // normalize the interval to (0.0, 1.0)
            float p = mod(t, interval) / interval;

            // color transition
            if (p >= idle_time){
                int next_color = cur_color + 1;
                vec4 n_texcolor = colors[next_color];

                p = (p - idle_time) / (1.0 - idle_time);

                texcolor.r = texcolor.r * (1.0 - p) + n_texcolor.r * p;
                texcolor.g = texcolor.g * (1.0 - p) + n_texcolor.g * p;
                texcolor.b = texcolor.b * (1.0 - p) + n_texcolor.b * p;
            }

            gl_FragColor = texcolor;
        }
    }
}
