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

uniform float FadeAmount;

const vec3 toLuma = vec3(0.212671, 0.715160, 0.072169);

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 );
/**/  
  // ends up being a good edge detection filter
  vec3 norm0 = texture2D(Position, gl_TexCoord[1].st).xyz;
  vec3 norm1 = texture2D(Position, gl_TexCoord[2].st).xyz;
  vec3 norm2 = texture2D(Position, gl_TexCoord[3].st).xyz;
  vec3 norm3 = texture2D(Position, gl_TexCoord[4].st).xyz;
  norm0 = 2.0 * norm0 - 1.0;
  norm1 = 2.0 * norm1 - 1.0;
  norm2 = 2.0 * norm2 - 1.0;
  norm3 = 2.0 * norm3 - 1.0;

  float edge;
  edge  = dot(norm0, norm2);
  edge += dot(norm1, norm3);
  edge *= 0.5;
  edge  = min(edge, 1.0);

  // use blur along edge for anti-aliasing
  standard.rgb = mix(glow.rgb, standard.rgb, edge);

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

  // simulate blue shift of scotopic vision. 4x scale for tone mapping
  vec3 nightshift = luma * vec3(1.05, 0.97, 1.27);//blurLuma * vec3( 4.20, 3.88, 5.08 );//luma * 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 * (luma + 2.5);//standard.rgb * 2.0 + glow.rgb * ( 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 );

  // blend to nightshift under low lighting
  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;

  light.rgb = standard.rgb;//mix(nightshift, standard.rgb, smoothstep(0.01, 0.05, luma)); // 
  light *= 1.0 - FadeAmount; // control full screen fade to black

  //light += vec3(0.141, 0.09, 0.157);
  light = max(light, vec3( 0.141 , 0.09 , 0.157 ));
  gl_FragColor = vec4( light, 1.0 );
}


