#version 330 core

uniform mat4 TextureMatrix;
uniform sampler2D diffuse_specular;
uniform sampler2D normal_depth;
uniform sampler2D depth;
uniform samplerCube cubemap;
uniform vec2 viewport;

in vec4 light_pos;
in vec3 color;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_include.frag>

#include <shading_model/blinn_phong_model_include.frag>

void main()
{
	vec2 uv = gl_FragCoord.xy * viewport;
	vec4 ds = textureLod(diffuse_specular, uv, 0.0);
	vec4 nd = textureLod(normal_depth, uv, 0.0);

	vec3 pos = calc_position(uv, nd.w);

	vec3 ld = light_pos.xyz - pos;
	float len = length(ld);
	if ( len > light_pos.w ) discard;

	ld = normalize(ld);

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

	vec3 cn = normalize( vec3(TextureMatrix * vec4(pos, 1.0)) );
	cn.y = -cn.y;
	vec3 cubecolor = textureLod(cubemap, cn, 0.0).rgb*color;
	//vec3 cubecolor = texture(cubemap, cn).rgb*color;

	float atten = 1.0 - (len / light_pos.w);
	vec3 terms = calculate_blinn_phong_model(n, ld, ed, 8.0)*atten;

	frag_color.rgb = cubecolor*ds.rgb*terms.x + cubecolor*ds.a*terms.y;
	frag_color.a = 0.0; //terms.x;
}
