/*******************************************************************
*	ColorFaceShaderShader.fx
*	Author - Pongthep Charnchaichujit
*	Created on - ?
*
*   All content © 2007 - 2008 DigiPen (USA) Corporation, all rights reserved.
*******************************************************************/
#include "Scene.h"

//CONSTANTS
float4x4 World;
float4x4 WorldViewProjection;

//Color
float4 DiffuseColor;
texture FaceTex;

// Settings controlling the Toon lighting technique.
float ToonThresholds[2] = { 0.8, 0.4 };
float ToonBrightnessLevels[3] = { 1.3, 0.9, 0.5 };

//STRUCTS
struct VS_IN {
	float4 pos : POSITION;
	float2 tex : TEXCOORD;
	float3 normal : NORMAL;
};

struct PS_IN {
	float4 pos : POSITION;
	float2 tex : TEXCOORD0;
	float3 normal : TEXCOORD1;
	float4 wpos : TEXCOORD2;
};

//face texture sampler
sampler FaceSampler = sampler_state
{
	texture = <FaceTex>;
	AddressU  = WRAP;
	AddressV  = WRAP;
	AddressW  = WRAP;
	MINFILTER = POINT;
	MAGFILTER = POINT;
};

//CelShader with color vertex shader
PS_IN CelShadedColorVertexShader(VS_IN input)
{
	PS_IN output;

	output.pos = mul(input.pos, WorldViewProjection);
	output.tex = input.tex;
	output.normal = mul(input.normal, (float3x3)World);
	output.wpos = mul(input.pos, World);

	return output;
}

//CelShader with color pixel shader
float4 CelShadedColorPixelShader(PS_IN input): COLOR
{	
	float3 normal = normalize(input.normal);
	float3 light_dir;
	float diffuse, diffuse_light = 0;
	
	float4 col = 0;

	for (int i=0; i<numLights; i++)
	{
		light_dir = normalize(Lights[i] - (float3)input.wpos);
		
		diffuse = saturate(dot(normal, light_dir));
		
		if (diffuse > ToonThresholds[0])
		{
			diffuse_light += ToonBrightnessLevels[0];
		}
		else if (diffuse > ToonThresholds[1])
		{
			diffuse_light += ToonBrightnessLevels[1];
		}
		else
		{
			diffuse_light += ToonBrightnessLevels[2];
		}
	}
	
	diffuse_light /= numLights;
	col = float4(DiffuseColor.xyz * diffuse_light, 1);

	return col;
}

//Diffuse with texture vertex shader
PS_IN FaceDiffuseVertexShader(VS_IN input)
{
	PS_IN output;

	output.pos = mul(input.pos, WorldViewProjection);
	output.tex = input.tex;
	output.normal = mul(input.normal, (float3x3)World);
	output.wpos = mul(input.pos, World);

	return output;
}

//with face texture on top of the base
float4 FaceDiffusePixelShader(PS_IN input): COLOR
{	
	return tex2D(FaceSampler, input.tex);
}

technique ColorFaceCelShaded
{
	pass BaseColor
	{
		VertexShader = compile vs_2_a CelShadedColorVertexShader();
		PixelShader = compile ps_2_a CelShadedColorPixelShader();
	}
	pass FaceTexture
	{
		AlphaBlendEnable = true;
		SrcBlend = BOTHSRCALPHA;
		VertexShader = compile vs_2_a FaceDiffuseVertexShader();
		PixelShader = compile ps_2_a FaceDiffusePixelShader();
	}
}