OpenGL中的Alpha蒙版

5 投票
2 回答
4500 浏览
提问于 2025-04-15 18:27

我想在OpenGL中使用一个透明度遮罩,让白色(1)表示可见,黑色(0)表示隐藏。

我做的事情是,先通过glColorMask(False, False, False, True)在帧缓冲区的透明度部分写入一些东西(我用的是python),然后再在上面绘制一些图形,使用混合效果。

但是这并没有成功:我尝试把透明度缓冲区完全填充为0,然后绘制一些本应该不可见的图形。但它总是显示出来,透明度缓冲区完全被忽略了。

# Clear alpha buffer to 0, and clear color buffer.
# After this, the alpha buffer should probaby be filled with 0.
glClearColor(0, 0, 0, 0)
glClear(GL_COLOR_BUFFER_BIT)

# Disable blending.
glDisable(GL_BLEND)

# Disable color writing.
glColorMask(False, False, False, True)

# Set color to a white with alpha 0.
glColor4f(1, 1, 1, 0)

# Now draw a fullscreen quad.
# After this, the alpha buffer should really be filled with 0.
# Shouldn't it?
glBegin(GL_QUADS)
glVertex2f(0, 0)
glVertex2f(320, 0)
glVertex2f(320, 480)
glVertex2f(0, 480)
glEnd()

# Enable color writing.
glColorMask(True, True, True, True)

# Enable blending so that incoming fragments are multiplied
# by alpha values already in the buffer.
glEnable(GL_BLEND)
glBlendFunc(GL_DST_ALPHA, GL_ONE)

# Set color to a white with alpha 1.
glColor4f(1, 1, 1, 1)    

# Now draw a triangle.
# It should not be visible because alpha in framebuffer is 0
# and 0 * 1 = 0.
glBegin(GL_TRIANGLES)
glVertex2f(20, 50)
glVertex2f(300, 50)
glVertex2f(160, 210)
glEnd()

(是的,投影矩阵是正确的,所以我的屏幕范围是从0/0到320/240。)

这个三角形不应该可见,我到底哪里出错了?

2 个回答

0

使用 glAlphaFunc( GL_GREATER, 0.5 );

3

如果你还没有这样做的话,试着在创建你的GL上下文时请求一个alpha缓冲区

撰写回答