Platform SDK: DirectX

Step 4: Enable Depth Buffering

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After attaching the depth buffer to the render-target surface, you can create a rendering device from the render target.

If your application uses a depth buffer you will need to clear both the viewport and the depth buffer. To clear the depth buffer, specify the D3DCLEAR_ZBUFFER flag in the IDirect3DDevice7::Clear method.

    pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
                       0x000000ff, 1.0f, 0L );

Given a rendering device, you enable depth buffering by setting the D3DRENDERSTATE_ZENABLE render state for the device. The D3DZBUFFERTYPE enumerated type includes members to set the depth-buffer render state. The D3DZB_TRUE member (or TRUE) enables z-buffering. The ZBuffer sample enables z-buffering during scene rendering in the App_Render application-defined function. The following is the appropriate excerpt from App_Render:

    // Enable z-buffering. (Note: we don't really need to do this every frame.)
    pd3dDevice->SetRenderState( D3DRENDERSTATE_ZENABLE, TRUE );

Although this tutorial enables depth-buffering each frame, it is not necessary to do so. A real-world application would likely set the D3DRENDERSTATE_ZENABLE render state during scene initialization, only changing to disable depth buffering or to choose another type of depth buffering.

Note  The D3DZBUFFERTYPE enumerated type includes the D3DZB_USEW value to enable w-based depth comparisons on compliant hardware. For more information, see Depth Buffers.