目前我正在绘制一个背景,然后是一个透明三角形进入模板缓冲区,然后是一个蓝色正方形,其中三角形不被绘制。我希望效果是一个蓝色的正方形,三角形孔暴露背景。但是我所得到的只是一个黑色的三角形。我认为我在广场上获得了预期的效果,但模板也适用于背景。
我的问题是如何调整以下代码以允许背景通过方形中的三角形孔显示?
static void Draw(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//big blue square
glColor3ub(0,255,255);
glBegin(GL_POLYGON);
glVertex3i(5, 5, 0);
glVertex3i(-5, 5, 0);
glVertex3i(-5, -5, 0);
glVertex3i(5, -5, 0);
glEnd();
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
/* transparent triangle */
glColor4ub(0.0f, 0.0f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex3i(-4, -4, 0);
glVertex3i(4, -4, 0);
glVertex3i(0, 4, 0);
glEnd();
glStencilFunc(GL_EQUAL, 1, 1);
glStencilOp(GL_INCR, GL_KEEP, GL_DECR);
glStencilFunc(GL_EQUAL, 2, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
/* blue square */
glColor3ub(0, 0, 200);
glBegin(GL_POLYGON);
glVertex3i(3, 3, 0);
glVertex3i(-3, 3, 0);
glVertex3i(-3, -3, 0);
glVertex3i(3, -3, 0);
glEnd();
if (doubleBuffer) {
glutSwapBuffers();
} else {
glFlush();
}
}
答案 0 :(得分:5)
问题一:绘制背景时要么先禁用模板测试,要么将模板功能切换到GL_ALWAYS以便碎片通过(我建议将其关闭)。然后你会设置两个不同的模板modi,但是你不会这样做,你打算做什么。所以这是改变:
glDisable(GL_STENCIL_TEST);
glStencilMask(0x0);
draw_background();
glEnable(GL_STENCIL_TEST);
glStencilMask(0x1);
glStencilFunc(GL_ALWAYS, 0x1, 0x1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glDepthMask(GL_FALSE);
draw_trangle();
glStencilFunc(GL_NOTEQUAL, 0x1, 0x1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_TRUE);
draw_blue_square();