#version 120
/*
varying float light;
uniform vec4 color;
uniform float ambientLight;

void main() {
  float lightValue = min(1.0, ambientLight + light);
  gl_FragColor = vec4(color.r * lightValue * color.a, color.g * lightValue * color.a, color.b * lightValue * color.a, color.a);
}
*/

varying vec2 uv;

uniform sampler2D u;    // input velocity
//uniform sampler2D x;    // qty to advect
uniform float timestep;
uniform float texelSize;

vec4 f4texRECTbilerp(sampler2D tex, vec2 s, float texelSize) {
  vec4 st;
  st.xy = (floor(s / texelSize - 0.5) + 0.5) * texelSize;
  st.zw = st.xy + texelSize;

  vec2 t = (s - st.xy) / texelSize; //interpolating factors

  vec4 tex11 = texture2D(tex, st.xy);
  vec4 tex21 = texture2D(tex, st.zy);
  vec4 tex12 = texture2D(tex, st.xw);
  vec4 tex22 = texture2D(tex, st.zw);

  // bilinear interpolation
  return mix(mix(tex11, tex21, t.x), mix(tex12, tex22, t.x), t.y);
}

void main() {
   // follow the velocity field "back in time"
   // interpolate and write to the output fragment
   if (uv.x > 0.49 && uv.x < 0.51 && uv.y > 0.49 && uv.y < 0.51)
    gl_FragColor = vec4(1, 1, 0, 0);
   else {
    vec2 pos = uv - timestep * texture2D(u, uv).xy;
    gl_FragColor = f4texRECTbilerp(u, pos, texelSize);
   }
    
}

/*
vec4 advect(vec2 uv, sampler2D textureSampler, float timestep)
{
  // follow the velocity field "back in time"
  float2 pos = coords - timestep * texture(textureSampler, uv).xy;
  return texture(pos);
}

void jacobi(vec2 coords, float alpha, float rBeta, float rdx)
{
  // left, right, bottom, and top x samples
  vec4 xL = texture(coords - vec2(1, 0)*rdx);
  vec4 xR = texture(coords + vec2(1, 0)*rdx);
  vec4 xB = texture(coords - vec2(0, 1)*rdx);
  vec4 xT = texture(coords + vec2(0, 1)*rdx);

  // b sample, from center
  vec4 bC = texture(coords).g;

  // evaluate Jacobi iteration
  return (xL + xR + xB + xT + alpha * bC) * rBeta;
}




void jacobi(half2 coords   : WPOS,   // grid coordinates
            
   out 
   half4 xNew : COLOR,  // result
            
   uniform 
   half alpha,
            uniform 
   half rBeta,      // reciprocal beta
            
   uniform samplerRECT x,   // x vector (Ax = b)
            
   uniform samplerRECT b)   // b vector (Ax = b)
{
  // left, right, bottom, and top x samples
  
  half4 xL = h4texRECT(x, coords - half2(1, 0));
  half4 xR = h4texRECT(x, coords + half2(1, 0));
  half4 xB = h4texRECT(x, coords - half2(0, 1));
  half4 xT = h4texRECT(x, coords + half2(0, 1));

  // b sample, from center
  
   half4 bC = h4texRECT(b, coords);

  // evaluate Jacobi iteration
  xNew = (xL + xR + xB + xT + alpha * bC) * rBeta;
}

*/