0
votes

I am trying to write a shader that computes the depth of a mesh from a camera with a linear scale from 0 to 1.

A vertex that is the closest to the camera would have a value of 0, whereas the vertex that is the farthest from the camera would have a value of 1. Also, if the camera is rotated, the depth values of the mesh must adapt to the change.

Here is an image to support the understanding.

Image Link

From the image, you can see that the closest vertices alpha is set to 0 as compared to the value of 1 for the farthest vertices.

I would like to achieve this effect, even when the camera is rotated.

From this Shader - Calculate depth relative to Object, I can find the closest vertex, but I am finding it difficult to calculate the farthest point of the mesh from the camera.

The bounding box of the mesh could be used, but if I rotate the camera, I need to recompute the bounding box. Hence, I would like to know if there is any solution that could be used using the matrices available?

PS: I am trying to implement this effect in both three.js and Unity.

1

1 Answers

0
votes

At least in three.js there is an official demo that produces your intended effect (just with inverted colors meaning white nearest): https://threejs.org/examples/webgl_depth_texture

The idea is to render the depth to a texture and then use this information in a custom shader. The relevant code in the fragment shader is:

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() and viewZToOrthographicDepth() are helper functions defined in the packing shader chunk which is included right at the top of the shader's source code.

three.js R116