启用深度测试时,OpenGL 不会丢弃我的片段

OpenGL is not discarding my fragments when depth testing is enabled

我正在用 wxWidgets 3.1.3 编写一个 OpenGL 渲染器。我可以看到隐藏在我的模型后面的碎片,但即使在它们应该被遮挡的时候也面向我。将我的片段着色器设置为显示深度表明深度设置正确,并且我有 znear=0.1 和 zfar=100。

这是我的 OpenGL 初始化代码:

this->m_glcontext = new wxGLContext(this);
this->SetCurrent(*this->m_glcontext);

std::remove(ENGINECANVAS_LOG_PATH);

glewExperimental = GL_TRUE;
glewInit();
glLoadIdentity();

glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);;

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);

glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);

glDebugMessageCallback(MessageCallback, 0);

this->Bind(wxEVT_PAINT, &EngineCanvas::Paint, this);
this->Render();

这是我的渲染循环:

glViewport(0, 0, (GLint)this->GetSize().x, (GLint)this->GetSize().y);

glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

this->m_active_camera->GenPerspMat((float)canvas->GetSize().x, (float)canvas->GetSize().y);
this->m_active_camera->GenViewMat();

for (size_t i = 0; i < this->models.size(); i++)
{
    this->models.at(i)->GenPosMat();

    this->models.at(i)->shader_program->Select(); //selects shader program

    this->m_active_camera->SetUniforms(this->models.at(i)->shader_program);
    this->models.at(i)->SetUniforms();
        glBindVertexArray(this->models.at(i)->vao);

    for (size_t j = 0; j < this->models.at(i)->vertex_buffers_count.size(); j++)
    {
        glBindBuffer(GL_ARRAY_BUFFER, this->models.at(i)->vertex_buffers.at(j));
        glDrawArrays(this->models.at(i)->triangle_mode, 0, this->models.at(i)->vertex_buffers_count.at(j));
    }
}

glFlush();
this->SwapBuffers();

片段着色器:

#version 400 core
layout(location = 0) out vec4 frag_out;
in vec3 vpos;

void main()
{
    frag_out = vec4(vec3(gl_FragCoord.z).xyz, 1.0f);
}

我的碎片在我的 NVIDIA 显卡上被丢弃了,但在两台不同的笔记本电脑和我的集成显卡上测试会产生这个错误。我的几何体本身渲染正确。回调没有返回任何错误(回调正在运行)。所有卡至少支持 OpenGL 4.0(在我的着色器和我的 GLCanvas args 中指定)。

感谢Rabbid76,

我需要在 wxGLCanvas 的参数中指定深度缓冲区。我需要使用 wxGLAttributes class 并传递它,而不是在提供整数数组的 wiki 示例中。

wxGLAttributes args;
args.PlatformDefaults().Depth(24).Stencil(8).RGBA().DoubleBuffer().EndList();

现在我知道去哪里找了,这在 wxWidgets 提供的金字塔示例中有记录。