Search Unity

Obtaining the rendered depth buffer (not the depth pass version)

Discussion in 'Shaders' started by Alex_May, Jan 15, 2021.

  1. Alex_May

    Alex_May

    Joined:
    Dec 29, 2013
    Posts:
    198
    I have objects that I do not want to cast shadows and therefore don't render in the depth pass. However, I do want to use the depth buffer after they have been rendered in the opaque pass so I can process the data in my fog image effect. How do I get access to the depth buffer that was rendered in the opaque pass?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    The TLDR version is... you don't. Unity doesn't expose any way to access let alone resolve a camera's default depth buffer to a texture that can be read by a shader. You can assign a render texture as a camera's render target, and then you have access to both the
    .colorBuffer
    and
    .depthBuffer
    of that render texture, but there's still no way to assign the depth buffer to anything so that it can be read directly, only to be used as the current render target's depth.

    A few options you have:
    1. Have them render to the depth pass, but disable shadow casting if you don't want to cast shadows. This is an option on the renderer component itself. There are also (hacky) ways to have a shader that renders to the camera depth texture but not to shadows.
    2. Calculate the effect in the object's shader instead of doing it in post. A good example of this would be fog.
    3. Render the depth for these objects separately to another render texture. It's even possible to render directly to the camera depth texture if you want to modify it after shadows have been done.
     
    Alex_May likes this.
  3. Alex_May

    Alex_May

    Joined:
    Dec 29, 2013
    Posts:
    198
    Thank you. I feared this was the case. Can it be grabbed with a command buffer? I will see i what the shadow casting mode does for this (I'm drawing them instanced, and they're quite dense billboards in the background which is why I don't want them casting shadows)

    Quite apart from the image effect problem, right now it seems to me that I'm drawing many things twice for no reason. I think the volumetric fog asset I'm using requires the depth pass, but it feels like all that could be done after the opaque pass, when there's a perfectly good depth buffer to use for free, as it were.
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    You can do even less to the depth buffer with a command buffer.

    If you really want to avoid rendering your objects multiple times, you may want to look into using deferred rendering. And, again, disable the shadow casting on the component (or draw commands if you're not using a component).
     
    Alex_May likes this.