uniform sampler2D Position; // eye space position
uniform sampler2D Color0;   // water surface texture

varying vec3 eyePos;
varying vec4 projPos;
varying vec3 normal;

//const vec3 waterColor = vec3( 0.0, 0.2, 0.6 );

//////////////////////////////////////////////////////////////////////////
// method to pack a f32 into an rgba8 from gamedev.net forums
//
// http://www.gamedev.net/community/forums/topic.asp?topic_id=463075
//
//////////////////////////////////////////////////////////////////////////

const vec4 bitSh = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
const vec4 bitMsk = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);

void main()
{
  vec2 texCoord = projPos.xy / projPos.w * .5 + .5;
  
  // normalize eye vector
  vec3 e = normalize( eyePos );
/**/
  // recover position from gbuffer
  float depth  = 2000.0 * ( dot( bitSh, texture2D( Position, texCoord ) ) );
  vec3 objPos = e * depth;
 
  // distance from light to geometry
  vec3 l = objPos - eyePos;
  float attenuation = length( l ) * 0.1;
  // discard if outside radius
  attenuation = max( attenuation, 1.0 );
  // quadric vs linear fall off
  //attenuation *= attenuation;
 
  vec4 norm, packpos;
  vec3 color;
  
  // normal
  norm   = vec4( normalize( normal ), 1.0 );
 
  // standard ndotl
  l = normalize( l );
  float ndotl = max( dot( norm, l ), 0.0 );
 
  // want eye linear depth
  float pos = 1.0 - eyePos.z / 2000.0;
  
  // pack
  packpos = fract( pos * bitSh );
  packpos -= packpos.xxyz * bitMsk;

  // unpack color
  color = texture2D( Color0, gl_TexCoord[0].st ).xyz;
  
  gl_FragData[0] = vec4( color, attenuation );
  gl_FragData[1] = norm * .5 + .5;
  gl_FragData[2] = packpos;
}
