uniform float4x4 	matWorld;
uniform float4x4 	matViewProjection;
uniform float4x4	matInvWorld;
uniform float3x4	matArrayBones[60];
uniform float3		msCamPos;

static const int  BONES_PER_VERTEX = 4;
static const int  NUM_LIGHTS = 2;
static float fDistMax = 1000;

struct VS_INPUT 
{
	float4 position		: POSITION0;
	float2 uv			: TEXCOORD0;
	float3 normal 		: NORMAL0;
	float3 tangent		: TANGENT0;
	
	float4 blendIdx		: BLENDINDICES;
	float4 blendWeight	: BLENDWEIGHT;
};

struct VS_OUTPUT 
{
	float4 position 					: POSITION0;
	float2 uv		 					: TEXCOORD0;
	float3 tsViewDirection 				: TEXCOORD1;
	float3 tsLightDirection[NUM_LIGHTS]	: TEXCOORD2;
	float  fDistance					: TEXCOORD5;
};

uniform float3 wsLightDir[NUM_LIGHTS];

VS_OUTPUT main_vs( VS_INPUT input )
{
	VS_OUTPUT output;
	
	output.uv = input.uv;
	
	// transform by indexed matrix
    float4 blendedPos = float4(0,0,0,0);
    for ( int i = 0; i < BONES_PER_VERTEX; ++i)
    {
         blendedPos += float4( mul(matArrayBones[ input.blendIdx[i] ], input.position ).xyz, 1.0 ) * input.blendWeight[i];
    }

	output.position = mul( matViewProjection, blendedPos );

     float3 wsNormal = float3(0,0,0);
     for (int i = 0; i < BONES_PER_VERTEX; ++i)
     {
         wsNormal += mul( (float3x3)matArrayBones[ input.blendIdx[i] ], input.normal) * input.blendWeight[i];
     }

     float3 wsTangent = float3(0,0,0);
     for (int i = 0; i < BONES_PER_VERTEX; ++i)
     {
         wsTangent += mul( (float3x3)matArrayBones[ input.blendIdx[i] ], input.tangent) * input.blendWeight[i];
     }
    
	// build a tangent space basis
	float3 msTangent = normalize( mul((float3x3)matInvWorld, wsTangent) ); 
	float3 msNormal = normalize( mul( (float3x3)matInvWorld, wsNormal) ); 
	float3 msBinormal = normalize( cross(msTangent, msNormal) );
	float3x3 rotation = float3x3( msTangent, msBinormal, msNormal);

	float3 tmp =  normalize(input.position - float4(msCamPos,0)).xyz;
	output.tsViewDirection =  normalize( mul(rotation, tmp) ).xyz;

	for (int i = 0; i < NUM_LIGHTS; i++)
	{
		float3 msLightDir = mul( matInvWorld, wsLightDir[i] ).xyz;
		output.tsLightDirection[i] = normalize( mul(rotation, msLightDir) ).xyz;	
	}

	float fDist = distance( msCamPos.xyz, input.position.xyz );
	output.fDistance = fDist / fDistMax; 

	return output;
}
