DirectX中,如何获取深度值,然后将它存储在一个txt文件中?其实只要修改两个地方:
第一个地方是:创建Direct3D设备时,将D3DPRESENT_PARAMETERS类型表示变量的AutoDepthStencilFormat设置为D3DFMT_D32F_LOCKABLE,代码如下:
D3DPRESENT_PARAMETERS d3dpp;
d3dpp.BackBufferWidth = width;
d3dpp.BackBufferHeight = height;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
d3dpp.MultiSampleQuality = 0;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hwnd;
d3dpp.Windowed = windowed;
d3dpp.EnableAutoDepthStencil = true;
d3dpp.AutoDepthStencilFormat = D3DFMT_D32F_LOCKABLE; // 16位总不行
d3dpp.Flags = 0;
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
第二个地方是:设置锁定缓存表面,并进行读写的代码:
// 获取深度模板表面
HRESULT hr = Device->GetDepthStencilSurface( &pZBuffer );
if ( FAILED( hr ) ) {
MessageBox( NULL, "GetDepthStencilSurface failure", 0, 0 );
}
// 打开文件
pFile = fopen( "ZBuffer.txt", "w" );
if ( pFile == NULL ) {
MessageBox( NULL, "shit", NULL, NULL);
}
// 获取表面特性
D3DSURFACE_DESC surfaceDesc;
pZBuffer->GetDesc( &surfaceDesc );
// 锁定表面
D3DLOCKED_RECT lockRect;
hr = pZBuffer->LockRect( &lockRect, NULL, D3DLOCK_READONLY );
if ( FAILED( hr ) ) {
MessageBox( NULL, "GetDepthStencilSurface", 0, 0 );
}
// 获取指向表面区域指针
float* pData = (float*)lockRect.pBits;
// 将深度信息输出到文件中
for (int y = 0; y < surfaceDesc.Height; ++y ) {
for (int x = 0; x < surfaceDesc.Width; ++x ) {
int index = y * lockRect.Pitch / 4 + x;
fprintf( pFile, "%f ", pData[index] );
}
fprintf( pFile,"\n");
}
// 解锁表面锁定
pZBuffer->UnlockRect();
// 释放接口和文件
pZBuffer->Release();
fclose( pFile );