How to copy depth buffer to CPU memory in DirectX?

Posted by Ashwin on Game Development See other posts from Game Development or by Ashwin
Published on 2013-08-02T08:50:57Z Indexed on 2013/08/02 16:07 UTC
Read the original article Hit count: 352

Filed under:

I have code in OpenGL that uses glReadPixels to copy the depth buffer to a CPU memory buffer:

glReadPixels(0, 0, w, h, GL_DEPTH_COMPONENT, GL_FLOAT, dbuf);

How do I achieve the same in DirectX?

I have looked at a similar question which gives the solution to copy the RGB buffer. I've tried to write similar code to copy the depth buffer:

IDirect3DSurface9* d3dSurface;
d3dDevice->GetDepthStencilSurface(&d3dSurface);

D3DSURFACE_DESC d3dSurfaceDesc;
d3dSurface->GetDesc(&d3dSurfaceDesc);

IDirect3DSurface9* d3dOffSurface;
d3dDevice->CreateOffscreenPlainSurface(
d3dSurfaceDesc.Width,
d3dSurfaceDesc.Height,
D3DFMT_D32F_LOCKABLE,
D3DPOOL_SCRATCH,
&d3dOffSurface,
NULL);

// FAILS: D3DERR_INVALIDCALL
D3DXLoadSurfaceFromSurface(
d3dOffSurface,
NULL,
NULL,
d3dSurface,
NULL,
NULL,
D3DX_FILTER_NONE,
0);

// Copy from offscreen surface to CPU memory ...

The code fails on the call to D3DXLoadSurfaceFromSurface. It returns the error value D3DERR_INVALIDCALL.

What is wrong with my code?

© Game Development or respective owner

Related posts about directx