OpenGL-如何访问深度缓冲区值? -或:gl_FragCoord.z与纹理渲染深度 [英] OpenGL - How to access depth buffer values? - Or: gl_FragCoord.z vs. Rendering depth to texture

查看:594
本文介绍了OpenGL-如何访问深度缓冲区值? -或:gl_FragCoord.z与纹理渲染深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问像素着色器中当前处理的像素处的深度缓冲区值.

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:

  1. 将深度渲染为纹理.我们该怎么做?权衡是什么?
  2. 使用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:

  1. 创建并绑定FBO.如果以前没有使用过FBO,请查找诸如glGenFramebuffersglBindFramebuffer之类的呼叫.
  2. 创建要用作颜色缓冲区的纹理或渲染缓冲区,然后使用glFramebufferTexture2DglFramebufferRenderbuffer将其附加到FBO的GL_COLOR_ATTACHMENT0附加点.如果您只关心此渲染过程的深度,则可以跳过此过程并在不使用颜色缓冲区的情况下进行渲染.
  3. 创建深度纹理,并将其附加到FBO的GL_DEPTH_ATTACHMENT附加点.
  4. 进行渲染以创建要使用的深度.
  5. 使用glBindFramebuffer切换回默认的帧缓冲区.
  6. 将深度纹理绑定到片段着色器使用的采样器.
  7. 您的片段着色器现在可以从深度纹理采样.
  1. Create and bind an FBO. Look up calls like glGenFramebuffers and glBindFramebuffer if you have not used FBOs before.
  2. 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 with glFramebufferTexture2D or glFramebufferRenderbuffer. If you only care about the depth from this rendering pass, you can skip this and render without a color buffer.
  3. Create a depth texture, and attach it to the GL_DEPTH_ATTACHMENT attachment point of the FBO.
  4. Do your rendering that creates the depth you want to use.
  5. Use glBindFramebuffer to switch back to the default framebuffer.
  6. Bind your depth texture to a sampler used by your fragment shader.
  7. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆