Search Unity

Get depth value of a transparent pixel / fragment

Discussion in 'Shaders' started by OCASM, Jan 23, 2017.

  1. OCASM

    OCASM

    Joined:
    Jan 12, 2011
    Posts:
    328
    Transparent objects don't write to the depth buffer so I'm wondering if it's possible to get the depth value some other way, maybe in the vertex shader? I want it so I can make a comparison with the regular depth texture and know if it's occluded by opaque objects or not.
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    What do you want to do with this information? The fact that it doesn't write it, doesn't mean it isn't calculated. It's usually still calculated for the z-test. So with normal z-testing, you know that it's not occluded by the fact it is rendered. If you want to do some output when it is occluded, you can just reverse the z-testing.
     
  3. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,755
    You can use UNITY_Z_0_FAR_FROM_CLIPSPACE(o.pos.z) (and maybe multiply it with *_ProjectionParams.w) in the transparent vertex shader.

    Not sure how you access that from your post FX though. Maybe you can write it out to a rendertexture using commandbuffers? I haven't used those at all though so I may be completely wrong.
     
  4. OCASM

    OCASM

    Joined:
    Jan 12, 2011
    Posts:
    328
    Thanks for your replies.

    This is the effect I'm doing:

    https://forum.unity3d.com/threads/screen-space-multiple-scattering.446647/#post-2920100

    The blur mask is created by re-rendering the scene with replacement shaders: alpha blended particles are white and opaque geometry is black. I'd like to avoid rendering opaque geometry and instead sample the depth buffer to check for occlusion. If the pixel is not occluded it's rendered as normal, if it's occluded it's rendered as transparent.
     
  5. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    That is possible of course, you can sample the depth buffer. Having the hardware do the z-rejection is a lot more efficient though. It's one of those things it's very good at.

    You could go for an if based on a sample from the depth buffer, but it would be more efficient to do two passes and let the hardware do a z-test. For the occluded part you can just reverse the z-test.
     
    OCASM likes this.