给定一个 WebGL 场景(从 THREE.js 创建),您将如何从给定帧缓冲区的 DEPTH_ATTACHMENT
访问浮点值(作为 WebGL 上下文外部的数据数组)已使用 framebufferTexture2D
绑定(bind)到纹理。
到目前为止,我已经收集了一个解决方案,即使用自定义着色器覆盖将场景渲染到纹理目标,该覆盖访问深度纹理信息,然后将其编码为 RGB 格式。使用的代码与此处找到的 THREE.js 示例非常相似:Depth-Texture-Example .
#include <packing>
varying vec2 vUv;
uniform sampler2D tDiffuse;
uniform sampler2D tDepth;
uniform float cameraNear;
uniform float cameraFar;
float readDepth (sampler2D depthSampler, vec2 coord) {
float fragCoordZ = texture2D(depthSampler, coord).x;
float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
}
void main() {
vec3 diffuse = texture2D(tDiffuse, vUv).rgb;
float depth = readDepth(tDepth, vUv);
gl_FragColor.rgb = vec3(depth);
gl_FragColor.a = 1.0;
}
渲染完成后,我可以使用 readPixels 将特定像素读入数组。然而,在给定 vec3(float) = vec3(float, float, float) 的情况下,此选项的精度极低,仅限于 256 个离散值。有没有办法从这种特定方法或替代方法中获得更高的精度?
最终我想要的是在 WebGL 上下文之外以高效的方式访问深度缓冲区作为浮点值数组。我有一个自定义光栅器,可以创建一个相当好的深度缓冲区,但我不想浪费任何时间重做已经完成的步骤。
最佳答案
一种可能性是对 32 位 IEEE 754 的 24 个有效位进行编码浮点值到 vec3
:
vec3 PackDepth(float depth)
{
float depthVal = depth * (256.0*256.0*256.0 - 1.0) / (256.0*256.0*256.0);
vec4 encode = fract(depthVal * vec4(1.0, 256.0, 256.0*256.0, 256.0*256.0*256.0));
return encode.xyz - encode.yzw / 256.0 + 1.0/512.0;
}
R
、G
和 B
颜色 channel 可以解码到 [0.0, 1.0] 范围内的深度,如下所示:
depth = (R*256.0*256.0 + G*256.0 + B) / (256.0*256.0*256.0 - 1.0);
关于javascript - 如何在 WebGL 上下文之外访问深度缓冲区的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47945303/