
// method give a random number between 0 and 1.
vec2 N22(vec2 p)
{
    vec3 a = fract(p.xyx*vec3(123.34, 234.34, 345.65));
    a += dot(a, a+34.45);
    return fract(vec2(a.x*a.y, a.y*a.z));
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Normalized pixel coordinates (from 0 to 1)
    vec2 uv = (2.*fragCoord-iResolution.xy)/iResolution.y;

    float m = 0.;
    float t = iTime *.5;   // because points will moving, store time.
   
    float minDst = 100.; // Need to keep track on the minimum Dst between a given uv pos and the closest point
    float cellIndex = 0.;
     
    vec3 col = vec3(0);
    
    if (false) {
        // Generate a bunch of random moving points
        for(float i=0.; i<50.; i++)
        {
            vec2 n = N22(vec2(i));
            vec2 pointPos = sin(n*t);

            float dst = length(uv-pointPos);
            m += smoothstep(.03, .02, dst);

            if (dst<minDst){
                minDst = dst;
                cellIndex = i;
            }
        }
    }
    else {
        uv *= 10.;

        vec2 grid = fract(uv)-.5;
        vec2 id = floor(uv); 
        
        vec2 cellId = vec2(0);
        
        for(float y=-1.; y<=1.; y++) {
            for(float x=-1.; x<=1.; x++) {
                vec2 offs = vec2(x,y);
                
                vec2 n = N22(id+offs);
                vec2 pointPos = offs + sin(n*t)*.5;
                float dst = length(grid-pointPos);
                
                if (dst<minDst){
                    minDst = dst;
                    cellId = id+offs;
                }
            }
        }
        
        col = vec3(minDst);
        col.rg = cellId * .12;
    }
    
    
    // Output to screen
    fragColor = vec4(col,1.0);
}
