1

我编写了一个程序来绘制一个简单的三角形,我使用 VAO、VBO 和 GLSL 着色器。结果如下:

在此处输入图像描述

但是如果我启用深度测试:</p>

glEnable(GL_DEPTH_TEST)

窗口中什么也没有出现。

现在我发布我的程序的一些代码:

float positionData[] = {
    -0.8f, -0.8f, 0.0f,
    0.8f, -0.8f, 0.0f,
    0.0f,  0.8f, 0.0f };
float colorData[] = {
        1.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 1.0f };
void initVBO()
{
    // Create and populate the buffer objects
    GLuint vboHandles[2];
    glGenBuffers(2, vboHandles);
    GLuint positionBufferHandle = vboHandles[0];
    GLuint colorBufferHandle = vboHandles[1];

    glBindBuffer(GL_ARRAY_BUFFER,positionBufferHandle);
    glBufferData(GL_ARRAY_BUFFER,9 * sizeof(float),
        positionData,GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER,colorBufferHandle);
    glBufferData(GL_ARRAY_BUFFER,9 * sizeof(float),
        colorData,GL_STATIC_DRAW);

    glGenVertexArrays(1,&vaoHandle);
    glBindVertexArray(vaoHandle);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL );

    glBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);
    glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL );
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glBindVertexArray(vaoHandle);
    glDrawArrays(GL_TRIANGLES,0,3);
    glBindVertexArray(0);

    glutSwapBuffers();
}

我的问题是:为什么在启用深度测试后无法绘制三角形?

4

2 回答 2

5

There are multiple (types of) buffers used when rendering, typically. One is the color buffer, which contains the pixel data in some pixel format (IE: RGB with 8 bits for each color channel). Another typical buffer used is the depth buffer. Depth testing and writing to the depth buffer are two different things. Depth testing checks the depth value from a pixel against the depth value of the associated pixel(s) in the depth buffer and decides whether to accept or reject the pixel/fragment. Depth writing actually writes that value to a buffer, such as the depth buffer.

您的程序可能会写入深度缓冲区并测试深度缓冲区,但您永远不会清除深度缓冲区,因此它认为,即使颜色缓冲区已被清除,已经有写入它的东西在/在您尝试写入的像素的前面(或任何配置),因此它会拒绝它们。

通常,每帧清除深度缓冲区。您可以通过将GL_DEPTH_BUFFER_BIT标志传递给glClear.

于 2012-09-18T03:53:40.803 回答
4

您还需要显式清除深度缓冲区:

        glClear(GL_COLOR_BUFFER_BIT |
                GL_DEPTH_BUFFER_BIT)
于 2012-09-18T02:49:26.830 回答