WJ的Direct3D简明教程2:Render-To-Texture

转载请注明:来自http://blog.csdn.net/skyman_2001

Rendering to a texture is one of the advanced techniques in Direct3D. On the one hand it is simple, on the other hand it is powerful and enables numerous special effects, such as glow effect, environment mapping, shadow mapping, and many more. Rendering to a texture is simply an extension to rendering to a surface.
1. Create the texture:
LPDIRECT3DTEXTURE9 pRenderTexture = NULL;
LPDIRECT3DSURFACE9 pRenderSurface = NULL, pBackBuffer = NULL;

pDevice()->CreateTexture(256, // width
256, // height
1, // number of mip levels
D3DUSAGE_RENDERTARGET, // must be!
D3DFMT_R8G8B8, // format
D3DPOOL_DEFAULT, // memory pool(must be!)
&pRenderTexture,
NULL);
2. Get the surface:
In order to access the texture memory a surface object is needed, because a texture object in Direct3D always uses such a surface to store its data.

pRenderTexture->GetSurfaceLevel(0,&pRenderSurface); // top-level surface
3. Render to the texture:
pDevice()->GetRenderTarget(0,&pBackBuffer); // back buffer

// render-to-texture
// set new render target
pDevice()->SetRenderTarget(0,pRenderSurface);
//clear texture
pDevice()->Clear(0,
NULL,
D3DCLEAR_TARGET D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(255,255,255),
1.0f,
0);
// render the scene
pDevice()->BeginScene();
...
pDevice()->EndScene();
4. Render the final scene using the texture:
// render scene with texture
// set back buffer
pDevice()->SetRenderTarget(0,pBackBuffer);
pDevice()->Clear(0,
NULL,
D3DCLEAR_TARGET D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0,0,0),
1.0f,
0);
pDevice()->BeginScene();
// set rendered texture
pDevice()->SetTexture(0,pRenderTexture);
// render the final scene
...
pDevice()->EndScene();
pDevice()->Present(NULL,NULL,NULL,NULL);

Lastly, there are some restrictions you have to take care of: (1) the depth stencil surface must always be greater or equal to the size of the render target; (2) the format of the render target and the depth stencil surface must be compatible and the multisample type must be the same.

你可能感兴趣的:(text)