Code Snippet: Clipping Planes in Shader [HLSL]



In the XNA 4.0 we dont have anymore the Fixed function that let us specify a clipping plane. Now we have to do this in shaders =P. In this post i will show how to do this !

The following code shows how to implement ONE clipping plane in Projection Space. (same as the fixed pipeline)

If you want more than one plane, just use the Y,Z,W coordinates from the clipping variable to put the others values. If you want to use the plane in World or View space, just make the “dot” with the position in the right space.

The theory for this is simple. The dot operation evaluates the plane equation and the result give us in what side of the plane the position is. For more info check this.

float4x4 WVP;
float4 clippingPlane;
bool isClip;

Texture diffuse;
sampler DiffuseSampler = sampler_state
{
texture =  ;
magfilter = ANISOTROPIC;
minfilter = ANISOTROPIC;
mipfilter = LINEAR;
AddressU = wrap;
AddressV = wrap;
};

struct VertexShaderInput
{
float3 Position : POSITION0;
float4 texturecoord :  TEXCOORD0;
};

struct VertexShaderOutput
{
float4 Position : POSITION0;
float4 texturecoord :  TEXCOORD0;
float4 clipping :  TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;
output.Position = mul(float4(input.Position,1), WVP);
output.texturecoord = input.texturecoord;
output.clipping = 0;
float4 clp = output.Position;
output.clipping.x = dot(clp,clippingPlane) ;
return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
if(isClip)
clip(input.clipping.x);

return tex2D(DiffuseSampler, input.texturecoord);
}

technique Technique1
{
pass Pass1
{
VertexShader = compile vs_2_0 VertexShaderFunction();
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}

, , , , , ,