#version 330

uniform sampler2D tex0;
uniform sampler2D tex1;
uniform vec2 size;
uniform float time;
uniform float zo;

in vec2 uv;
in vec2 uv1;
in vec4 color;

layout(location = 0) out vec4 output;

uint wang_hash(uint seed)
{
    seed = (seed ^ 61u) ^ (seed >> 16u);
    seed *= 9u;
    seed = seed ^ (seed >> 4u);
    seed *= 668265261u;
    seed = seed ^ (seed >> 15u);
    return seed;
}

float rand(uint value)
{
	return float(wang_hash(value)) * (1.0 / 4294967296.0);
}


void main()
{
  float _time = time / 1000.0; //mod(time / 10000.0, 10000);
  
	vec2 uv = gl_FragCoord.xy / size.xy;
	vec2 block = floor(gl_FragCoord.xy / vec2(64));
	vec2 uv_noise = block / vec2(64);
	//uv_noise += floor(vec2(_time) * vec2(125234.0, 353743.0)) / vec2(64);
	
  float blockSize = 64;
  //if (texture(tex1, uv_noise).r < block_thresh)
  //if (rand(uint(block.x + block.y)) < 0.2)
  {
    float _zo = max(0, zo * 3.0 * 1.5 - 0.5);

    float alpha = 1.0;
        
    float randomFadeIn = _zo * 2.0 + texture(tex1, uv_noise).r -1.0;        
    if (randomFadeIn < 0.0)
    {
      //-1..0
      // 5..6
      alpha = 0; 
    }
    
    if (texture(tex1, uv_noise).r < _zo + 0.5)
      blockSize = 32;        

    if (texture(tex1, uv_noise).r < _zo + 0.2)
      blockSize = 16;        

    if (texture(tex1, uv_noise).r < _zo + 0.1)
      blockSize = 8;        

    if (texture(tex1, uv_noise).r < _zo + 0.05)
      blockSize = 1;        
    
      vec2 zo2 = mod(gl_FragCoord.xy, blockSize) / blockSize;
      vec4 s0 = texture(tex0, (floor((gl_FragCoord.xy) / blockSize + vec2(0.0, 0.0)) * blockSize) / size.xy);
      vec4 s1 = texture(tex0, (floor((gl_FragCoord.xy) / blockSize + vec2(1.0, 0.0)) * blockSize) / size.xy);
      vec4 s2 = texture(tex0, (floor((gl_FragCoord.xy) / blockSize + vec2(1.0, 1.0)) * blockSize) / size.xy);
      vec4 s3 = texture(tex0, (floor((gl_FragCoord.xy) / blockSize + vec2(0.0, 1.0)) * blockSize) / size.xy);
    //output = mix(mix(s0, s1, zo2.x), mix(s3, s2, zo2.x), zo2.y);
    
    s0 = s0 * 0.55 + s1 * 0.15 + s2 * 0.15 + s3 * 0.15;
    
    output = s0;

    if (mod(gl_FragCoord.x, blockSize) < 1 || mod(gl_FragCoord.y, blockSize) < 1)
    {
      output = mix(s0, vec4(1,1,1,1), blockSize / 64.0);
      output.a *= s0.a;
    }
     output.a *= alpha;
  }
}