#extension GL_OES_standard_derivatives : enable

precision highp float;

uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;

float random (in vec2 _st) {
   return fract(sin(dot(_st.xy,
                        vec2(12.9898,78.233)))*
       43758.5453123);
}

// Based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in vec2 _st) {
   vec2 i = floor(_st);
   vec2 f = fract(_st);

   // Four corners in 2D of a tile
   float a = random(i);
   float b = random(i + vec2(1.0, 0.0));
   float c = random(i + vec2(0.0, 1.0));
   float d = random(i + vec2(1.0, 1.0));

   vec2 u = f * f * (3.0 - 2.0 * f);

   return mix(a, b, u.x) +
           (c - a)* u.y * (1.0 - u.x) +
           (d - b) * u.x * u.y;
}

#define NUM_OCTAVES 5

float fbm ( in vec2 _st) {
   float v = 0.;
   float a = .5;
   vec2 shift = vec2(100.);
   // Rotate to reduce axial bias
   mat2 rot = mat2(cos(.5), sin(.5),
                   -sin(.5), cos(.5));
   for (int i = 0; i < NUM_OCTAVES; ++i) {
       v += a * noise(_st);
       _st = rot * _st * 2. + shift;
       a *= .5;
   }
   return v;
}

vec2 random2( vec2 p ) {
   return fract(sin(vec2(dot(p,vec2(123.,456.)),dot(p,vec2(789.,158.))))*12345.);
}

void main() {
   vec2 st = gl_FragCoord.xy/resolution.xy;

   vec3 color = vec3(0.0);
   vec2 rand = random2(vec2(0.));
   float zoom = sin(rand.x+time*.2);
   st -= vec2(zoom);
   st *= sin(time/8.)*10.;


   mat2 rot = mat2(cos(time*.2+rand.x), sin(rand.y+time*.3),
                   -sin(rand.y+time*.5), cos(rand.x+time*.4));

   st *= rot;

   vec2 gv = floor(st);
   vec2 id = fract(st);

   float m_dist = 1.;  // minimum distance

   for (int y= -1; y <= 1; y++) {
       for (int x= -1; x <= 1; x++) {
           // Neighbor place in the grid
           vec2 neighbor = vec2(float(x),float(y));

           // Random position from current + neighbor place in the grid
           vec2 point = random2(gv + neighbor);

           // Animate the point
           point = .5 + .5*sin(time + 6.3*point);

           // Vector between the pixel and the point
           vec2 diff = neighbor + point - id;

           // Distance to the point
           float dist = length(diff);

           // Keep the closer distance
           m_dist = min(m_dist, dist);
       }
   }

   color += m_dist;

   // Draw cell center
   color += 1.-step(-.4, m_dist);

   vec2 q = vec2(0.);
   q.x = fbm(gv);
   q.y = fbm( gv + vec2(1.));

   vec2 r = vec2(0.);
   r.x = fbm( gv + q + vec2(1.7,9.2)+ 0.15*m_dist );
   r.y = fbm( gv + q + vec2(8.3,2.8)+ 0.15*m_dist);

   float f = fbm(gv+r);

   color += mix(vec3(.8,.9,.5),
               vec3(.6,0.7,.5),
               clamp((f*f)*4.,.0,1.));

   color = mix(color,
               vec3(.9,.3,0.3),
               clamp(length(q),0.,1.));

   color = mix(color,
               vec3(0.8,1.0,.5),
               clamp(length(r.x),0.0,1.0));

   gl_FragColor = vec4((f*f*f+1.2*f*f+.6*f)*color,1.);
}