OpenGL-如何访问深度缓冲区值? -或:gl_FragCoord.z与纹理渲染深度 [英] OpenGL - How to access depth buffer values? - Or: gl_FragCoord.z vs. Rendering depth to texture
问题描述
我想访问像素着色器中当前处理的像素处的深度缓冲区值.
I want to access the depth buffer value at the currently processed pixel in a pixel shader.
我们如何实现这一目标?基本上,似乎有两个选择:
How can we achieve this goal? Basically, there seems to be two options:
- 将深度渲染为纹理.我们该怎么做?权衡是什么?
- 使用gl_FragCoord.z提供的值-但是:这是正确的值吗?
推荐答案
关于问题1:您不能直接从片段着色器的深度缓冲区中读取(除非有我不熟悉的最新扩展).您需要渲染到帧缓冲区对象(FBO).典型步骤:
On question 1: You can't directly read from the depth buffer in the fragment shader (unless there are recent extensions I'm not familiar with). You need to render to a Frame Buffer Object (FBO). Typical steps:
- 创建并绑定FBO.如果以前没有使用过FBO,请查找诸如
glGenFramebuffers
和glBindFramebuffer
之类的呼叫. - 创建要用作颜色缓冲区的纹理或渲染缓冲区,然后使用
glFramebufferTexture2D
或glFramebufferRenderbuffer
将其附加到FBO的GL_COLOR_ATTACHMENT0
附加点.如果您只关心此渲染过程的深度,则可以跳过此过程并在不使用颜色缓冲区的情况下进行渲染. - 创建深度纹理,并将其附加到FBO的
GL_DEPTH_ATTACHMENT
附加点. - 进行渲染以创建要使用的深度.
- 使用
glBindFramebuffer
切换回默认的帧缓冲区. - 将深度纹理绑定到片段着色器使用的采样器.
- 您的片段着色器现在可以从深度纹理采样.
- Create and bind an FBO. Look up calls like
glGenFramebuffers
andglBindFramebuffer
if you have not used FBOs before. - Create a texture or renderbuffer to be used as your color buffer, and attach it to the
GL_COLOR_ATTACHMENT0
attachment point of your FBO withglFramebufferTexture2D
orglFramebufferRenderbuffer
. If you only care about the depth from this rendering pass, you can skip this and render without a color buffer. - Create a depth texture, and attach it to the
GL_DEPTH_ATTACHMENT
attachment point of the FBO. - Do your rendering that creates the depth you want to use.
- Use
glBindFramebuffer
to switch back to the default framebuffer. - Bind your depth texture to a sampler used by your fragment shader.
- Your fragment shader can now sample from the depth texture.
关于问题2:gl_FragCoord.z
是着色器正在操作的片段的深度值,不是在片段位置的深度缓冲区的当前值.
On question 2: gl_FragCoord.z
is the depth value of the fragment that your shader is operating on, not the current value of the depth buffer at the fragment position.
这篇关于OpenGL-如何访问深度缓冲区值? -或:gl_FragCoord.z与纹理渲染深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!