
// You may modify this to move more data from the vertex shader to the pixel shader.
// It needs at least the position to work.
struct VS_to_PS {
	float4 Pos : SV_POSITION;
	float4 Tex : TEXCOORD0;
	float4 Color : COLOR;
	float3 Normal_WorldSpace : NORMAL;
	float4 Pos_WorldSpace : TEXCOORD1;
	float4 Pos_CameraSpace : TEXCOORD2;
};

//--------------------------------------------------------------------------------------
// Vertex Shader
//--------------------------------------------------------------------------------------
VS_to_PS VS( VS_structure input ) {
	VS_to_PS output = (VS_to_PS)0;
	
	// Convert vertice positions from object space to world space
	output.Pos_WorldSpace = mul( input.Pos, ObjectToWorld );
	// Convert vertice positions from world space to camera space
	output.Pos_CameraSpace = mul( output.Pos_WorldSpace, WorldToCamera );
	// Convert vertice positions from camera space to 2D projection
	output.Pos = mul( output.Pos_CameraSpace, CameraToImage );
	
	// Transform normals to world space
	output.Normal_WorldSpace = mul(input.Normal,(float3x3)ObjectToWorld);
	
	// Give the texture coordinates to the pixel shader
	output.Tex = input.Tex;
	
	// Give the vertex color multiplied with the instance color to the pixel shader
	output.Color = lerp(input.Color * InstanceColor, float4(0.0f,0.0f,1.0f,1.0f), input.Selected);
	
	return output;
}

//tex_0 is the blend map using UV2
//	Red show tex_1, green show tex_2, blue show tex_3 and black show tex_4
//tex_1 to tex_4 are diffuse textures using UV1

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PS( VS_to_PS input) : SV_Target {
	// If the camera has a world space cutting plane, clip on the negative side.
	UseCuttingPlane(input.Pos_WorldSpace)
	
	// Sample all maps
	float3 Blend = tex_0.Sample( samAnisotropicMipmap, input.Tex.zw ).rgb;
	float3 RedMap = tex_1.Sample( samAnisotropicMipmap, input.Tex.xy ).rgb;
	float3 GreenMap = tex_2.Sample( samAnisotropicMipmap, input.Tex.xy ).rgb;
	float3 BlueMap = tex_3.Sample( samAnisotropicMipmap, input.Tex.xy ).rgb;
	float3 BlackMap = tex_4.Sample( samAnisotropicMipmap, input.Tex.xy ).rgb;
	
	float3 DiffuseLight;
	Engine_GetDiffuseLight(input.Pos_WorldSpace,normalize(input.Normal_WorldSpace),DiffuseLight);
	float4 finalColor = float4(((RedMap * Blend.r) + (GreenMap * Blend.g) + (BlueMap * Blend.b) + (BlackMap * (1 - (Blend.r + Blend.g + Blend.b)))) * input.Color * DiffuseLight,1.0f);
	
	// Show the final color with fog on R,G,B channels
	return float4((lerp(finalColor,FogColor,saturate(length(input.Pos_CameraSpace) / FogDistance) * MaxFogIntensity)).xyz,finalColor.w);
}
