片段着色器中的丢弃是否会阻止修改模板缓冲区?

Does discard in fragment shader prevent modifications to stencil buffer?

我想 discard 在我的片段着色器中防止该片段写入模板缓冲区;我有一个在我的游戏中实现视觉效果的想法,如果我可以依赖 discard.

的行为,它可能是可以实现的

我的片段着色器没有做任何很花哨的事情;它只是对纹理进行采样,如果 alpha 接近 0,它 discard 否则它会写入。

void main()
{
    vec4 texColor = texture(tex, texCoord);
    if(texColor.a < 0.5f)
    {
        discard;
    }
    FragColor = texColor;
}

但是,it sounds like 我不能依赖 discard 阻止模板缓冲区写入:

If Stencil Testing is active, then discarded fragments can still affect the stencil buffer. The stencil test can modify the stencil buffer, even on a stencil or depth test failure. And since the stencil test happens before the depth test, the depth test failures cannot prevent the stencil test from updating the stencil buffer.

我确实需要在渲染时激活模板测试。我可以不依靠 discard 阻止写入模板缓冲区吗?

按照OpenGL操作顺序的正常规则,模板测试发生在片段着色器执行之后。因此,执行 discard 语句的片段着色器将阻止写入帧缓冲区图像。除了一个例外。

唯一的例外是可以通过 explicit request of the FS. If no such request is given, then things must proceed as defined by the original order (which is why using discard turns off early fragment tests as an optimization) 更改操作顺序。

有问题的段落是在讨论称为“模板测试”的操作部分如何包括潜在地更新模板缓冲区。也就是说,模板测试可以同时丢弃片段 根据丢弃的方式更改模板缓冲区的值。这与深度测试不同,深度测试如果失败,则永远不会更新深度缓冲区的值。