#version 430 core

uniform sampler2D gb_diffuse;
uniform sampler2D gb_specular;
uniform sampler2D gb_normal;
uniform sampler2D gb_depth;
uniform vec2      viewport;

in vec4 light_plane;
in vec3 light_pos;
in vec3 light_coeff; // size, length, intensity
in vec3 light_color;

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>


float point_plane_intersection( in vec3 pos )
{
	float dist = dot(light_plane.xyz, pos) + light_plane.w;
	if ( dist < 0.0 )
	{
		return -1.0;
	}
	else
	{
		vec3 isect = pos - light_plane.xyz*dist;
		vec3 pn = light_pos - isect;
		float s = min( length( light_pos - isect ), light_coeff.x ) / light_coeff.x;
		float l = min( dist, light_coeff.y ) / light_coeff.y;
		return (1.0 - pow(s, 8.0)) * (1.0 - pow(l, 8.0));
	}
}

void main()
{
	vec2 uv_pos = gl_FragCoord.xy * viewport;
	vec4 diff = texture2D(gb_diffuse, uv_pos);
	vec4 spec = texture2D(gb_specular, uv_pos);
	vec4 norm = texture2D(gb_normal, uv_pos);
	float dpt = (texture(gb_depth, uv_pos).x-0.5)*2.0;
	//vec3 pos = calc_position(uv_pos, nd.w);
	vec3 pos = calc_position(uv_pos, dpt);

	float atten = point_plane_intersection(pos);
	if ( atten < 0.0 ) discard;

	vec3 n = normalize(norm.xyz);
	vec3 ed = normalize(-pos);
	vec3 ld = normalize(light_pos.xyz - pos);

	//vec3 terms = calculate_blinn_phong_model(n, ld, ed, 8.0) * atten;
	vec3 terms = calculate_strauss_model(n, ld, ed, 0.1, 0.9, 0.0) * atten;

	frag_color.xyz = diff.xyz*light_color*terms.x + light_color*spec.rgb*terms.y;
	frag_color.w = terms.x;
}
