uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform sampler2D texPos;
varying vec3 eye,light;

uniform mat4 modelview;
uniform mat4 projection;
                 
void main(void)
{
  vec3 useColor = vec3(1.0, 0.2, 0.0);
  vec3 halfv;
  float ndotl;
  
  //vec3 backgroundColor = vec4(47.0 / 255.0, 96.0 / 255.0, 163.0 / 255.0,1);
  vec4 backgroundColor = vec4(1.0, 1.0, 1.0, 0.0);

	vec4 col, texel = texture2D(tex0, gl_TexCoord[0].st);
  
  vec4 depth = texture2D(tex2, gl_TexCoord[0].st);
  
  vec3 pos = (texture2D(texPos, gl_TexCoord[0].st).xyz - 0.5) * 2.0 * 1.0;
  
  vec3 n;
  
  useColor = texture2D(tex1, gl_TexCoord[0].st);


  n = (texel.xyz - 0.5) * 2.0;
 
  if (length(n) > 1.01)
  {
    gl_FragColor = backgroundColor;
    return;
  }
  
  //gl_FragColor = texel;
  //return;

  n = normalize(n);
	/*halfv = normalize(eye+light);
	ndotl = clamp(dot(n,halfv), 0.0, 1.0);*/
  
  vec3 lightDir = normalize(light);
  float lamb = max(dot(lightDir, n), 0.0);
  float spec = 0.0;

  if (lamb > 0.0)
  {
    //vec3 viewDir = normalize(-pos);
    vec3 viewDir = vec3(0,0,0);

    vec3 halfDir = normalize(lightDir + viewDir);
    float specAngle = max(dot(halfDir, n), 0.0);
    spec = pow(specAngle, 90.0);
  }
  
  ndotl = lamb;
  

//useColor = vec3(0.8,0,0);
			
  col = vec4(vec3(useColor.r+ndotl*0.2,useColor.g+ndotl*0.3,useColor.b+ndotl*0.5)*max(ndotl,0.625),1.0);
  col = vec4(useColor * lamb, 1.0);
  
  //col = vec4(useColor * max(ndotl,0.1),1.0);
      
	//col=mix(vec4(0.0,0.0,0.1,1),col,clamp(300*ao*ao*ao,0.3,1.));
      
	//col=mix(col,vec4(1.0, 1.0, 0.8, 1.0),/*pow(ndotl,90.0)*/ spec);
  col += vec4(1.0, 1.0, 0.8, 1.0) * spec * 0.3;
    
  //col = vec4(vec3(ndotl) * useColor, 1.0);
  
  //col = vec4(useColor, 1.0);
  
  col = clamp(col, 0.0, 1.0);
  
  
  vec4 avgD = vec4(0);
  float counter = 0.0;
  
  for (int i = -7; i <= 7; i+=2)
  {
    for (int j = -7; j <= 7; j+=2)
    {
        avgD += texture2D(tex2, gl_TexCoord[0].st + vec2(i, j) * 0.004);
        counter++;
    }
  }
  avgD /= counter;
  
  float ssao = 1.0 - /*abs*/(avgD - depth);
  ssao = min(1.0, max(0.0, ssao));
  ssao = pow(ssao, 4.0);
  //ssao = 1.0;
  
  float fog = min(1.0, pow(depth.r * 5.0,1.0));  
  //fog = 1.0; 
  
  //col.rgb = useColor.rgb;
  

  //col.rgb = mix(backgroundColor.rgb, col.rgb, fog);  
  //col.rgb = mix(backgroundColor*0.0, col.rgb, ssao);  

  //gl_FragColor = vec4(vec3(pow(n.rgb, vec3(0.1))), 1.0);
  
  gl_FragColor = vec4(col);
  
  //gl_FragColor = vec4(lightDir, 1.0);
  
  vec4 ssn = projection * modelview * vec4(n,1.0);
  
  //gl_FragColor = vec4(vec3(0.5 + 0.5 * n), 1.0);
  
  //gl_FragColor = vec4(vec3(ssao), 1.0);
  
  //gl_FragColor = depth;
  //gl_FragColor = vec4(useColor, 1.0);
  
  //gl_FragColor = vec4(texel.xyz, 1);
}
