
#define MapScale Arg[0].xy
#define MapOffset Arg[0].zw

// 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;
	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 );
	
	// Generate texture coordinates
	output.Tex.xy = (output.Pos_WorldSpace.xz + MapOffset) / MapScale;
	output.Tex.zw = output.Pos_WorldSpace.xz / 16;
	
	// 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 to tex_1 are diffuse textures

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PS( VS_to_PS input) : SV_Target {
	// Get the dimensions of the texture
	uint2 Dimensions; uint Levels;
	tex_0.GetDimensions(0,Dimensions.x,Dimensions.y,Levels);
	
	// Scale from UV to pixel coordinates
	float2 PixelCoord = (input.Tex.xy * Dimensions) - 0.5f;
	
	int2 LowPixel = clamp(floor(PixelCoord), 0, Dimensions - 1);
	int2 HighPixel = clamp(LowPixel + 1, 0, Dimensions - 1);;
	
	float2 Sharpness = clamp(100.0f / length(input.Pos_CameraSpace),0.0f,20.0f);
	float2 SharpFrac = saturate(lerp(-Sharpness, 1.0f + Sharpness,frac(PixelCoord)));
	
	float4 LXLY = tex_0.Load(int3(LowPixel.x, LowPixel.y, 0));
	float4 LXHY = tex_0.Load(int3(LowPixel.x, HighPixel.y, 0));
	float4 HXLY = tex_0.Load(int3(HighPixel.x, LowPixel.y, 0));
	float4 HXHY = tex_0.Load(int3(HighPixel.x, HighPixel.y, 0));
	return lerp(lerp(LXLY,HXLY,SharpFrac.x),lerp(LXHY,HXHY,SharpFrac.x),SharpFrac.y) * tex_1.Sample( samAnisotropicMipmap, input.Tex.zw ) * input.Color;
	
	//return tex_0.Sample( samClampedConstant, input.Tex.xy ) * tex_1.Sample( samAnisotropicMipmap, input.Tex.zw ) * input.Color;
}
