#version 430 core

uniform sampler2D gb_depth;
uniform vec2 viewport;

in vec3 normal;
in vec3 ec_pos;
in vec2 uv;
in vec4 extinction;
in vec3 inscatter;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#include <shading_model/atmosphere_include.frag>

#include <deferred/cascaded_shadow_include.frag>

void main()
{
	vec2 uv_view = gl_FragCoord.xy * viewport;
	float viewdepth = texture(depth, uv_view).x;
	vec3 pos = calc_position(uv_view, (viewdepth - 0.5)*2.0);
	if ( pos.z < ec_pos.z ) discard;

	vec3 ppos = calc_position(uv_pos, gl_FragCoord.z*2.0 - 1.0);
	float shadow_term = calculate_cascaded_shadow(viewDepth, ppos)*shadowParams.x + shadowParams.y;

	vec4 color = vec4(1.0);
	lightGroundAtmosphere(color, extinction, inscatter);
	color.rgb *= shadow_term;
	color.a = min(pos.z - ec_pos.z, 1.0);

	frag_color = color;
}
