Creating and Deleting Viewports

A viewport is the surface rectangle into which a three-dimensional scene is projected. A Direct3D viewport object is used to specify the following:

·The screen-space viewport to which the rendering will be confined.

·The post-transform clip volume, the contents of which will be mapped in to the viewport. (This is also known as the "window" in a "window-to-viewport transform," in standard computer-graphics terminology.)

·The background material and texture to which the viewport should be cleared.

·The background depth buffer used to initialize the z-buffer before rendering the scene.

The IDirect3DViewport2 interface has two ways of specifying a viewport. The D3DVIEWPORT2 structure is specified by the new methods in IDirect3DViewport2. This is similar to the D3DVIEWPORT structure except that it allows a better clip-volume definition. The new viewport structure is recommended for all DirectX 5 applications.

The first thing to do when creating a viewport is to create a D3DVIEWPORT2 structure and a pointer to a viewport object:

LPDIRECT3DVIEWPORT2 lpD3DViewport;

D3DVIEWPORT2 viewData;

Next, fill in the viewport structure:

float aspect = (float)width/height; // aspect ratio of surface

memset(&viewData, 0, sizeof(D3DVIEWPORT2));

viewData.dwSize = sizeof(D3DVIEWPORT2);

viewData.dwX = 0;

viewData.dwY = 0;

viewData.dwWidth = width;

viewData.dwHeight = height;

viewData.dvClipX = -1.0f;

viewData.dvClipY = aspect;

viewData.dvClipWidth = 2.0f;

viewData.dvClipHeight = 2.0f * aspect;

viewData.dvMinZ = 0.0f;

viewData.dvMaxZ = 1.0f;

(You can find a discussion of setting the clipping volume in this structure in the reference material for D3DVIEWPORT2.)

After filling in this structure, call the IDirect3D2::CreateViewport method to create the viewport object. For this you need a valid LPDIRECT3D2 pointer, shown in the following example as lpD3D2.

if ((err = lpD3D2->CreateViewport(&lpD3DViewport2, NULL)) != D3D_OK) {

return err;

}

Now you can call the IDirect3DDevice2::AddViewport method to add the newly created viewport object to the device. For this you need a valid LPDIRECT3DDEVICE2 pointer, shown in the following example as lpD3DDevice2.

if ((err = d3dapp->lpD3DDevice2->AddViewport(lpD3DViewport2)) != D3D_OK) {

return err;

}

Finally, call the IDirect3DViewport2::SetViewport2 method to associate the D3DVIEWPORT2 structure whose values you have already filled out with the new viewport object.

if ((err = lpD3DViewport2->SetViewport2(&viewData)) != D3D_OK) {

return err;

}

At this point you have a working viewport. If you need to make changes to the viewport values, simply update the values in the D3DVIEWPORT2 structure and call IDirect3DViewport2::SetViewport2 again.

When you are ready to delete the viewport, first delete any lights and materials associated with it and then call the IDirect3DViewport2::Release method.

lpD3DViewport2->Release();