uniform sampler2D Color0;
uniform sampler2D Color1;
uniform sampler2D Position;

const vec3 toLuma = vec3( 0.299, 0.587, 0.114 );

const float screenWidth = 1024.0;
const float screenHeight = 768.0;

const vec2 offset0 = vec2( 1.0 / screenWidth, 1.0 / screenHeight );
const vec2 offset1 = vec2(-1.0 / screenWidth, 1.0 / screenHeight );
const vec2 offset2 = vec2(-1.0 / screenWidth,-1.0 / screenHeight );
const vec2 offset3 = vec2( 1.0 / screenWidth,-1.0 / screenHeight );

void main()
{
  vec4  standard   = texture2D( Color0, gl_TexCoord[0].st );
  vec3  glow       = texture2D( Color1, gl_TexCoord[0].st ).rgb;
  float luma       = dot( toLuma, standard.rgb );
 /* */
  // multiple samples for antialiasing based on edge detect
  float offsetx = 1.0 / screenWidth;
  float offsety = 1.0 / screenHeight;
  
  vec4 aa;
  aa  = texture2D( Color0, gl_TexCoord[0].st + offset0 );
  aa += texture2D( Color0, gl_TexCoord[0].st + offset1 );
  aa += texture2D( Color0, gl_TexCoord[0].st + offset2 );
  aa += texture2D( Color0, gl_TexCoord[0].st + offset3 );
  aa.rgb *= 0.25;
  aa.a = min( ( aa.a + standard.a ), 1.0 );

  standard.rgb = mix( standard.rgb, aa.rgb, aa.a );

  // unsharp mask
  float blurLuma = dot( toLuma, glow );
  float unsharpMask = luma - blurLuma;
  standard.rgb += unsharpMask;

  // simulate blue shift of scotopic vision. 4x scale for tone mapping
  //vec3 nightshift = luma * vec3( 4.20, 3.88, 5.08 );
  vec3 nightshift = blurLuma * vec3( 4.20, 3.88, 5.08 );
  
  // clamp lower color to purple, use instead of black
  nightshift = max( nightshift, vec3( 0.141 , 0.09 , 0.157 ) );

  // nice sharp darks
  vec3 light = standard.rgb * 2.0 + glow * ( luma + 0.5 );
  // some additional glow, green is the most perceived, so similar to luma, 
  // also want greens to glow more from an artistic standpoint
  light += glow.ggg;

  float cmix = luma * 10.0;
  cmix = min( cmix, 1.0 );

  light = mix( nightshift, light, cmix );

  // do final tone mapping scale as last step, softens specular lighting
  float lluma = dot( toLuma, light );
  light /= 1.0+lluma;

  gl_FragColor = vec4( light, 1.0 );
}
