Setting Up a Projection Matrix

The following ProjectionMatrix sample function sets the front and back clipping planes, as well as the horizontal and vertical field of view angles. This code parallels the approach discussed in the What Is the Projection Transformation? topic. The fields of view should be less than pi radians.

```D3DXMATRIX
ProjectionMatrix(const float near_plane, // Distance to near clipping
// plane
const float far_plane,  // Distance to far clipping
// plane
const float fov_horiz,  // Horizontal field of view
const float fov_vert)   // Vertical field of view
{
float    h, w, Q;

w = (float)1/tan(fov_horiz*0.5);  // 1/tan(x) == cot(x)
h = (float)1/tan(fov_vert*0.5);   // 1/tan(x) == cot(x)
Q = far_plane/(far_plane - near_plane);

D3DXMATRIX ret;
ZeroMemory(&ret, sizeof(ret));

ret(0, 0) = w;
ret(1, 1) = h;
ret(2, 2) = Q;
ret(3, 2) = -Q*near_plane;
ret(2, 3) = 1;
return ret;
}   // End of ProjectionMatrix
```

After creating the matrix, set it with IDirect3DDevice9::SetTransform specifying D3DTS_PROJECTION.

The Direct3D extensions (D3DX) utility library provides the following functions to help you set up your projections matrix.