Search Unity

A transparent shader writing to depth buffer?

Discussion in 'Shaders' started by TheGaul, Jan 21, 2020.

  1. TheGaul

    TheGaul

    Joined:
    Apr 15, 2019
    Posts:
    199
    Is it possible to write a transparent shader that also writes depth information? As far as I know transparent shaders don't write anything to the depth buffer.

    However, if I have another transparent water shader which is using the depth information for it's opacity then I'll need this. i.e. Think of a glass sphere, I want the back of the sphere to have transparency but write to the depth buffer. So the front of the sphere can use this depth information. Is this posisble?
     
  2. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,550
    It's possible, but you run into sorting issues then because semi-transparent objects won't always blend properly due to being depth-culled by the backface of your water you output.

    For a water shader, if it's a body of water resting on a surface, you don't need to do this, you can just sample the depth buffer the opaque objects wrote, as well as the depth of the front water surface fragment you're currently rendering and calculate the depth of that surface from the depth buffer to get your water "depth" to modulate by.

    If you're trying to do some falling water stuff or glass that appears to have light-falloff inside, then a common route is using a command buffer to render a "translucency" or "thickness" pass for those objects to use.
     
  3. TheGaul

    TheGaul

    Joined:
    Apr 15, 2019
    Posts:
    199
    Howabout if I render something invisible that just writes to depth buffer. So it's not transparent. It's just invisible?
     
  4. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,550
    It's the same issues, you just have a completely transparent object is all (which you can achieve by adding
    ColorMask 0
    ). Any triangles rendered after this object, behind it, won't show up, won't blend with it, unless those objects were rendered with ZTest off, in which case they would always draw over everything and that would be its own issue. Dealing with semi-transparency has always been a complicated issue in real-time/rasterized graphics.
     
  5. Brother_77

    Brother_77

    Joined:
    Feb 8, 2019
    Posts:
    233
  6. mabulous

    mabulous

    Joined:
    Jan 4, 2013
    Posts:
    198
    No problem at all. Just enable ZWrite in the shader. Just be sure you understand what you’re doing.