![]() |
![]() |
![]() |
Applications use the stencil buffer to determine whether a pixel is written to the rendering target surface. For details, see Stencil Buffer Techniques.
To enable stencil testing, use:
pDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
To set the comparison function that the stencil testing uses to accept or reject pixels, use a member of D3DCMPFUNC like this:
pDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL);
To set the reference value used in the comparison, use:
pDevice->SetRenderState(D3DRS_STENCILREF, 0);
By default, the stencil reference value is zero. Any integer value is valid.
To set the stencil mask, use:
pDevice->SetRenderState(D3DRS_STENCILMASK, 0);
Microsoft Direct3D performs a bitwise AND of the stencil reference value and a stencil mask value before the stencil test.
You can control what pixel information is output depending on the stencil comparison. For instance, to set what happens to stencil buffer data when the stencil test fails, use:
pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
to keep the information in the stencil buffer unchanged if the stencil test fails. Use D3DRS_STENCILZFAIL instead, if you want to control the z-buffer if the z-buffer test fails.
You can write your own formula for the value you want written into the stencil buffer. For instance, you could use the write mask, the stencil-op, and the stencil buffer value as shown here:
NewStencilBufferValue = (StencilBufferValue & ~StencilWriteMask) | (StencilWriteMask & StencilOp(StencilBufferValue))
Naturally, the stencil operation will depend on the render states that are set.
Lastly, use a write mask to control what is written to the stencil buffer like this:
pDevice->SetRenderState(D3DRS_STENCILWRITEMASK, D3DSTENCILOP_KEEP);