#version 430 core

uniform sampler2D gb_diffuse;
uniform sampler2D gb_specular;
uniform sampler2D gb_normal;
uniform sampler2D gb_depth;
uniform sampler2D lightcolor;

uniform vec2 viewport;
uniform vec4 Params; // radius, bleed, intensity, falloff power
uniform float flicker;

in vec3 light_pos; //x,y,z
in vec3 normal;
in vec2 uv;
in float falloff;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#if 0
#include <shading_model/blinn_phong_model_include.frag>
#endif

#include <shading_model/strauss_model_include.frag>

void main()
{
	vec3 color = texture(lightcolor, uv).rgb * Params.z * flicker;

	vec2 uv_pos = gl_FragCoord.xy * viewport;
	vec4 diff = texture(gb_diffuse, uv_pos);
	vec4 spec = texture(gb_specular, uv_pos);
	vec4 norm = texture(gb_normal, uv_pos);
	float dpt = (texture(gb_depth, uv).x - 0.5)*2.0;

	//vec3 pos = calc_position(uv_pos, nd.w);
	vec3 pos = calc_position(uv_pos, dpt);
	if ( pos.z > light_pos.z ) discard;

	vec3 ld = light_pos.xyz - pos;
	float len = length(ld);

	float bleed = max(dot(normalize(normal), vec3(0.0, 0.0, 1.0)), Params.y) * pow(falloff, Params.w);
	vec3 lit = color.rgb * bleed;

	if ( len < Params.x )
	{
		ld = normalize(ld);
		vec3 n = normalize(norm.xyz);
		vec3 ed = normalize(-pos);
		float atten = 1.0 - (len / Params.x);
		vec3 terms = calculate_strauss_model(n, ld, ed, 0.1, 0.9, 0.0) * atten * bleed;

		lit += color*diff.rgb*terms.x + color*spec.rgb*(terms.y + terms.z);
		bleed += terms.x;
	}

	frag_color.rgb = lit;
	frag_color.a = bleed;
}
