Sampling a depth buffer (without a camera)

I’m using Graphics.ExecuteCommandBuffer() to draw some meshes to a custom low res render target, no cameras involved. The goal is to use the depth buffer to generate a depth pyramid for occlusion culling.

Except Unity just won’t let me get the render target depth buffer data no matter what. All CommandBuffer APIs I tried passing the RenderTexture.depthBuffer to end up using the color attachment instead. This includes trying to bind the depthBuffer as a shader texture parameter (global, or compute shader param), trying to pass it as source to CommandBuffer.CopyTexture().

Is there any trick to this that doesn’t involve setting up an actual camera to have Unity magically invoke CopyDepth to produce the _CameraDepthTexture?

Found it. Creating two separate RenderTextures, one for color and one for depth (colorFormat = RenderTextureFormat.Depth), both with depth bits set to zero, then binding them using:

cb.SetRenderTarget(colorTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare, depthTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);

…did the trick. The 2nd RenderTexture is used directly as depth attachment, so it can be used correctly by subsequent draw/dispatch calls.

Still angry that RenderTexture.depthBuffer did not work as advertised, and the “correct” way is the non-obvious one.

2 Likes