有时候,我们需要查看depth/stencil buffer的内容,比如上一章中,我们要查看stencil buffer,看看我们设置的stencil值是否起作用,这时就要输出depth/stencil buffer内容,但这些内容在gpu中,我们并不能直接查看,需要通过纹理copy,资源映射的方式,拷贝到system memory中才可以直接查看。
下面是输出depth/stencil buffer的代码,最终结果被输出到一个csv文件中,便于用excel 查看。该函数我加在了D3DClass类中:
bool D3DClass::SaveDepthStencilBuffer() { D3D11_TEXTURE2D_DESC dsDesc, destTexDesc; ID3D11Texture2D* destTex; HRESULT result;
if(m_depthStencilBuffer) { m_depthStencilBuffer->GetDesc(&dsDesc); // 使目的和源的描述一致 memcpy(&destTexDesc,&dsDesc,sizeof(destTexDesc)); destTexDesc.Usage = D3D11_USAGE_STAGING; destTexDesc.BindFlags = 0; destTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; result = m_device->CreateTexture2D(&destTexDesc, 0, &destTex); if(FAILED(result)) { HR(result); return false; }
//depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; m_deviceContext->CopyResource(destTex, m_depthStencilBuffer);
D3D11_MAPPED_SUBRESOURCE mappedResource;
result = m_deviceContext->Map(destTex, 0, D3D11_MAP_READ, 0, &mappedResource); if(FAILED(result)) { return false; }
FILE *fp = fopen("depth-stencil.csv","w");
const UINT WIDTH = destTexDesc.Width ; const UINT HEIGHT = destTexDesc.Height; //映射为32位的dword DWORD* pTexels = (DWORD*)mappedResource.pData; for( UINT row = 0; row < HEIGHT; row++ ) { UINT rowStart = row * mappedResource.RowPitch/sizeof(pTexels[0]); for( UINT col = 0; col < WIDTH; col++ ) { fprintf(fp,"%08x,",pTexels[rowStart + col]); } fprintf(fp,"\n"); }
fclose(fp); m_deviceContext->Unmap(destTex, 0); } return true; }
在GraphicClass类的Render函数中,调用该函数,我们就可以得到depth/stencil buffer的内容了。
本文参考了这篇blog。