#version 330
 
uniform sampler2D t;
uniform sampler2D m;
uniform int mask;
uniform vec2 size;

uniform float wave_amp;
uniform float wave_speed;
uniform float wave_freq;
uniform float wave_phase;
uniform float zo;
uniform int use_wave; 

in vec2 uv;
in vec2 uv1;
in vec4 color;
in float vertexFade;

smooth in vec4 vPosition;
smooth in vec4 vPrevPosition;
smooth in vec4 maskPosition;

layout(location = 0) out vec4 output;
layout(location = 1) out vec4 motion;

void main()
{
  float d = length(uv1 - vec2(0.5, 0.5));

  if (vertexFade > 0.0 && d > 1.0 - vertexFade) discard;
  
  float alphaMask = 1.0;
  vec3 ndc = maskPosition.xyz / maskPosition.w; 
  vec2 muv = (ndc.xy * .5 + .5);  
  if (mask == 1)
  {
    alphaMask = 1.0-texture(m, gl_FragCoord.xy / size).r;
  }
  else
  if (mask == 2)
  {
    alphaMask = texture(m, gl_FragCoord.xy / size).r;
  }


  vec2 offset = vec2(0.0);
  
  vec2 sp = gl_FragCoord.xy / size;
  
  if (use_wave == 1)
  {
    offset = wave_amp * vec2(sin(wave_phase + 2.0 * 3.141592654 * uv.y * wave_freq + zo * wave_speed), 0.0);
  }

  vec4 texColor = texture(t, uv + offset);
  
  /*if (vertexFade > 0.0 && d > 1.0 - vertexFade)
    texColor.a = 0.0;*/
    
  texColor.a *= alphaMask;
  
  if (texColor.a < 0.005) discard;
  
  //texColor.a = pow(texColor.a, 0.3);
  
  //if (vPosition.z > 0.5) discard;

  output = vec4(mix(texColor.rgb, vec3(1.0), pow(vertexFade, 4.0)), texColor.a) * color;
  
  //output = vec4(muv.x, 0.0, 0.0, 1.0);
  
  //output = vec4(texColor.rgba);
                  
  vec2 a = (vPosition.xy / vPosition.w) * 0.5 + 0.5;
  vec2 b = (vPrevPosition.xy / vPrevPosition.w) * 0.5 + 0.5;
  vec2 velocity = a - b;
    
  motion = vec4(velocity * 0.5 + 0.5,0,1);
  
  //output = texColor;
  
  //output = vec4(1,0,0,1);
  
  
  /*float ndcDepth = 
    (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /
    (gl_DepthRange.far - gl_DepthRange.near);
  float clipDepth = ndcDepth / gl_FragCoord.w;


  output = vec4(clipDepth, clipDepth, clipDepth, 1.0);*/       
  
}