#version 410 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;
in vec3 normal;
in vec2 uv;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

#include <shading_model/blinn_phong_model_include.frag>


void main()
{
	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);

	vec2 rfuv = uv + reflect(nd.xyz, normal).xy*vec2(16.0/64.0, 64.0/512.0);
	vec3 color = texture(lightcolor, uv).rgb * flicker;
	vec3 reflColor = texture(lightcolor, rfuv).rgb * Params.z * flicker;
	vec3 lit = color.rgb * Params.y;

	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_blinn_phong_model(n, ld, ed, 32.0) * atten;
		lit += reflColor*ds.rgb*terms.x + reflColor*ds.a*(terms.y + terms.z);
	}

	frag_color.rgb = lit;
	frag_color.a = Params.y;
}
