#version 120
uniform vec2 u_resolution;
uniform float u_time;
uniform sampler2D source;
uniform float u_mouse;
uniform float value = 0.2;
uniform int octaves=8;

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

float noise(in vec2 st) {
  vec2 i = floor(st);
  vec2 f = fract(st);

  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;
}

float fbm(in vec2 st) {
  float v = 0.0;
  float a = 0.5;
  vec2 shift = vec2(100.0);
  mat2 rot = mat2(cos(0.5), sin(0.5),
      -sin(0.5), cos(0.5));

  for(int i = 0; i < octaves; i++) {
    v += a * noise(st);
    st = rot * st * 2.0 + shift;
    a *= 0.5;
  }

  return v;
}

void main() {
  vec2 st = gl_FragCoord.xy/u_resolution.xy * 3.0;
  vec3 color = vec3(0.0);

  float speed = u_time * 40.0;
  float value = cos(u_time) * cos(u_time);

  vec2 q = vec2(0.0);
  q.x = fbm(st + 0.00 * speed);
  q.y = fbm(st + vec2(1.0));

  vec2 r = vec2(0,0);
  r.x += fbm( st + 1.0*q + vec2(1.0, 0.0)+ 0.15* speed );
  r.y += fbm( st + 1.0*q + vec2(-1.0, 0.0)+ 0.126* speed);

  float f = fbm(st / r);

  color = mix(vec3(0.122777,0.619608, 0.666667),
                vec3(0.498039,0.666667,0.666667),
                clamp((f*f)*4.0,0.0,1.0));

  color = mix(color,
       vec3(0.0666667, 0.122222, 0.666667),
       clamp(length(r.x), 0.0, 1.0));

  color *= (f*f*f+0.5*f*f+0.6*f) * value;

  vec4 pixel = texture2D(source, gl_TexCoord[0].xy);

  float mask = color.r * pixel.a;

  gl_FragColor = gl_Color * vec4(color, mask) + pixel;
}
