OpenGL:四边形似乎没有正确剔除

OpenGL: Quads seemingly not culled properly

我构建了一个简单的场景,如下所示:

问题是,蓝色的形状比红色的低,但不知何故渗出。当我像下面这样旋转它时它看起来很合适:

根据我的搜索,这可能与发送顶点的顺序有关,这是我对它们的定义:

Shape* Obj1 = new Quad(Vec3(-5.0, 5.0, 0.0), Vec3(5.0, 5.0, 0.0), Vec3(5.0, 5.0, -10.0), Vec3(-5.0, 5.0, -10.0));
Shape* Obj2 = new Quad(Vec3(-5.0, 3.0, 0.0), Vec3(5.0, 3.0, 0.0), Vec3(5.0, 3.0, -10.0), Vec3(-5.0, 3.0, -10.0));

Vec3 class 只包含 3 个 x,y,z 坐标。我将这些 Vec3 classes 添加到一个向量中,并在我想绘制时遍历它们,如下所示:

glBegin(GL_QUADS);
    for (auto it = vertex_list.begin(); it != vertex_list.end(); ++it)
        glVertex3d(it->get_x(), it->get_y(), it->get_z());
glEnd();

最后,我的设置:

glEnable(GL_ALPHA_TEST | GL_DEPTH_TEST | GL_CULL_FACE);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glAlphaFunc(GL_GREATER, 0.0f);
glViewport(0, 0, WINDOW_X, WINDOW_Y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0f, 300.0);
// camera origin xyz, point to look at xyz, camera rot xyz
gluLookAt(10, 10, -20, 2.5, 2.5, -10, 0, 1, 0);

您应该分别启用深度测试、面部剔除和 alpha 测试。

glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);

它们不是旗帜。你不能那样使用它们。

参见glEnable

glEnable — enable or disable server-side GL capabilities

void glEnable(GLenum cap);

cap Specifies a symbolic constant indicating a GL capability.

这意味着 glEnable 的参数是一个常量而不是一组位,并且 GL_ALPHA_TESTGL_DEPTH_TESTGL_CULL_FACE 是符号常量而不是位位设置。

像这样更改您的代码:

glEnable(GL_ALPHA_TEST);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);


OpenGL Specifiction - 17.3.4 Depth Buffer Test, p. 500:

17.3.4 Depth Buffer Test

The depth buffer test discards the incoming fragment if a depth comparison fails. The comparison is enabled or disabled with the generic Enable and Disable commands using target DEPTH_TEST.

参见OpenGL Specifiction - 14.6.1 Basic Polygon Rasterization, p. 473

Culling is enabled or disabled by calling Enable or Disable with target CULL_FACE.