#version 330
 
uniform sampler2D t;

uniform float phase;
uniform float amp0;
uniform float amp1;
uniform float freq;
uniform int mode;

in vec2 uv;

smooth in vec4 vPosition;
smooth in vec4 vPrevPosition;

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

float coss(float x)
{
  if (x < 0)
    return 0;
  if (x > 2.0 * 3.141592654)
    return 0;
  
  return (1.0 - cos(x)) * 0.5;
}
 
void main()
{
  float width = 1.0;
  
  if (mode == 0)
  {
    width = amp0;
  }
  else if (mode == 1)
  {
    width = amp0 + (amp1 - amp0) * coss(freq * (uv.x + (1 / freq) - phase * (1 + 1/freq)) * 2.0 * 3.141592);
  }
  else if (mode == 2)
  {
    width = amp0 + (amp1 - amp0) * 0.5 * (1.0 - cos(freq * (uv.x + (1 / freq) - phase * (1 + 1/freq)) * 2.0 * 3.141592));
  }
  
  if (uv.y < 0.5 - width * 0.5)
  {
    discard;
  }
  else if (uv.y > 0.5 + width * 0.5)
  {
    discard;
  }
  else
  {
    float a = 1.0;
    for (float i = 0; i <= 250; i++)
    {
      float zo = -1.0 + 2.0 * (float(i) / 250);
      
      vec4 c = texture(t, clamp((uv - vec2(0.0, 0.5)) * vec2(1.0, 1.0 / width)
                    + vec2(0, 0.5)
                    
                    + vec2(0.0, zo * (1.0 - width) * 0.3)
                    
                    , vec2(0), vec2(1))
                    
                    );
                    
      a *= (1.0 - c.a);
    }
      
    //ac *= 250;
    a = 1.0 - a;
        
    /*float a = texture(t, (uv - vec2(0.0, 0.5)) * vec2(1.0, 1.0 / width)
                    + vec2(0, 0.5)
                    ).a;*/
    output = vec4(0, 0, 0, a);
    
    {
      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);
    }    
  }
  

  //vec4 texColor = texture(t, uv * vec2(1.0, 1));
  //output = vec4(texColor);
}