#version 430 core

uniform sampler2D clouds;
uniform sampler2D noise;
uniform sampler2D gb_depth;
uniform vec2 viewport;

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

layout (location = 0) out vec4 frag_color;

#include <shading_model/atmosphere_include.frag>

#include <deferred/gbuffer_read_include.frag>

void main()
{
	const vec3 light = vec3(1.0);
	const vec3 dark = vec3(0.75);

	vec2 uv_pos = gl_FragCoord.xy * viewport;
	float d = (texture(gb_depth, uv_pos).x - 0.5)*2.0;
	vec3 pos = calc_position(uv_pos, d);
	if ( pos.z > ec_pos.z ) discard;

	float NdotL = max(dot(normalize(-normal.xyz), SunDirection), 0.0);

	float depth = texture(clouds, uv).r * pow(texture(noise, uv_noise).r, 2.0);

	float shade = 1.0 - smoothstep(0.0, 0.75, depth);//*0.5;
	float shadeVariance = (texture(noise, uv.yx*2.0).r + texture(noise, uv_noise*2.0).r)*0.5;
	shade *= pow(shadeVariance, 2.0);

	vec4 color = vec4(mix(dark,light,shade)*shade*NdotL, smoothstep(0.0, 0.15, depth)*0.8);
	float alpha = color.a*normal.w;
	lightCloudAtmosphere(color, extinction, inscatter);

	frag_color.rgb = color.rgb;
	frag_color.a = alpha * clamp((ec_pos.z - pos.z)/4.0, 0.0, 1.0);
}
