#version 330 core

uniform sampler2D diffuse_specular;
uniform sampler2D normal_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_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 ds = texture(diffuse_specular, uv_pos);
	vec4 nd = texture(normal_depth, uv_pos);

	vec3 pos = calc_position(uv_pos, nd.w);
	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(nd.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*ds.rgb*terms.x + color*ds.a*(terms.y + terms.z);
		bleed += terms.x;
	}

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