// ambient (and apparently directional light, too) pass
#version 120

uniform sampler2D tex_diffuse;
uniform sampler2D tex_normal;
uniform sampler2D tex_depth;

uniform vec2    res_r;
uniform vec3    depth_range;
uniform vec3    light_vec;
uniform vec3    fov_modifier;

/// mangles the depth texture's contents into actual depth values
float readDepth(in vec2 coord) {
    float sample = ((texture2D(tex_depth, coord).x * 2.0) - 1.0);
    return depth_range.z / (sample * (depth_range.y - depth_range.x)
                            - (depth_range.y+depth_range.x));
}
void main(){
    vec2 tex_coord = gl_FragCoord.xy * res_r;

    vec3 ns = texture2D(tex_normal, tex_coord).xyz;
    vec3 normal = normalize((ns - vec3(0.5, 0.5, 0.5)) * vec3(2.0,2.0,2.0));
    vec3 eye_vec = vec3(tex_coord * 2.0 - vec2(1,1), -1.0) * fov_modifier;

    vec4 l_vert = vec4(1.0, 0.7, 0.3, 0.0) * 2.5;
    vec4 l_horz = vec4(0.3, 0.4, 0.5, 0.0) * 0.7;

    vec3 half_vec = light_vec-eye_vec;

    vec4 specular = vec4(1.4, 1.0, 0.7, 0.70) * pow(max(dot(normalize(half_vec), normal), 0.0), 70.0);

    gl_FragColor = texture2D(tex_diffuse, tex_coord) * (mix(l_horz, l_vert, max(dot(normal, light_vec), 0.0)) + specular * 1.5);

    gl_FragColor = mix(gl_FragColor, vec4(0.5, 0.6, 0.7, 0.0) * 0.05, readDepth(tex_coord)/depth_range.y);
}
