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

//test shader to calculate luminance value of player

#version 150

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

//light variables
uniform vec3			uLightPos; //viewspace light position
uniform vec3			uTarget; //viewspace light target

uniform vec4			uDiffuse; //diffuse component
uniform vec3			uAtten; //attenuation
uniform float			uIntensity; //light intensity

uniform float			uCosInnerAngle; //cosine of spotlight inner angle
uniform float			uCosOuterAngle; //cosine of spotlight outer angle
uniform float			uFalloff; //spotlight falloff

uniform bool			uCastShadow; 

// ---------------------------------------------------------------------------
// from vertex shader

in vec3					vPixelPos;	

// ---------------------------------------------------------------------------
// const

const vec4				LUMINANCE = vec4( 0.2126, 0.7152, 0.0722, 0.0 );

// ---------------------------------------------------------------------------
// function declarations

float					calcShadow( in vec3 viewSpacePos ); //passing in world space pos

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

out vec4				out_Color;

void main()
{	
	//get the surface-to-light ray (world space)
	vec3 lightVec = uLightPos - vPixelPos;
		
	//---------------------------------------------------------------
	//calculate distance attenuation factor
		
	float d = length( lightVec ); //distance from light to this pixel
	lightVec = normalize( lightVec );
	d = min( 1.0/( uAtten.x + uAtten.y * d + uAtten.z * d * d ), 1.0 ); 
	
	float nl = max( dot( vec3(0.0, 1.0, 0.0), lightVec ), 0.0 ); //normal.lightVec. Always assume normal is positive y vec

	//---------------------------------------------------------------
	//calculate spotlight effect
	
	float e = 1.0;
	vec3 dirVec = normalize( uTarget - uLightPos ); //direction vector of spotlight
	float ld = max( dot( dirVec, -lightVec ), 0.0 );
			
	if ( ld < uCosOuterAngle )
	{
		//outside outer cone, no spotlight effect
		e = 0.0;
	}
	else
	{
		if ( ld <= uCosInnerAngle )
		{
			//interpolate
			e = pow( (ld - uCosOuterAngle)/(uCosInnerAngle - uCosOuterAngle), uFalloff );
		}
		//else inside inner cone, receive max light
	}

	d *= e;

	//----------------------------------------------------------------
	//add shadow occlusion

	if ( uCastShadow )
		d *= calcShadow( vPixelPos );

	//----------------------------------------------------------------
	//calculate light value

	//calculate light color and then convert from RGB to luminance
	//G is the pixel counter
	out_Color += vec4( dot(LUMINANCE, uDiffuse * nl * d * uIntensity), 1.0, 0.0, 0.0 );
}
