在GLSL着色器中采样类型GL_UNSIGNED_SHORT的GL_DEPTH_COMPONENTs

问题描述

我可以访问深度相机的输出。我想使用计算着色器在opengl中对此进行可视化。

深度进给作为框架给出,我提前知道宽度和高度。如何采样纹理并在着色器中检索深度值?这可能吗?我已阅读过OpenGl类型here,但在未签名的短裤上找不到任何东西,因此开始担心。有什么解决方法吗?

我当前的计算着色器

#version 430
layout(local_size_x = 1,local_size_y = 1) in;
layout(rgba32f,binding = 0) uniform image2D img_output;


uniform float width;
uniform float height;
uniform sampler2D depth_Feed;

void main() {
  // get index in global work group i.e x,y position
  vec2 sample_coords = ivec2(gl_GlobalInvocationID.xy) / vec2(width,height);

  float visibility = texture(depth_Feed,sample_coords).r;

  vec4 pixel = vec4(1.0,1.0,0.0,visibility);

  // output to a specific pixel in the image
  imageStore(img_output,ivec2(gl_GlobalInvocationID.xy),pixel);
}

深度纹理定义如下:

glTexImage2D(GL_TEXTURE_2D,GL_DEPTH_COMPONENT16,width,height,GL_DEPTH_COMPONENT,GL_UNSIGNED_SHORT,nullptr);

当前,我的代码显示一个纯黄色的屏幕。

解决方法

如果使用透视投影,则深度值不是线性的。参见LearnOpenGL - Depth testing

如果所有深度值都接近0.0,则使用以下表达式:

vec4 pixel = vec4(vec3(visibility),1.0);

然后所有像素几乎都显示为黑色。实际上,像素并非完全是黑色的,但是差异几乎没有引起注意。

当远平面“太”远时会发生这种情况。为了验证您可以计算1.0 - visibility的功效,以使不同的深度值可识别。例如:

float exponent = 5.0;
vec4 pixel = vec4(vec3(pow(1.0-visibility,exponent)),1.0);

如果需要更复杂的解决方案,可以按照How to render depth linearly in modern OpenGL with gl_FragCoord.z in fragment shader?的答案中的说明线性化深度值。

请注意,为获得令人满意的可视化效果,应使用深度缓冲区的整个范围([0.0,1.0])。几何必须在近平面和远平面之间,但是请尝试将近平面和远平面移到尽可能靠近几何的位置。