#version 430 core

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

in vec3 light_start;
in vec3 light_end;
in vec2 light_coeff; // radius, width
in vec3 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>

vec4 point_line_intersection( in vec3 pos )
{
	vec3 a = light_end - light_start;
	vec3 b = pos - light_start;
	float mag = length( a );
	float u = dot( a, b ) / (mag*mag);
	if ( u < 0.0 || u > 1.0 ) return vec4( pos, 0.0 );
	return vec4( light_start + a*u, u );
}

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

	vec4 isect = point_line_intersection( pos );
	vec3 ld = isect.xyz - pos;
	float len = length(ld);
	if ( len > light_coeff.x ) discard;

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

	float atten = 1.0 - (len / light_coeff.x);
	atten *= smoothstep(0.0, 0.25, isect.w) - smoothstep(0.75, 1.0, isect.w);

	//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.rgb = color*diff.rgb*terms.x + color*spec.rgb*terms.y;
	frag_color.a = terms.x;
}
