uniform sampler falloff			: register(s0);
uniform sampler splat0			: register(s1);
uniform sampler splat1			: register(s2);
uniform sampler bumpmaps[8];

static const int NUM_LIGHTS = 2;

uniform float3 lightAmbient[NUM_LIGHTS];
uniform float3 lightDiffuse[NUM_LIGHTS];

uniform float4 wsPosCamera;
static float fDistMax = 1000;

struct VS_INPUT 
{
	float2 uv0							: TEXCOORD0;
	float4 shadowUV						: TEXCOORD1;
	float2 terrainUV					: TEXCOORD2;
	float3 tsLightDir					: TEXCOORD3;	//tangent space light direction
	float3 wsPos						: TEXCOORD6;
};

float4 main_ps( VS_INPUT input ) : COLOR0
{
	float4 outColor = float4(1, 1, 1, 1);

	float4 splatValues0 = tex2D( splat0, input.terrainUV );
	float4 splatValues1 = tex2D( splat1, input.terrainUV );
	
	// the perturbed normal from bumpmaps
	float3 pn = float3(0.0f, 0.0f, 0.0f);

	float fSum = 	splatValues0.a + splatValues0.b + splatValues0.g + splatValues0.r +
					splatValues1.a + splatValues1.b + splatValues1.g + splatValues1.r;
	
	pn = lerp( pn, tex2D( bumpmaps[0], input.uv0 ).xyz*2.0f - 1.0f, splatValues0.a/fSum);
	pn = lerp( pn, tex2D( bumpmaps[1], input.uv0 ).xyz*2.0f - 1.0f, splatValues0.b/fSum);
	pn = lerp( pn, tex2D( bumpmaps[2], input.uv0 ).xyz*2.0f - 1.0f, splatValues0.g/fSum);
	pn = lerp( pn, tex2D( bumpmaps[3], input.uv0 ).xyz*2.0f - 1.0f, splatValues0.r/fSum);

	// [AS] can't have bumpmapping for the texture variations ( patches ) as we'd exceed the PS2.0 instruction limit		
	pn = lerp( pn, tex2D( bumpmaps[4], input.uv0 ).xyz*2.0f - 1.0f, splatValues1.a/fSum);
	pn = lerp( pn, tex2D( bumpmaps[5], input.uv0 ).xyz*2.0f - 1.0f, splatValues1.b/fSum);
	pn = lerp( pn, tex2D( bumpmaps[6], input.uv0 ).xyz*2.0f - 1.0f, splatValues1.g/fSum);
	pn = lerp( pn, tex2D( bumpmaps[7], input.uv0 ).xyz*2.0f - 1.0f, splatValues1.r/fSum);

	pn.x *= 0.75f;
	pn.y *= 0.75f;

	float3 normal = normalize( pn );
	float3 lightDir = normalize( input.tsLightDir );
	float nDotL = dot(normal, lightDir);
	float3 l = lightAmbient[0] + lightDiffuse[0] * max( 0, nDotL );
	outColor.rgb = saturate( l + l );

	float fDist = distance( input.wsPos, wsPosCamera );
	float3 fBrightness = tex1D( falloff, fDist/fDistMax ); 
	outColor.rgb *= fBrightness;

	return outColor;
}
