[我正在尝试编写一个着色器,用于计算线性比例从0到1的摄像机的网格深度。
最接近摄影机的顶点的值为0,而离摄影机最远的顶点的值为1。而且,如果旋转摄影机,则网格的深度值必须为0。适应变化。
这里是支持理解的图像。
从图像中,您可以看到最接近的顶点alpha设置为0,而最远的顶点的值为1。
即使旋转相机,我也想达到这种效果。
从此Shader - Calculate depth relative to Object,我可以找到最接近的顶点,但是我发现很难计算出距相机最远的网格点。
可以使用网格的边界框,但是如果旋转相机,则需要重新计算边界框。因此,我想知道使用现有矩阵是否可以使用任何解决方案?
PS:我正在尝试在three.js和Unity中实现此效果。
至少在three.js
中有一个官方演示会产生您想要的效果(只是反转的颜色表示最近的白色:https://threejs.org/examples/webgl_depth_texture
想法是将深度渲染到纹理,然后在自定义着色器中使用此信息。片段着色器中的相关代码为:
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() {
// readDepth() will return a linearized depth value that will be used to compute the fragment's color value
float depth = readDepth( tDepth, vUv );
gl_FragColor.rgb = 1.0 - vec3( depth ); // change this bit to invert colors
gl_FragColor.a = 1.0;
}
[perspectiveDepthToViewZ()
和viewZToOrthographicDepth()
是在packing
着色器块中定义的辅助函数,该函数包含在着色器源代码的顶部。
three.js R116