Textures are loaded in to an XNA project just like any other content pipeline asset.
atexture = content.Load("china") as Texture2D; ... //pass the texture to the shader effect.Parameters["myTexture"].SetValue(atexture);
In the shader code the texture is passed as an external parameter. The texture is used to create a 'sampler', which will be used to sample the shader at the texture coodrdinates
//shader code, both of these items are declared globally in the .fx file
uniform extern texture myTexture;
sampler textureSampler = sampler_state
{
Texture = <myTexture>;
};
In the most basic case, to render a texture, all the vertex shader needs to do is to pass the recived texture coordinates to the pixel shader;
struct VS_OUTPUT
{
float4 position : POSITION;
float4 textcoord: TEXCOORD0;
};
VS_OUTPUT Transform(
float4 Pos : POSITION,
float4 textcoord:TEXCOORD0,
)
{
VS_OUTPUT Out = (VS_OUTPUT)0;
Out.position = mul(Pos, WorldViewProj);
Out.textcoord=textcoord;
return Out;
}
The pixel shader needs to look-up the texture at the given texture coordinates to determine the colour of the pixel using the tex2D function and the previously defined sampler.
void PixelShader( float4 textureCoordinate : TEXCOORD0, out float4 col:COLOR)
{
col=tex2D(textureSampler, textureCoordinate);
}
uniform extern float4x4 WorldViewProj : WORLDVIEWPROJECTION;
uniform extern texture myTexture;
struct VS_OUTPUT
{
float4 position : POSITION;
float4 textcoord: TEXCOORD0;
};
sampler textureSampler = sampler_state
{
Texture =<myTexture>;
};
VS_OUTPUT Transform(
float4 Pos : POSITION,
float4 textcoord:TEXCOORD0
)
{
VS_OUTPUT Out = (VS_OUTPUT)0;
Out.position = mul(Pos, WorldViewProj);
Out.textcoord=textcoord;
return Out;
}
void PixelShader( float4 textureCoordinate : TEXCOORD0, out float4 col:COLOR)
{
col=tex2D(textureSampler, textureCoordinate);
}
technique TransformTechnique
{
pass P0
{
vertexShader = compile vs_2_0 Transform();
pixelShader = compile ps_1_1 PixelShader();
}
}
A sampler is an abstraction of a texture and sample states. E.g this sample sets the sample states to binlinear filtering (the default filtering is POINT filtering.
sampler Sampler = sampler_state
{
Texture = <myTexture>;
MipFilter = LINEAR;
MinFilter = LINEAR;
MagFilter = LINEAR;
};