如何在Direct3D 11中启用深度测试?

时间:2014-06-21 22:24:04

标签: graphics 3d depth-buffer direct3d11

我正在尝试使用Direct3D 11 API,我对D3D不是很熟悉。我的项目总是使用OpenGL。 到目前为止,我设法绘制了简单的三角形。现在我想绘制一些更复杂的对象,但是有一个问题。我不知道如何启用深度测试(或者它是否使用完全不同的概念?)。我得到这样的东西:

depth problem

我像这样初始化D3D:

DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = hWnd;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.Windowed = true;

HRESULT result = D3D11CreateDeviceAndSwapChain(
    NULL,
    D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE,
    NULL,
    0,
    NULL,
    0,
    D3D11_SDK_VERSION,
    &swapChainDesc,
    &SwapChain,
    &Device,
    NULL,
    &DeviceContext);

if (result != S_OK)
    throw "Direct3D initialization error";

ID3D11Texture2D *backBufferTexture;
result = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&backBufferTexture);

if (result != S_OK)
{
        [error handling here]
}

result = Device->CreateRenderTargetView(backBufferTexture, NULL, &BackBuffer);
backBufferTexture->Release();

if (result != S_OK)
{
        [error handling here]
}

DeviceContext->OMSetRenderTargets(1, &BackBuffer, NULL);

之后是着色器加载,矩阵设置,顶点和索引缓冲区初始化。我打赌这里缺少一些东西,但不知道是什么。

1 个答案:

答案 0 :(得分:1)

好的,我发现了什么遗失了。需要显式创建深度缓冲区。有趣的是,深度和模板缓冲区合并到一个缓冲区中。

D3D11_TEXTURE2D_DESC depthTextureDesc;
ZeroMemory(&depthTextureDesc, sizeof(depthTextureDesc));
depthTextureDesc.Width = width;
depthTextureDesc.Height = height;
depthTextureDesc.MipLevels = 1;
depthTextureDesc.ArraySize = 1;
depthTextureDesc.SampleDesc.Count = 1;
depthTextureDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthTextureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;

ID3D11Texture2D *DepthStencilTexture;
result = Device->CreateTexture2D(&depthTextureDesc, NULL, &DepthStencilTexture);

if (result != S_OK) [error handling code]

D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
ZeroMemory(&dsvDesc, sizeof(dsvDesc));
dsvDesc.Format = depthTextureDesc.Format;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;

result = Device->CreateDepthStencilView(DepthStencilTexture, &dsvDesc, &DepthBuffer);
DepthStencilTexture->Release();

if (result != S_OK) [error handling code]

DeviceContext->OMSetRenderTargets(1, &BackBuffer, DepthBuffer);

当然,每帧都需要清除缓冲区。

DeviceContext->ClearDepthStencilView(DepthBuffer, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);