Z缓冲区导致事物无法绘制

时间:2011-12-09 20:22:37

标签: c++ directx-9

我在使用DirectX9时会遇到一些问题。

这是我的渲染功能:

void Render(GameWorld& world)
{
    DWORD BackgroundColour = 0x00102010;    

    g_pd3dDevice -> Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, BackgroundColour, 1.0f, 0);

    // Begin rendering the scene.
    if (SUCCEEDED(g_pd3dDevice -> BeginScene()))
    {
        world.draw();

        g_pd3dDevice -> EndScene();
    }

    // Present the backbuffer to the display.
    g_pd3dDevice -> Present(NULL, NULL, NULL, NULL);
}

我正在使用以下代码设置DirectX:

// Create the D3D object, return failure if this can't be done.
if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION))) return E_FAIL;

// Set up the structure used to create the D3DDevice
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

// Create the D3DDevice
if (FAILED(g_pD3D -> CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pd3dDevice)))
{
    return E_FAIL;
}

// Turn on the Z buffer
g_pd3dDevice -> SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);

g_pd3dDevice -> SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS);
g_pd3dDevice -> SetRenderState(D3DRS_ZWRITEENABLE, TRUE);

// Start with lighting off - we can add lights later.
g_pd3dDevice -> SetRenderState(D3DRS_LIGHTING, FALSE);

// Set transparencies
g_pd3dDevice -> SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
g_pd3dDevice -> SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
g_pd3dDevice -> SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
g_pd3dDevice -> SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);




// Set culling
g_pd3dDevice -> SetRenderState(D3DRS_CULLMODE,D3DCULL_CCW);

return S_OK;

实际上,这会绘制一个BackgroundColour屏幕,上面没有任何内容。

关闭Z缓冲区[即g_pd3dDevice - > SetRenderState(D3DRS_ZENABLE,D3DZB_FALSE);]所有内容都按照其“绘制”函数的调用顺序绘制。之后绘制的对象会遮挡先前绘制的对象。

我也尝试过这些改变:

g_pd3dDevice -> SetRenderState(D3DRS_ZFUNC, D3DCMP_GREATER);

g_pd3dDevice -> Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, BackgroundColour, 0.0f, 0);

现在效果是,首先绘制的对象会遮挡稍后绘制的对象,无论其空间位置如何。

我想要的效果是让近处的物体遮挡远处的物体。

任何人都可以对此有所了解。

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试删除这些行:

g_pd3dDevice -> SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);

g_pd3dDevice -> SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS);
g_pd3dDevice -> SetRenderState(D3DRS_ZWRITEENABLE, TRUE);

默认情况下启用z缓冲区,因此它应该可以工作 确保使用正确的WorldViewProjection矩阵转换对象 如果未渲染对象,请检查是否调用了World.draw()。也许BeginScene()失败了?