#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif

varying vec2 v_uv;

uniform float u_time;
uniform vec2 u_resolution;
uniform float u_grid_size;
uniform sampler2D u_texture;
uniform vec2 u_texture_resolution;
uniform vec2 u_mouse;

#include ../utils/fitImage.frag;

float rand(vec2 co) {
    return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453);
}

float greyScale(in vec3 col) {
    return dot(col, vec3(0.2126, 0.7152, 0.0722));
}

void main() {
    float aspectRatio = u_resolution.x / u_resolution.y;
    vec2 st = vec2(v_uv.x * aspectRatio, v_uv.y);
    vec2 st_mouse = vec2(u_mouse.x * aspectRatio, u_mouse.y);
    // vec2 st_mouse = vec2(0.5,0.5);


    float distance = max(0.6, distance(st, st_mouse) * 10.);

    float gridValue = rand(st + u_time);

    vec3 grainColor = vec3(1.);
    if(gridValue < 0.5) {
        grainColor = vec3(0.);
    }

    vec2 texCoordinates = fitImage(v_uv, u_texture_resolution, u_resolution, 0);
    vec3 texColor = texture2D(u_texture, texCoordinates).rgb;
    texColor = vec3(greyScale(texColor));
    texColor *= rand(st + u_time) / distance;

    vec3 finalTexColor = vec3(0.);
    if(texColor.r > 0.5) {
        finalTexColor = vec3(1.);
    }

    gl_FragColor = vec4(mix(finalTexColor, grainColor, 0.2), 1.);
}
