#version 330
precision highp float;

uniform sampler2D previousState;
uniform float size[2];
uniform float nFrame;

smooth in vec2 vTexCoord;

out vec4 vColor;

void main()
{
    vColor = vec4(1.0,0.0,0.0,1.0);
	float pre = texture(previousState, vTexCoord.st).r;
    int nachbarn = 0;
    if (nFrame > 6500 || vTexCoord.t < 0.5) {
        for(int i = -1; i < 2; i++)
        {
            for(int j = -1; j < 2; j++)
            {
                if((i != 0 || j !=  0) && texture(previousState,vec2(vTexCoord.s+(i*(1.0/size[0])),vTexCoord.t+(j*(1.0/size[1])))).r > 0.0)
                    nachbarn++;
            }
        }
        if ((pre > 0.0 && nachbarn == 2) || (pre > 0.0 && nachbarn == 3) || (pre == 0.0 && nachbarn == 3)) {
            vColor.rgb = vec3(1.0);
        }
        else
            vColor.rgb = vec3(0.0);
    }
    else
        vColor.rgb = vec3(pre);
    
    if(nFrame > 7500)
    {
        float curT = min(1.0, (nFrame-7500)/500.0);
        vColor.rgb = vColor.rgb * vec3(1.0-curT*0.4, 1.0-curT*0.8, 1.0-curT);
        if(curT > 0.5)
            vColor.rgb *= vec3(1.0-mod(curT, 0.5)*2.0);
    }
}