#version 430 core

uniform sampler2D gb_diffuse;
uniform sampler2D gb_specular;
uniform sampler2D gb_normal;
uniform sampler2D gb_depth;
uniform vec2 viewport;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#include <shading_model/atmosphere_include.frag>

#include <shading_model/material_model_include.frag>

#include <shading_model/light_equation.frag>

void main()
{
	vec2 uv = gl_FragCoord.xy * viewport;
	vec4 diff = texture(gb_diffuse, uv);
	vec4 spec = texture(gb_specular, uv);
	vec3 n = normalize( texture(gb_normal, uv).xyz );
	float dpt = (texture(gb_depth, uv).x - 0.5)*2.0;
	//vec3 pos = calc_position(uv, nd.w);
	vec3 pos = calc_position(uv, dpt);

	vec3 ld = normalize(SunDirection);
	vec3 ed = normalize(-pos);

	vec4 extinction;
	vec3 inscatter;
	calculateGroundAtmosphere(pos, n, extinction, inscatter);

	vec3 terms = calculate_material_model(n, ld, ed, spec.a);

	vec4 color;
	//color.rgb = diff.rgb*terms.x + spec.rgb*terms.y + diff.rgb*vec3(0.5, 0.5, 1.0)*terms.z;
	color.rgb = lightEquation(diff.rgb, spec.rgb, diff.rgb, terms);
	color.a = 1.0;
	lightGroundAtmosphere(color, extinction, inscatter);

	frag_color = vec4(color.rgb, SunPosition.x*0.00000000000001);
}
