#version 330 core

in vec2 texCoord;
in vec4 vertexFragColor;
out vec4 fragColor;
uniform sampler2D texture0;
uniform vec4 color = vec4(1,1,1,1);
uniform bool enableVertexColor = false;
uniform float time = 1.0;
uniform vec2 resolution = vec2(1280,720)*0.3;
uniform int usePlasma = 1;

#define M_PI 3.1415926535897932384626433832795

vec2 pixelate(vec2 coord)
{
    vec2 d = vec2(1.0,1.0)/resolution;
    coord.s = floor(coord.s/d.s)*d.s;
    coord.t = floor(coord.t/d.t)*d.t;
    return coord;    
}

float rand(vec2 coord)
{
    return fract(sin(dot(coord.st,vec2(12.9898,78.233)+time)) * 43758.5453);
}

uniform vec2 scale = vec2(4,3);

vec4 plasma()
{
    vec2 coord = texCoord * scale;
    float d = 0.0;
    d+=sin(coord.x+time)*0.3;
    d+=cos(coord.y+time)*0.8;
    d-=sin(coord.x+coord.y+time);
    coord += vec2(sin(coord.x+time*2), cos(coord.y+time*3));
    d += sin(sqrt(d*10+coord.x*coord.x+coord.y*coord.y)+time);
    d = (1+cos(M_PI*1.4*d))/2.;

    return vec4(vec3(d), 1);
}

void main()
{
    fragColor = vec4(vec3(rand(pixelate(texCoord))),1) * texture(texture0, texCoord) * color;
    if (usePlasma == 1) {
        fragColor *= plasma();
    }
}
