// All content © 2010-2011 DigiPen (USA) Corporation, all rights reserved.

//shader to render a point light's properties into the light buffer.

#version 150

// ---------------------------------------------------------------------------
//uniforms

//light variables
uniform vec3		uLightPos; //viewspace light position
uniform float		uRadius; //light radius
uniform float		uSpecular; //specular component 
uniform vec4		uDiffuse; //diffuse component
uniform float		uIntensity; //light intensity

uniform sampler2D	uGBuffer; //geometry buffer storing depth + normals

uniform float		uCamFarPlane; //scene camera far plane

// ---------------------------------------------------------------------------
// varyings

in vec3				vViewPos; //view space position	

// ---------------------------------------------------------------------------

out vec4			out_Color;

void main()
{
	vec4 nrmDepth = texelFetch( uGBuffer, ivec2( gl_FragCoord.xy ), 0 );

	//reconstruct pixel position from depth and get the surface-to-light ray: frustum ray * depth
	//frustum ray = viewPos * ( camFarPlane/viewPos.z )
	vec3 pixelPos = vViewPos * ( uCamFarPlane/-vViewPos.z * nrmDepth.a );
	vec3 lightVec = uLightPos - pixelPos; //eyescreenray * normalized view space depth
		
	//---------------------------------------------------------------
	//calculate distance attenuation factor
		
	float l = length( lightVec ); //distance from light to this pixel
	
	//	out_Color = vec4( diffuse_color.rgb, specular_component ) * attenuation * light_intensity

	out_Color = vec4( (uDiffuse * max( dot(nrmDepth.rgb, lightVec/l), 0.0 ) ).rgb, //diffuse * nl
					pow( clamp( dot( normalize(reflect(lightVec, nrmDepth.rgb)), normalize(pixelPos) ), 0.0, 1.0), uSpecular ) ) //specular
				* clamp( 1.0 - l/uRadius, 0.0, 1.0 ) 
				* uIntensity;
}
