layout(location = 0)in vec3 vertex_position;
layout(location = 1)in vec3 vertex_normal;
layout(location = 2)in vec2 vertex_uv;

out vec3 normal;
out vec2 uv;
out vec3 frag_position;
out vec3 vpos;
out float mat;

uniform mat4 wvp;

uniform float fTime;
uniform float nTime;

uniform int instanceX;
uniform int instanceZ;

mat2 rot(float a){
  float c=cos(a),s=sin(a);
  return mat2(c,s,-s,c);
}

void main() {
  normal = vertex_normal;
  vec2 vuv = vertex_uv.xy*vec2(1,-1);
  uv = vuv;
  uv += vec2(instanceX, instanceZ);
  float hash = instanceX + instanceZ*10 +uv.x + uv.y*99.0; 
  hash = fract(hash*hash*1.1134+hash*412.1234+5341.123);
  // float anim = sin(fTime*3.14159*0.125+hash*0.0+uv.x+uv.y+cos(uv.y+fTime*0.1));
  float anim = 1;
  float len=length(uv*4-vec2(24,21));
  anim=sin(len*5-fTime)/len;
  
  anim=mix(anim,
    sin(fTime*3.14159*0.125+hash*0.2+uv.x*9+uv.y*4+cos(uv.y*5+fTime*1.1)),
    smoothstep(0.4,0.6,nTime));

  anim = smoothstep(-1,1, anim);
  vec4 pos = vec4(vertex_position, 1.0);
  vpos=vertex_position;
  mat=0;

  pos.xz -= vuv;
  // pos.xy *= rot(anim*3.14159);
  // pos.xy *= rot(anim*3.14159);
  pos.xz += vuv;
  pos.x += instanceX * 2.0-9.5;
  pos.z += instanceZ * 2.0-9.5;
  pos.y -= 1; 
  pos.y += anim*nTime;
  mat2 rm=rot(-0.05*fTime);
  pos.xz*=rm;
  normal.xz*=rm;

  frag_position = pos.xyz;
  gl_Position = vec4(pos * wvp);
}
