Search code examples
three.jsdepth-buffer

Three.js render depth from texture


Is it possible to somehow render to depth buffer from pre-rendered texture?

I am pre-rendering scene like original resident evil games and I would like to apply both pre-rendered depth and color texture to screen.

I previously used technique to make simpler proxy scene for depth but I am wondering if there is a way to use precise pre rendered depth texture instead.


Solution

  • three.js provides a DepthTexture class which can be used to save the depth of a rendered scene into a texture. Typical use cases for such a texture are post processing effects like Depth-of-Field or SSAO.

    If you bind a depth texture to a shader, you can sample it like any other texture. However, the sampled depth value is sometimes converted to different representations for further processing. For instance you could compute the viewZ value (which is the z-distance between the rendered fragment and the camera) or convert between perspective and orthographic depth and vice versa. three.js provides helper functions for such tasks.

    The official depth texture example uses these helper functions in order to visualize the scene's depth texture. The important function is:

    float readDepth( sampler2D depthSampler, vec2 coord ) {
        float fragCoordZ = texture2D( depthSampler, coord ).x;
        float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
        return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
    }
    

    In the example, the resulting depth value is used to compute the final color of the fragment.