#version 330 core

uniform sampler2D diffuse_specular;
uniform sampler2D normal_depth;
uniform sampler2D depth;
uniform sampler2D lightcolor;

uniform vec2 viewport;
uniform vec4 Params; // radius, bleed, offset.xy
uniform float AlphaTest;
uniform float Smoothness;

in vec3 light_pos; //x,y,z
in vec2 uv;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_include.frag>

void main()
{
	const float SPECULAR_POWER = 8.0;

	vec2 uv2 = uv + Params.zw;
	vec4 color = texture(lightcolor, uv2);
	//if ( color.a > AlphaTest ) discard;

	//color.rgb *= color.a;

	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 light_dir = light_pos.xyz - pos;
	float len = length(light_dir);

	light_dir = normalize( light_dir );
	vec3 normal = normalize(nd.xyz);
	float NdotL = dot(normal, light_dir);

	float alpha = 1.0; //clamp((light_pos.z - pos.z)*Smoothness, 0.0, 1.0);
	vec3 lit = color.rgb*Params.y;
	if ( NdotL > 0.0 && (len < Params.x) )
	{
		float atten = 1.0 - (len / Params.x);
		vec3 half_vector = normalize(reflect(normalize(pos), light_dir));
		float NdotHV = max(dot(normal, half_vector), 0.0)*NdotL;

		vec2 uv_offset = light_dir.xy*atten*(8.0/512.0);
		vec3 lcolor = texture(lightcolor, uv2 - uv_offset).rgb;
		lit += (lcolor.rgb*ds.rgb*NdotL + lcolor.rgb*ds.a*pow(NdotHV, SPECULAR_POWER))*atten;
	}
	frag_color = vec4(1.0); //vec4(lit*alpha, 1.0);
}
